Debian Codegraph @

testing/web-platform/tests/tools/manifest/sourcefile.py

raw
1 import hashlib
2 import re
3 import os
4 from collections import deque
5 from fnmatch import fnmatch
6 from io import BytesIO
7 from typing import (Any, BinaryIO, Callable, Deque, Dict, Iterable, List,
8 Optional, Pattern, Set, Text, Tuple, TypedDict, Union)
9 from urllib.parse import parse_qs, urlparse, urljoin
10
11 try:
12 from xml.etree import cElementTree as ElementTree
13 except ImportError:
14 from xml.etree import ElementTree as ElementTree # type: ignore
15
16 import html5lib
17
18 from . import XMLParser
19 from .item import (ConformanceCheckerTest,
20 CrashTest,
21 ManifestItem,
22 ManualTest,
23 PrintRefTest,
24 RefTest,
25 SpecItem,
26 SupportFile,
27 TestharnessTest,
28 VisualTest,
29 WebDriverSpecTest)
30 from .utils import cached_property
31
32 # Cannot do `from ..metadata.webfeatures.schema import WEB_FEATURES_YML_FILENAME`
33 # because relative import beyond toplevel throws *ImportError*!
34 from metadata.webfeatures.schema import WEB_FEATURES_YML_FILENAME # type: ignore
35
36 wd_pattern = "*.py"
37 js_meta_re = re.compile(br"//\s*META:\s*(\w*)=(.*)$")
38 python_meta_re = re.compile(br"#\s*META:\s*(\w*)=(.*)$")
39
40 reference_file_re = re.compile(r'(^|[\-_])(not)?ref[0-9]*([\-_]|$)')
41
42 space_chars: Text = "".join(html5lib.constants.spaceCharacters) # type: ignore[attr-defined]
43
44
45 def replace_end(s: Text, old: Text, new: Text) -> Text:
46 """
47 Given a string `s` that ends with `old`, replace that occurrence of `old`
48 with `new`.
49 """
50 assert s.endswith(old)
51 return s[:-len(old)] + new
52
53
54 def read_script_metadata(f: BinaryIO, regexp: Pattern[bytes]) -> Iterable[Tuple[Text, Text]]:
55 """
56 Yields any metadata (pairs of strings) from the file-like object `f`,
57 as specified according to a supplied regexp.
58
59 `regexp` - Regexp containing two groups containing the metadata name and
60 value.
61 """
62 for line in f:
63 assert isinstance(line, bytes), line
64 m = regexp.match(line)
65 if not m:
66 break
67
68 yield (m.groups()[0].decode("utf8"), m.groups()[1].decode("utf8"))
69
70
71 class VariantData(TypedDict, total=False):
72 suffix: str
73 force_https: bool
74 longhand: Set[str]
75
76
77 _any_variants: Dict[Text, VariantData] = {
78 "window": {"suffix": ".any.html"},
79 "window-module": {},
80 "serviceworker": {"force_https": True},
81 "serviceworker-module": {"force_https": True},
82 "sharedworker": {},
83 "sharedworker-module": {},
84 "dedicatedworker": {"suffix": ".any.worker.html"},
85 "dedicatedworker-module": {"suffix": ".any.worker-module.html"},
86 "worker": {"longhand": {"dedicatedworker", "sharedworker", "serviceworker"}},
87 "worker-module": {},
88 "shadowrealm-in-window": {},
89 "shadowrealm-in-shadowrealm": {},
90 "shadowrealm-in-dedicatedworker": {},
91 "shadowrealm-in-sharedworker": {},
92 "shadowrealm-in-serviceworker": {
93 "force_https": True,
94 "suffix": ".https.any.shadowrealm-in-serviceworker.html",
95 },
96 "shadowrealm-in-audioworklet": {
97 "force_https": True,
98 "suffix": ".https.any.shadowrealm-in-audioworklet.html",
99 },
100 "shadowrealm": {"longhand": {
101 "shadowrealm-in-window",
102 "shadowrealm-in-shadowrealm",
103 "shadowrealm-in-dedicatedworker",
104 "shadowrealm-in-sharedworker",
105 "shadowrealm-in-serviceworker",
106 "shadowrealm-in-audioworklet",
107 }},
108 "jsshell": {"suffix": ".any.js"},
109 }
110
111
112 def get_any_variants(item: Text) -> Set[Text]:
113 """
114 Returns a set of variants (strings) defined by the given keyword.
115 """
116 assert isinstance(item, str), item
117
118 variant = _any_variants.get(item, None)
119 if variant is None:
120 return set()
121
122 return variant.get("longhand", {item})
123
124
125 def get_default_any_variants() -> Set[Text]:
126 """
127 Returns a set of variants (strings) that will be used by default.
128 """
129 return set({"window", "dedicatedworker"})
130
131
132 def parse_variants(value: Text) -> Set[Text]:
133 """
134 Returns a set of variants (strings) defined by a comma-separated value.
135 """
136 assert isinstance(value, str), value
137
138 if value == "":
139 return get_default_any_variants()
140
141 globals = set()
142 for item in value.split(","):
143 item = item.strip()
144 globals |= get_any_variants(item)
145 return globals
146
147
148 def global_suffixes(value: Text) -> Set[Tuple[Text, bool]]:
149 """
150 Yields tuples of the relevant filename suffix (a string) and whether the
151 variant is intended to run in a JS shell, for the variants defined by the
152 given comma-separated value.
153 """
154 assert isinstance(value, str), value
155
156 rv = set()
157
158 global_types = parse_variants(value)
159 for global_type in global_types:
160 variant = _any_variants[global_type]
161 suffix = variant.get("suffix", ".any.%s.html" % global_type)
162 rv.add((suffix, global_type == "jsshell"))
163
164 return rv
165
166
167 def global_variant_url(url: Text, suffix: Text) -> Text:
168 """
169 Returns a url created from the given url and suffix (all strings).
170 """
171 url = url.replace(".any.", ".")
172 # If the url must be loaded over https, ensure that it will have
173 # the form .https.any.js
174 if ".https." in url and suffix.startswith(".https."):
175 url = url.replace(".https.", ".")
176 elif ".h2." in url and suffix.startswith(".h2."):
177 url = url.replace(".h2.", ".")
178 return replace_end(url, ".js", suffix)
179
180
181 def _parse_html(f: BinaryIO) -> ElementTree.Element:
182 return html5lib.parse(f, treebuilder="etree", useChardet=False)
183
184 def _parse_xml(f: BinaryIO) -> ElementTree.Element:
185 try:
186 # raises ValueError with an unsupported encoding,
187 # ParseError when there's an undefined entity
188 return ElementTree.parse(f).getroot()
189 except (ValueError, ElementTree.ParseError):
190 f.seek(0)
191 return ElementTree.parse(f, XMLParser.XMLParser()).getroot() # type: ignore
192
193
194 class SourceFile:
195 parsers: Dict[Text, Callable[[BinaryIO], ElementTree.Element]] = {"html":_parse_html,
196 "xhtml":_parse_xml,
197 "svg":_parse_xml}
198
199 root_dir_non_test = {"common"}
200
201 dir_non_test = {"resources",
202 "support",
203 "tools"}
204
205 dir_path_non_test: Set[Tuple[Text, ...]] = {("css21", "archive"),
206 ("css", "CSS2", "archive"),
207 ("css", "common")}
208
209 def __init__(self, tests_root: Text,
210 rel_path: Text,
211 url_base: Text,
212 hash: Optional[Text] = None,
213 contents: Optional[bytes] = None) -> None:
214 """Object representing a file in a source tree.
215
216 :param tests_root: Path to the root of the source tree
217 :param rel_path_str: File path relative to tests_root
218 :param url_base: Base URL used when converting file paths to urls
219 :param contents: Byte array of the contents of the file or ``None``.
220 """
221
222 assert not os.path.isabs(rel_path), rel_path
223 if os.name == "nt":
224 # do slash normalization on Windows
225 rel_path = rel_path.replace("/", "\\")
226
227 dir_path, filename = os.path.split(rel_path)
228 name, ext = os.path.splitext(filename)
229
230 type_flag = None
231 if "-" in name:
232 type_meta = name.rsplit("-", 1)[1].split(".")
233 type_flag = type_meta[0]
234 meta_flags = type_meta[1:]
235 else:
236 meta_flags = name.split(".")[1:]
237
238 self.tests_root: Text = tests_root
239 self.rel_path: Text = rel_path
240 self.dir_path: Text = dir_path
241 self.filename: Text = filename
242 self.name: Text = name
243 self.ext: Text = ext
244 self.type_flag: Optional[Text] = type_flag
245 self.meta_flags: Union[List[bytes], List[Text]] = meta_flags
246 self.url_base = url_base
247 self.contents = contents
248 self.items_cache: Optional[Tuple[Text, List[ManifestItem]]] = None
249 self._hash = hash
250
251 def __getstate__(self) -> Dict[str, Any]:
252 # Remove computed properties if we pickle this class
253 rv = self.__dict__.copy()
254
255 if "__cached_properties__" in rv:
256 cached_properties = rv["__cached_properties__"]
257 rv = {key:value for key, value in rv.items() if key not in cached_properties}
258 del rv["__cached_properties__"]
259 return rv
260
261 def name_prefix(self, prefix: Text) -> bool:
262 """Check if the filename starts with a given prefix
263
264 :param prefix: The prefix to check"""
265 return self.name.startswith(prefix)
266
267 def is_dir(self) -> bool:
268 """Return whether this file represents a directory."""
269 if self.contents is not None:
270 return False
271
272 return os.path.isdir(self.rel_path)
273
274 def open(self) -> BinaryIO:
275 """
276 Return either
277 * the contents specified in the constructor, if any;
278 * a File object opened for reading the file contents.
279 """
280 if self.contents is not None:
281 file_obj: BinaryIO = BytesIO(self.contents)
282 else:
283 file_obj = open(self.path, 'rb')
284 return file_obj
285
286 @cached_property
287 def rel_path_parts(self) -> Tuple[Text, ...]:
288 return tuple(self.rel_path.split(os.path.sep))
289
290 @cached_property
291 def path(self) -> Text:
292 return os.path.join(self.tests_root, self.rel_path)
293
294 @cached_property
295 def rel_url(self) -> Text:
296 assert not os.path.isabs(self.rel_path), self.rel_path
297 return self.rel_path.replace(os.sep, "/")
298
299 @cached_property
300 def url(self) -> Text:
301 return urljoin(self.url_base, self.rel_url)
302
303 @cached_property
304 def hash(self) -> Text:
305 if not self._hash:
306 with self.open() as f:
307 content = f.read()
308
309 data = b"".join((b"blob ", b"%d" % len(content), b"\0", content))
310 self._hash = str(hashlib.sha1(data).hexdigest())
311
312 return self._hash
313
314 def in_non_test_dir(self) -> bool:
315 if self.dir_path == "":
316 return True
317
318 parts = self.rel_path_parts
319
320 if (parts[0] in self.root_dir_non_test or
321 any(item in self.dir_non_test for item in parts) or
322 any(parts[:len(path)] == path for path in self.dir_path_non_test)):
323 return True
324 return False
325
326 def in_conformance_checker_dir(self) -> bool:
327 return self.rel_path_parts[0] == "conformance-checkers"
328
329 @property
330 def name_is_non_test(self) -> bool:
331 """Check if the file name matches the conditions for the file to
332 be a non-test file"""
333 return (self.is_dir() or
334 self.name_prefix("MANIFEST") or
335 self.filename == "META.yml" or
336 self.filename == WEB_FEATURES_YML_FILENAME or
337 self.filename.startswith(".") or
338 self.filename.endswith(".headers") or
339 self.filename.endswith(".ini") or
340 self.in_non_test_dir())
341
342 @property
343 def name_is_conformance(self) -> bool:
344 return (self.in_conformance_checker_dir() and
345 self.type_flag in ("is-valid", "no-valid"))
346
347 @property
348 def name_is_conformance_support(self) -> bool:
349 return self.in_conformance_checker_dir()
350
351 @property
352 def name_is_manual(self) -> bool:
353 """Check if the file name matches the conditions for the file to
354 be a manual test file"""
355 return self.type_flag == "manual"
356
357 @property
358 def name_is_visual(self) -> bool:
359 """Check if the file name matches the conditions for the file to
360 be a visual test file"""
361 return self.type_flag == "visual"
362
363 @property
364 def name_is_multi_global(self) -> bool:
365 """Check if the file name matches the conditions for the file to
366 be a multi-global js test file"""
367 return "any" in self.meta_flags and self.ext == ".js"
368
369 @property
370 def name_is_worker(self) -> bool:
371 """Check if the file name matches the conditions for the file to
372 be a worker js test file"""
373 return "worker" in self.meta_flags and self.ext == ".js"
374
375 @property
376 def name_is_window(self) -> bool:
377 """Check if the file name matches the conditions for the file to
378 be a window js test file"""
379 return "window" in self.meta_flags and self.ext == ".js"
380
381 @property
382 def name_is_webdriver(self) -> bool:
383 """Check if the file name matches the conditions for the file to
384 be a webdriver spec test file"""
385 # wdspec tests are in subdirectories of /webdriver excluding __init__.py
386 # files.
387 rel_path_parts = self.rel_path_parts
388 return (((rel_path_parts[0] == "webdriver" and len(rel_path_parts) > 1) or
389 (rel_path_parts[:2] == ("infrastructure", "webdriver") and
390 len(rel_path_parts) > 2)) and
391 self.filename not in ("__init__.py", "conftest.py") and
392 fnmatch(self.filename, wd_pattern))
393
394 @property
395 def name_is_reference(self) -> bool:
396 """Check if the file name matches the conditions for the file to
397 be a reference file (not a reftest)"""
398 return "/reference/" in self.url or bool(reference_file_re.search(self.name))
399
400 @property
401 def name_is_crashtest(self) -> bool:
402 return (self.markup_type is not None and
403 (self.type_flag == "crash" or "crashtests" in self.dir_path.split(os.path.sep)))
404
405 @property
406 def name_is_tentative(self) -> bool:
407 """Check if the file name matches the conditions for the file to be a
408 tentative file.
409
410 See https://web-platform-tests.org/writing-tests/file-names.html#test-features"""
411 return "tentative" in self.meta_flags or "tentative" in self.dir_path.split(os.path.sep)
412
413 @property
414 def name_is_print_reftest(self) -> bool:
415 return (self.markup_type is not None and
416 (self.type_flag == "print" or "print" in self.dir_path.split(os.path.sep)))
417
418 @property
419 def markup_type(self) -> Optional[Text]:
420 """Return the type of markup contained in a file, based on its extension,
421 or None if it doesn't contain markup"""
422 ext = self.ext
423
424 if not ext:
425 return None
426 if ext[0] == ".":
427 ext = ext[1:]
428 if ext in ["html", "htm"]:
429 return "html"
430 if ext in ["xhtml", "xht", "xml"]:
431 return "xhtml"
432 if ext == "svg":
433 return "svg"
434 return None
435
436 @cached_property
437 def root(self) -> Optional[ElementTree.Element]:
438 """Return an ElementTree Element for the root node of the file if it contains
439 markup, or None if it does not"""
440 if not self.markup_type:
441 return None
442
443 parser = self.parsers[self.markup_type]
444
445 with self.open() as f:
446 try:
447 tree = parser(f)
448 except Exception:
449 return None
450
451 return tree
452
453 @cached_property
454 def timeout_nodes(self) -> List[ElementTree.Element]:
455 """List of ElementTree Elements corresponding to nodes in a test that
456 specify timeouts"""
457 assert self.root is not None
458 return self.root.findall(".//{http://www.w3.org/1999/xhtml}meta[@name='timeout']")
459
460 @cached_property
461 def pac_nodes(self) -> List[ElementTree.Element]:
462 """List of ElementTree Elements corresponding to nodes in a test that
463 specify PAC (proxy auto-config)"""
464 assert self.root is not None
465 return self.root.findall(".//{http://www.w3.org/1999/xhtml}meta[@name='pac']")
466
467 @cached_property
468 def script_metadata(self) -> Optional[List[Tuple[Text, Text]]]:
469 if self.name_is_worker or self.name_is_multi_global or self.name_is_window:
470 regexp = js_meta_re
471 elif self.name_is_webdriver:
472 regexp = python_meta_re
473 else:
474 return None
475
476 with self.open() as f:
477 return list(read_script_metadata(f, regexp))
478
479 @cached_property
480 def timeout(self) -> Optional[Text]:
481 """The timeout of a test or reference file. "long" if the file has an extended timeout
482 or None otherwise"""
483 if self.script_metadata:
484 if any(m == ("timeout", "long") for m in self.script_metadata):
485 return "long"
486
487 if self.root is None:
488 return None
489
490 if self.timeout_nodes:
491 timeout_str: Optional[Text] = self.timeout_nodes[0].attrib.get("content", None)
492 if timeout_str and timeout_str.lower() == "long":
493 return "long"
494
495 return None
496
497 @cached_property
498 def pac(self) -> Optional[Text]:
499 """The PAC (proxy config) of a test or reference file. A URL or null"""
500 if self.script_metadata:
501 for (meta, content) in self.script_metadata:
502 if meta == 'pac':
503 return content
504
505 if self.root is None:
506 return None
507
508 if self.pac_nodes:
509 return self.pac_nodes[0].attrib.get("content", None)
510
511 return None
512
513 @cached_property
514 def viewport_nodes(self) -> List[ElementTree.Element]:
515 """List of ElementTree Elements corresponding to nodes in a test that
516 specify viewport sizes"""
517 assert self.root is not None
518 return self.root.findall(".//{http://www.w3.org/1999/xhtml}meta[@name='viewport-size']")
519
520 @cached_property
521 def viewport_size(self) -> Optional[Text]:
522 """The viewport size of a test or reference file"""
523 if self.root is None:
524 return None
525
526 if not self.viewport_nodes:
527 return None
528
529 return self.viewport_nodes[0].attrib.get("content", None)
530
531 @cached_property
532 def dpi_nodes(self) -> List[ElementTree.Element]:
533 """List of ElementTree Elements corresponding to nodes in a test that
534 specify device pixel ratios"""
535 assert self.root is not None
536 return self.root.findall(".//{http://www.w3.org/1999/xhtml}meta[@name='device-pixel-ratio']")
537
538 @cached_property
539 def dpi(self) -> Optional[Text]:
540 """The device pixel ratio of a test or reference file"""
541 if self.root is None:
542 return None
543
544 if not self.dpi_nodes:
545 return None
546
547 return self.dpi_nodes[0].attrib.get("content", None)
548
549 def parse_ref_keyed_meta(self, node: ElementTree.Element) -> Tuple[Optional[Tuple[Text, Text, Text]], Text]:
550 item: Text = node.attrib.get("content", "")
551
552 parts = item.rsplit(":", 1)
553 if len(parts) == 1:
554 key: Optional[Tuple[Text, Text, Text]] = None
555 value = parts[0]
556 else:
557 key_part = urljoin(self.url, parts[0])
558 reftype = None
559 for ref in self.references: # type: Tuple[Text, Text]
560 if ref[0] == key_part:
561 reftype = ref[1]
562 break
563 if reftype not in ("==", "!="):
564 raise ValueError("Key %s doesn't correspond to a reference" % key_part)
565 key = (self.url, key_part, reftype)
566 value = parts[1]
567
568 return key, value
569
570
571 @cached_property
572 def fuzzy_nodes(self) -> List[ElementTree.Element]:
573 """List of ElementTree Elements corresponding to nodes in a test that
574 specify reftest fuzziness"""
575 assert self.root is not None
576 return self.root.findall(".//{http://www.w3.org/1999/xhtml}meta[@name='fuzzy']")
577
578
579 @cached_property
580 def fuzzy(self) -> Dict[Optional[Tuple[Text, Text, Text]], List[List[int]]]:
581 rv: Dict[Optional[Tuple[Text, Text, Text]], List[List[int]]] = {}
582 if self.root is None:
583 return rv
584
585 if not self.fuzzy_nodes:
586 return rv
587
588 args = ["maxDifference", "totalPixels"]
589
590 for node in self.fuzzy_nodes:
591 key, value = self.parse_ref_keyed_meta(node)
592 ranges = value.split(";")
593 if len(ranges) != 2:
594 raise ValueError("Malformed fuzzy value %s" % value)
595 arg_values: Dict[Text, List[int]] = {}
596 positional_args: Deque[List[int]] = deque()
597 for range_str_value in ranges: # type: Text
598 name: Optional[Text] = None
599 if "=" in range_str_value:
600 name, range_str_value = (part.strip()
601 for part in range_str_value.split("=", 1))
602 if name not in args:
603 raise ValueError("%s is not a valid fuzzy property" % name)
604 if arg_values.get(name):
605 raise ValueError("Got multiple values for argument %s" % name)
606 if "-" in range_str_value:
607 range_min, range_max = range_str_value.split("-")
608 else:
609 range_min = range_str_value
610 range_max = range_str_value
611 try:
612 range_value = [int(x.strip()) for x in (range_min, range_max)]
613 except ValueError:
614 raise ValueError("Fuzzy value %s must be a range of integers" %
615 range_str_value)
616 if name is None:
617 positional_args.append(range_value)
618 else:
619 arg_values[name] = range_value
620 rv[key] = []
621 for arg_name in args:
622 if arg_values.get(arg_name):
623 arg_value = arg_values.pop(arg_name)
624 else:
625 arg_value = positional_args.popleft()
626 rv[key].append(arg_value)
627 assert len(arg_values) == 0 and len(positional_args) == 0
628 return rv
629
630 @cached_property
631 def page_ranges_nodes(self) -> List[ElementTree.Element]:
632 """List of ElementTree Elements corresponding to nodes in a test that
633 specify print-reftest """
634 assert self.root is not None
635 return self.root.findall(".//{http://www.w3.org/1999/xhtml}meta[@name='reftest-pages']")
636
637 @cached_property
638 def page_ranges(self) -> Dict[Text, List[List[Optional[int]]]]:
639 """List of ElementTree Elements corresponding to nodes in a test that
640 specify print-reftest page ranges"""
641 rv: Dict[Text, List[List[Optional[int]]]] = {}
642 for node in self.page_ranges_nodes:
643 key_data, value = self.parse_ref_keyed_meta(node)
644 # Just key by url
645 if key_data is None:
646 key = self.url
647 else:
648 key = key_data[1]
649 if key in rv:
650 raise ValueError("Duplicate page-ranges value")
651 rv[key] = []
652 for range_str in value.split(","):
653 range_str = range_str.strip()
654 if "-" in range_str:
655 range_parts_str = [item.strip() for item in range_str.split("-")]
656 try:
657 range_parts = [int(item) if item else None for item in range_parts_str]
658 except ValueError:
659 raise ValueError("Malformed page-range value %s" % range_str)
660 if any(item == 0 for item in range_parts):
661 raise ValueError("Malformed page-range value %s" % range_str)
662 else:
663 try:
664 range_parts = [int(range_str)]
665 except ValueError:
666 raise ValueError("Malformed page-range value %s" % range_str)
667 rv[key].append(range_parts)
668 return rv
669
670 @cached_property
671 def testharness_nodes(self) -> List[ElementTree.Element]:
672 """List of ElementTree Elements corresponding to nodes representing a
673 testharness.js script"""
674 assert self.root is not None
675 return self.root.findall(".//{http://www.w3.org/1999/xhtml}script[@src='/resources/testharness.js']")
676
677 @cached_property
678 def content_is_testharness(self) -> Optional[bool]:
679 """Boolean indicating whether the file content represents a
680 testharness.js test"""
681 if self.root is None:
682 return None
683 return bool(self.testharness_nodes)
684
685 @cached_property
686 def variant_nodes(self) -> List[ElementTree.Element]:
687 """List of ElementTree Elements corresponding to nodes representing a
688 test variant"""
689 assert self.root is not None
690 return self.root.findall(".//{http://www.w3.org/1999/xhtml}meta[@name='variant']")
691
692 @cached_property
693 def test_variants(self) -> List[Text]:
694 rv: List[Text] = []
695 if self.ext == ".js":
696 script_metadata = self.script_metadata
697 assert script_metadata is not None
698 for (key, value) in script_metadata:
699 if key == "variant":
700 rv.append(value)
701 else:
702 for element in self.variant_nodes:
703 if "content" in element.attrib:
704 variant: Text = element.attrib["content"]
705 rv.append(variant)
706
707 for variant in rv:
708 if variant != "":
709 if variant[0] not in ("#", "?"):
710 raise ValueError("Non-empty variant must start with either a ? or a #")
711 if len(variant) == 1 or (variant[0] == "?" and variant[1] == "#"):
712 raise ValueError("Variants must not have empty fragment or query " +
713 "(omit the empty part instead)")
714
715 if not rv:
716 rv = [""]
717
718 return rv
719
720 @cached_property
721 def testdriver_nodes(self) -> List[ElementTree.Element]:
722 """List of ElementTree Elements corresponding to nodes representing a
723 testdriver.js script"""
724 assert self.root is not None
725 # `xml.etree.ElementTree.findall` has a limited support of xPath, so
726 # explicit filter is required.
727 return [node for node in
728 self.root.findall(".//{http://www.w3.org/1999/xhtml}script")
729 if node.attrib.get('src',
730 "") == '/resources/testdriver.js' or
731 node.attrib.get('src', "").startswith(
732 '/resources/testdriver.js?')]
733
734 @cached_property
735 def has_testdriver(self) -> Optional[bool]:
736 """Boolean indicating whether the file content represents a
737 testharness.js test"""
738 if self.root is None:
739 return None
740 return bool(self.testdriver_nodes)
741
742 def ___get_testdriver_include_path(self) -> Optional[str]:
743 if self.script_metadata:
744 for (meta, content) in self.script_metadata:
745 if meta.strip() == 'script' and (
746 content == '/resources/testdriver.js' or content.startswith(
747 '/resources/testdriver.js?')):
748 return content.strip()
749
750 if self.root is None:
751 return None
752
753 for node in self.testdriver_nodes:
754 if "src" in node.attrib:
755 return node.attrib.get("src")
756
757 return None
758
759 @cached_property
760 def testdriver_features(self) -> Optional[List[Text]]:
761 """
762 List of requested testdriver features.
763 """
764
765 testdriver_include_url = self.___get_testdriver_include_path()
766
767 if testdriver_include_url is None:
768 return None
769
770 # Parse the URL
771 parsed_url = urlparse(testdriver_include_url)
772 # Extract query parameters
773 query_params = parse_qs(parsed_url.query)
774 # Get the values for the 'feature' parameter
775 feature_values = query_params.get('feature', [])
776
777 if len(feature_values) > 0:
778 return feature_values
779
780 return None
781
782 @cached_property
783 def reftest_nodes(self) -> List[ElementTree.Element]:
784 """List of ElementTree Elements corresponding to nodes representing a
785 to a reftest <link>"""
786 if self.root is None:
787 return []
788
789 match_links = self.root.findall(".//{http://www.w3.org/1999/xhtml}link[@rel='match']")
790 mismatch_links = self.root.findall(".//{http://www.w3.org/1999/xhtml}link[@rel='mismatch']")
791 return match_links + mismatch_links
792
793 @cached_property
794 def references(self) -> List[Tuple[Text, Text]]:
795 """List of (ref_url, relation) tuples for any reftest references specified in
796 the file"""
797 rv: List[Tuple[Text, Text]] = []
798 rel_map = {"match": "==", "mismatch": "!="}
799 for item in self.reftest_nodes:
800 if "href" in item.attrib:
801 ref_url = urljoin(self.url, item.attrib["href"].strip(space_chars))
802 ref_type = rel_map[item.attrib["rel"]]
803 rv.append((ref_url, ref_type))
804 return rv
805
806 @cached_property
807 def content_is_ref_node(self) -> bool:
808 """Boolean indicating whether the file is a non-leaf node in a reftest
809 graph (i.e. if it contains any <link rel=[mis]match>"""
810 return bool(self.references)
811
812 @cached_property
813 def css_flag_nodes(self) -> List[ElementTree.Element]:
814 """List of ElementTree Elements corresponding to nodes representing a
815 flag <meta>"""
816 if self.root is None:
817 return []
818 return self.root.findall(".//{http://www.w3.org/1999/xhtml}meta[@name='flags']")
819
820 @cached_property
821 def css_flags(self) -> Set[Text]:
822 """Set of flags specified in the file"""
823 rv: Set[Text] = set()
824 for item in self.css_flag_nodes:
825 if "content" in item.attrib:
826 for flag in item.attrib["content"].split():
827 rv.add(flag)
828 return rv
829
830 @cached_property
831 def content_is_css_manual(self) -> Optional[bool]:
832 """Boolean indicating whether the file content represents a
833 CSS WG-style manual test"""
834 if self.root is None:
835 return None
836 # return True if the intersection between the two sets is non-empty
837 return bool(self.css_flags & {"animated", "font", "history", "interact", "paged", "speech", "userstyle"})
838
839 @cached_property
840 def spec_link_nodes(self) -> List[ElementTree.Element]:
841 """List of ElementTree Elements corresponding to nodes representing a
842 <link rel=help>, used to point to specs"""
843 if self.root is None:
844 return []
845 return self.root.findall(".//{http://www.w3.org/1999/xhtml}link[@rel='help']")
846
847 @cached_property
848 def spec_links(self) -> Set[Text]:
849 """Set of spec links specified in the file"""
850 rv: Set[Text] = set()
851 for item in self.spec_link_nodes:
852 if "href" in item.attrib:
853 rv.add(item.attrib["href"].strip(space_chars))
854 return rv
855
856 @cached_property
857 def content_is_css_visual(self) -> Optional[bool]:
858 """Boolean indicating whether the file content represents a
859 CSS WG-style visual test"""
860 if self.root is None:
861 return None
862 return bool(self.ext in {'.xht', '.html', '.xhtml', '.htm', '.xml', '.svg'} and
863 self.spec_links)
864
865 @property
866 def type(self) -> Text:
867 possible_types = self.possible_types
868 if len(possible_types) == 1:
869 return possible_types.pop()
870
871 rv, _ = self.manifest_items()
872 return rv
873
874 @property
875 def possible_types(self) -> Set[Text]:
876 """Determines the set of possible types without reading the file"""
877
878 if self.items_cache:
879 return {self.items_cache[0]}
880
881 if self.name_is_non_test:
882 return {SupportFile.item_type}
883
884 if self.name_is_manual:
885 return {ManualTest.item_type}
886
887 if self.name_is_conformance:
888 return {ConformanceCheckerTest.item_type}
889
890 if self.name_is_conformance_support:
891 return {SupportFile.item_type}
892
893 if self.name_is_webdriver:
894 return {WebDriverSpecTest.item_type}
895
896 if self.name_is_visual:
897 return {VisualTest.item_type}
898
899 if self.name_is_crashtest:
900 return {CrashTest.item_type}
901
902 if self.name_is_print_reftest:
903 return {PrintRefTest.item_type}
904
905 if self.name_is_multi_global:
906 return {TestharnessTest.item_type}
907
908 if self.name_is_worker:
909 return {TestharnessTest.item_type}
910
911 if self.name_is_window:
912 return {TestharnessTest.item_type}
913
914 if self.markup_type is None:
915 return {SupportFile.item_type}
916
917 if not self.name_is_reference:
918 return {ManualTest.item_type,
919 TestharnessTest.item_type,
920 RefTest.item_type,
921 VisualTest.item_type,
922 SupportFile.item_type}
923
924 return {TestharnessTest.item_type,
925 RefTest.item_type,
926 SupportFile.item_type}
927
928 def manifest_items(self) -> Tuple[Text, List[ManifestItem]]:
929 """List of manifest items corresponding to the file. There is typically one
930 per test, but in the case of reftests a node may have corresponding manifest
931 items without being a test itself."""
932
933 if self.items_cache:
934 return self.items_cache
935
936 drop_cached = "root" not in self.__dict__
937
938 if self.name_is_non_test:
939 rv: Tuple[Text, List[ManifestItem]] = ("support", [
940 SupportFile(
941 self.tests_root,
942 self.rel_path
943 )])
944
945 elif self.name_is_manual:
946 rv = ManualTest.item_type, [
947 ManualTest(
948 self.tests_root,
949 self.rel_path,
950 self.url_base,
951 self.rel_url
952 )]
953
954 elif self.name_is_conformance:
955 rv = ConformanceCheckerTest.item_type, [
956 ConformanceCheckerTest(
957 self.tests_root,
958 self.rel_path,
959 self.url_base,
960 self.rel_url
961 )]
962
963 elif self.name_is_conformance_support:
964 rv = "support", [
965 SupportFile(
966 self.tests_root,
967 self.rel_path
968 )]
969
970 elif self.name_is_webdriver:
971 rv = WebDriverSpecTest.item_type, [
972 WebDriverSpecTest(
973 self.tests_root,
974 self.rel_path,
975 self.url_base,
976 self.rel_url,
977 timeout=self.timeout
978 )]
979
980 elif self.name_is_visual:
981 rv = VisualTest.item_type, [
982 VisualTest(
983 self.tests_root,
984 self.rel_path,
985 self.url_base,
986 self.rel_url
987 )]
988
989 elif self.name_is_crashtest:
990 rv = CrashTest.item_type, [
991 CrashTest(
992 self.tests_root,
993 self.rel_path,
994 self.url_base,
995 self.rel_url,
996 testdriver=self.has_testdriver,
997 )]
998
999 elif self.name_is_print_reftest:
1000 references = self.references
1001 if not references:
1002 raise ValueError("%s detected as print reftest but doesn't have any refs" %
1003 self.path)
1004 rv = PrintRefTest.item_type, [
1005 PrintRefTest(
1006 self.tests_root,
1007 self.rel_path,
1008 self.url_base,
1009 self.rel_url,
1010 references=references,
1011 timeout=self.timeout,
1012 viewport_size=self.viewport_size,
1013 fuzzy=self.fuzzy,
1014 page_ranges=self.page_ranges,
1015 testdriver=self.has_testdriver,
1016 )]
1017
1018 elif self.name_is_multi_global:
1019 globals = ""
1020 script_metadata = self.script_metadata
1021 assert script_metadata is not None
1022 for (key, value) in script_metadata:
1023 if key == "global":
1024 globals = value
1025 break
1026
1027 tests: List[ManifestItem] = [
1028 TestharnessTest(
1029 self.tests_root,
1030 self.rel_path,
1031 self.url_base,
1032 global_variant_url(self.rel_url, suffix) + variant,
1033 timeout=self.timeout,
1034 pac=self.pac,
1035 testdriver_features=self.testdriver_features,
1036 jsshell=jsshell,
1037 script_metadata=self.script_metadata
1038 )
1039 for (suffix, jsshell) in sorted(global_suffixes(globals))
1040 for variant in self.test_variants
1041 ]
1042 rv = TestharnessTest.item_type, tests
1043
1044 elif self.name_is_worker:
1045 test_url = replace_end(self.rel_url, ".worker.js", ".worker.html")
1046 tests = [
1047 TestharnessTest(
1048 self.tests_root,
1049 self.rel_path,
1050 self.url_base,
1051 test_url + variant,
1052 timeout=self.timeout,
1053 pac=self.pac,
1054 testdriver_features=self.testdriver_features,
1055 script_metadata=self.script_metadata
1056 )
1057 for variant in self.test_variants
1058 ]
1059 rv = TestharnessTest.item_type, tests
1060
1061 elif self.name_is_window:
1062 test_url = replace_end(self.rel_url, ".window.js", ".window.html")
1063 tests = [
1064 TestharnessTest(
1065 self.tests_root,
1066 self.rel_path,
1067 self.url_base,
1068 test_url + variant,
1069 timeout=self.timeout,
1070 pac=self.pac,
1071 testdriver_features=self.testdriver_features,
1072 script_metadata=self.script_metadata
1073 )
1074 for variant in self.test_variants
1075 ]
1076 rv = TestharnessTest.item_type, tests
1077
1078 elif self.content_is_css_manual and not self.name_is_reference:
1079 rv = ManualTest.item_type, [
1080 ManualTest(
1081 self.tests_root,
1082 self.rel_path,
1083 self.url_base,
1084 self.rel_url
1085 )]
1086
1087 elif self.content_is_testharness:
1088 rv = TestharnessTest.item_type, []
1089 testdriver = self.has_testdriver
1090 for variant in self.test_variants:
1091 url = self.rel_url + variant
1092 rv[1].append(TestharnessTest(
1093 self.tests_root,
1094 self.rel_path,
1095 self.url_base,
1096 url,
1097 timeout=self.timeout,
1098 pac=self.pac,
1099 testdriver_features=self.testdriver_features,
1100 testdriver=testdriver,
1101 script_metadata=self.script_metadata
1102 ))
1103
1104 elif self.content_is_ref_node:
1105 rv = RefTest.item_type, []
1106 for variant in self.test_variants:
1107 url = self.rel_url + variant
1108 rv[1].append(RefTest(
1109 self.tests_root,
1110 self.rel_path,
1111 self.url_base,
1112 url,
1113 references=[
1114 (ref[0] + variant, ref[1])
1115 for ref in self.references
1116 ],
1117 timeout=self.timeout,
1118 viewport_size=self.viewport_size,
1119 dpi=self.dpi,
1120 fuzzy=self.fuzzy,
1121 testdriver=self.has_testdriver,
1122 ))
1123
1124 elif self.content_is_css_visual and not self.name_is_reference:
1125 rv = VisualTest.item_type, [
1126 VisualTest(
1127 self.tests_root,
1128 self.rel_path,
1129 self.url_base,
1130 self.rel_url
1131 )]
1132
1133 else:
1134 rv = "support", [
1135 SupportFile(
1136 self.tests_root,
1137 self.rel_path
1138 )]
1139
1140 assert rv[0] in self.possible_types
1141 assert len(rv[1]) == len(set(rv[1]))
1142
1143 self.items_cache = rv
1144
1145 if drop_cached and "__cached_properties__" in self.__dict__:
1146 cached_properties = self.__dict__["__cached_properties__"]
1147 for prop in cached_properties:
1148 if prop in self.__dict__:
1149 del self.__dict__[prop]
1150 del self.__dict__["__cached_properties__"]
1151
1152 return rv
1153
1154 def manifest_spec_items(self) -> Optional[Tuple[Text, List[ManifestItem]]]:
1155 specs = list(self.spec_links)
1156 if not specs:
1157 return None
1158 rv: Tuple[Text, List[ManifestItem]] = (SpecItem.item_type, [
1159 SpecItem(
1160 self.tests_root,
1161 self.rel_path,
1162 specs
1163 )])
1164 return rv