Debian Codegraph @

testing/web-platform/tests/resources/test/conftest.py

raw
1 import copy
2 import json
3 import os
4 import ssl
5 import sys
6 import subprocess
7 import urllib
8
9 import html5lib
10 import py
11 import pytest
12
13 from wptserver import WPTServer
14
15 HERE = os.path.dirname(os.path.abspath(__file__))
16 WPT_ROOT = os.path.normpath(os.path.join(HERE, '..', '..'))
17 HARNESS = os.path.join(HERE, 'harness.html')
18 TEST_TYPES = ('functional', 'unit')
19
20 sys.path.insert(0, os.path.normpath(os.path.join(WPT_ROOT, "tools")))
21 import localpaths
22
23 sys.path.insert(0, os.path.normpath(os.path.join(WPT_ROOT, "tools", "webdriver")))
24 import webdriver
25
26
27 def pytest_addoption(parser):
28 parser.addoption("--binary", action="store", default=None, help="path to browser binary")
29 parser.addoption("--headless", action="store_true", default=False, help="run browser in headless mode")
30
31
32 def pytest_collect_file(file_path, path, parent):
33 if file_path.suffix.lower() != '.html':
34 return
35
36 # Tests are organized in directories by type
37 test_type = os.path.relpath(str(file_path), HERE)
38 if os.path.sep not in test_type or ".." in test_type:
39 # HTML files in this directory are not tests
40 return
41 test_type = test_type.split(os.path.sep)[1]
42
43 return HTMLFile.from_parent(parent, path=file_path, test_type=test_type)
44
45
46 def pytest_configure(config):
47 config.proc = subprocess.Popen(["geckodriver"])
48 config.add_cleanup(config.proc.kill)
49
50 capabilities = {"alwaysMatch": {"acceptInsecureCerts": True, "moz:firefoxOptions": {}}}
51 if config.getoption("--binary"):
52 capabilities["alwaysMatch"]["moz:firefoxOptions"]["binary"] = config.getoption("--binary")
53 if config.getoption("--headless"):
54 capabilities["alwaysMatch"]["moz:firefoxOptions"]["args"] = ["--headless"]
55
56 config.driver = webdriver.Session("localhost", 4444,
57 capabilities=capabilities)
58 config.add_cleanup(config.driver.end)
59
60 # Although the name of the `_create_unverified_context` method suggests
61 # that it is not intended for external consumption, the standard library's
62 # documentation explicitly endorses its use:
63 #
64 # > To revert to the previous, unverified, behavior
65 # > ssl._create_unverified_context() can be passed to the context
66 # > parameter.
67 #
68 # https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection
69 config.ssl_context = ssl._create_unverified_context()
70
71 config.server = WPTServer(WPT_ROOT)
72 config.server.start(config.ssl_context)
73 config.add_cleanup(config.server.stop)
74
75
76 def resolve_uri(context, uri):
77 if uri.startswith('/'):
78 base = WPT_ROOT
79 path = uri[1:]
80 else:
81 base = os.path.dirname(context)
82 path = uri
83
84 return os.path.exists(os.path.join(base, path))
85
86
87 def _summarize(actual):
88 def _scrub_stack(test_obj):
89 copy = dict(test_obj)
90 del copy['stack']
91 return copy
92
93 def _expand_status(status_obj):
94 for key, value in [item for item in status_obj.items()]:
95 # In "status" and "test" objects, the "status" value enum
96 # definitions are interspersed with properties for unrelated
97 # metadata. The following condition is a best-effort attempt to
98 # ignore non-enum properties.
99 if key != key.upper() or not isinstance(value, int):
100 continue
101
102 del status_obj[key]
103
104 if status_obj['status'] == value:
105 status_obj[u'status_string'] = key
106
107 del status_obj['status']
108
109 return status_obj
110
111 def _summarize_test(test_obj):
112 del test_obj['index']
113
114 assert 'phase' in test_obj
115 assert 'phases' in test_obj
116 assert 'COMPLETE' in test_obj['phases']
117 assert test_obj['phase'] == test_obj['phases']['COMPLETE']
118 del test_obj['phases']
119 del test_obj['phase']
120
121 return _expand_status(_scrub_stack(test_obj))
122
123 def _summarize_status(status_obj):
124 return _expand_status(_scrub_stack(status_obj))
125
126
127 summarized = {}
128
129 summarized[u'summarized_status'] = _summarize_status(actual['status'])
130 summarized[u'summarized_tests'] = [
131 _summarize_test(test) for test in actual['tests']]
132 summarized[u'summarized_tests'].sort(key=lambda test_obj: test_obj.get('name'))
133 summarized[u'summarized_asserts'] = [
134 {"assert_name": assert_item["assert_name"],
135 "test": assert_item["test"]["name"] if assert_item["test"] else None,
136 "args": assert_item["args"],
137 "status": assert_item["status"]} for assert_item in actual["asserts"]]
138 summarized[u'type'] = actual['type']
139
140 return summarized
141
142
143 class HTMLFile(pytest.File):
144 def __init__(self, test_type=None, **kwargs):
145 super().__init__(**kwargs)
146 self.test_type = test_type
147
148 def collect(self):
149 url = self.session.config.server.url(self.path)
150 # Some tests are reliant on the WPT servers substitution functionality,
151 # so tests must be retrieved from the server rather than read from the
152 # file system directly.
153 handle = urllib.request.urlopen(url,
154 context=self.parent.session.config.ssl_context)
155 try:
156 markup = handle.read()
157 finally:
158 handle.close()
159
160 if self.test_type not in TEST_TYPES:
161 raise ValueError('Unrecognized test type: "%s"' % self.test_type)
162
163 parsed = html5lib.parse(markup, namespaceHTMLElements=False)
164 name = None
165 expected = None
166
167 for element in parsed.iter():
168 if not name and element.tag == 'title':
169 name = element.text
170 continue
171 if element.tag == 'script':
172 if element.attrib.get('id') == 'expected':
173 try:
174 expected = json.loads(element.text)
175 except ValueError:
176 print("Failed parsing JSON in %s" % filename)
177 raise
178
179 if not name:
180 raise ValueError('No name found in %s add a <title> element' % filename)
181 elif self.test_type == 'functional':
182 if not expected:
183 raise ValueError('Functional tests must specify expected report data')
184 elif self.test_type == 'unit' and expected:
185 raise ValueError('Unit tests must not specify expected report data')
186
187 yield HTMLItem.from_parent(self, name=name, url=url, expected=expected)
188
189
190 class HTMLItem(pytest.Item):
191 def __init__(self, name, parent=None, config=None, session=None, nodeid=None, test_type=None, url=None, expected=None, **kwargs):
192 super().__init__(name, parent, config, session, nodeid, **kwargs)
193
194 self.test_type = self.parent.test_type
195 self.url = url
196 self.expected = expected
197
198 def reportinfo(self):
199 return self.fspath, None, self.url
200
201 def runtest(self):
202 if self.test_type == 'unit':
203 self._run_unit_test()
204 elif self.test_type == 'functional':
205 self._run_functional_test()
206 else:
207 raise NotImplementedError
208
209 def _run_unit_test(self):
210 driver = self.session.config.driver
211 server = self.session.config.server
212
213 driver.url = server.url(HARNESS)
214
215 actual = driver.execute_async_script(
216 'runTest("%s", "foo", arguments[0])' % self.url
217 )
218
219 summarized = _summarize(copy.deepcopy(actual))
220
221 print(json.dumps(summarized, indent=2))
222
223 assert summarized[u'summarized_status'][u'status_string'] == u'OK', summarized[u'summarized_status'][u'message']
224 for test in summarized[u'summarized_tests']:
225 msg = "%s\n%s" % (test[u'name'], test[u'message'])
226 assert test[u'status_string'] == u'PASS', msg
227
228 def _run_functional_test(self):
229 driver = self.session.config.driver
230 server = self.session.config.server
231
232 driver.url = server.url(HARNESS)
233
234 test_url = self.url
235 actual = driver.execute_async_script('runTest("%s", "foo", arguments[0])' % test_url)
236
237 print(json.dumps(actual, indent=2))
238
239 summarized = _summarize(copy.deepcopy(actual))
240
241 print(json.dumps(summarized, indent=2))
242
243 # Test object ordering is not guaranteed. This weak assertion verifies
244 # that the indices are unique and sequential
245 indices = [test_obj.get('index') for test_obj in actual['tests']]
246 self._assert_sequence(indices)
247
248 self.expected[u'summarized_tests'].sort(key=lambda test_obj: test_obj.get('name'))
249
250 # Make asserts opt-in for now
251 if "summarized_asserts" not in self.expected:
252 del summarized["summarized_asserts"]
253 else:
254 # We can't be sure of the order of asserts even within the same test
255 # although we could also check for the failing assert being the final
256 # one
257 for obj in [summarized, self.expected]:
258 obj["summarized_asserts"].sort(
259 key=lambda x: (x["test"] or "", x["status"], x["assert_name"], tuple(x["args"])))
260
261 assert summarized == self.expected
262
263 @staticmethod
264 def _assert_sequence(nums):
265 if nums and len(nums) > 0:
266 assert nums == list(range(nums[-1] + 1))