moztest 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
moztest/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ from moztest import adapters
6
+
7
+ __all__ = ["adapters"]
@@ -0,0 +1,7 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ from moztest.adapters import unit
6
+
7
+ __all__ = ["unit"]
@@ -0,0 +1,229 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ import sys
6
+ import time
7
+ import traceback
8
+ import unittest
9
+ from unittest import TextTestResult
10
+
11
+ """Adapter used to output structuredlog messages from unittest
12
+ testsuites"""
13
+
14
+
15
+ def get_test_class_name(test):
16
+ """
17
+ This method is used to return the full class name from a
18
+ :class:`unittest.TestCase` instance.
19
+
20
+ It is used as a default to define the "class_name" extra value
21
+ passed in structured loggers. You can override the default by
22
+ implementing a "get_test_class_name" method on you TestCase subclass.
23
+ """
24
+ return "%s.%s" % (test.__class__.__module__, test.__class__.__name__)
25
+
26
+
27
+ def get_test_method_name(test):
28
+ """
29
+ This method is used to return the full method name from a
30
+ :class:`unittest.TestCase` instance.
31
+
32
+ It is used as a default to define the "method_name" extra value
33
+ passed in structured loggers. You can override the default by
34
+ implementing a "get_test_method_name" method on you TestCase subclass.
35
+ """
36
+ return test._testMethodName
37
+
38
+
39
+ class StructuredTestResult(TextTestResult):
40
+ def __init__(self, *args, **kwargs):
41
+ self.logger = kwargs.pop("logger")
42
+ self.test_list = kwargs.pop("test_list", [])
43
+ self.result_callbacks = kwargs.pop("result_callbacks", [])
44
+ self.group = kwargs.pop("group", None)
45
+ self.passed = 0
46
+ self.testsRun = 0
47
+ TextTestResult.__init__(self, *args, **kwargs)
48
+
49
+ def call_callbacks(self, test, status):
50
+ debug_info = {}
51
+ for callback in self.result_callbacks:
52
+ info = callback(test, status)
53
+ if info is not None:
54
+ debug_info.update(info)
55
+ return debug_info
56
+
57
+ def startTestRun(self):
58
+ # This would be an opportunity to call the logger's suite_start action,
59
+ # however some users may use multiple suites, and per the structured
60
+ # logging protocol, this action should only be called once.
61
+ pass
62
+
63
+ def startTest(self, test):
64
+ self.testsRun += 1
65
+ self.logger.test_start(test.id(), group=self.group)
66
+
67
+ def stopTest(self, test):
68
+ pass
69
+
70
+ def stopTestRun(self):
71
+ # This would be an opportunity to call the logger's suite_end action,
72
+ # however some users may use multiple suites, and per the structured
73
+ # logging protocol, this action should only be called once.
74
+ pass
75
+
76
+ def _extract_err_message(self, err):
77
+ # Format an exception message in the style of unittest's _exc_info_to_string
78
+ # while maintaining a division between a traceback and a message.
79
+ exc_ty, val, _ = err
80
+ exc_msg = "".join(traceback.format_exception_only(exc_ty, val))
81
+ if self.buffer:
82
+ output_msg = "\n".join([sys.stdout.getvalue(), sys.stderr.getvalue()])
83
+ return "".join([exc_msg, output_msg])
84
+ return exc_msg.rstrip()
85
+
86
+ def _extract_stacktrace(self, err, test):
87
+ # Format an exception stack in the style of unittest's _exc_info_to_string
88
+ # while maintaining a division between a traceback and a message.
89
+ # This is mostly borrowed from unittest.result._exc_info_to_string.
90
+
91
+ exctype, value, tb = err
92
+ while tb and self._is_relevant_tb_level(tb):
93
+ tb = tb.tb_next
94
+ # Header usually included by print_exception
95
+ lines = ["Traceback (most recent call last):\n"]
96
+ if exctype is test.failureException and hasattr(
97
+ self, "_count_relevant_tb_levels"
98
+ ):
99
+ length = self._count_relevant_tb_levels(tb)
100
+ lines += traceback.format_tb(tb, length)
101
+ else:
102
+ lines += traceback.format_tb(tb)
103
+ return "".join(lines)
104
+
105
+ def _get_class_method_name(self, test):
106
+ if hasattr(test, "get_test_class_name"):
107
+ class_name = test.get_test_class_name()
108
+ else:
109
+ class_name = get_test_class_name(test)
110
+
111
+ if hasattr(test, "get_test_method_name"):
112
+ method_name = test.get_test_method_name()
113
+ else:
114
+ method_name = get_test_method_name(test)
115
+
116
+ return {"class_name": class_name, "method_name": method_name}
117
+
118
+ def addError(self, test, err):
119
+ self.errors.append((test, self._exc_info_to_string(err, test)))
120
+ extra = self.call_callbacks(test, "ERROR")
121
+ extra.update(self._get_class_method_name(test))
122
+ self.logger.test_end(
123
+ test.id(),
124
+ "ERROR",
125
+ message=self._extract_err_message(err),
126
+ expected="PASS",
127
+ stack=self._extract_stacktrace(err, test),
128
+ extra=extra,
129
+ group=self.group,
130
+ )
131
+
132
+ def addFailure(self, test, err):
133
+ extra = self.call_callbacks(test, "FAIL")
134
+ extra.update(self._get_class_method_name(test))
135
+ self.logger.test_end(
136
+ test.id(),
137
+ "FAIL",
138
+ message=self._extract_err_message(err),
139
+ expected="PASS",
140
+ stack=self._extract_stacktrace(err, test),
141
+ extra=extra,
142
+ group=self.group,
143
+ )
144
+
145
+ def addSuccess(self, test):
146
+ extra = self._get_class_method_name(test)
147
+ self.logger.test_end(
148
+ test.id(), "PASS", expected="PASS", extra=extra, group=self.group
149
+ )
150
+
151
+ def addExpectedFailure(self, test, err):
152
+ extra = self.call_callbacks(test, "FAIL")
153
+ extra.update(self._get_class_method_name(test))
154
+ self.logger.test_end(
155
+ test.id(),
156
+ "FAIL",
157
+ message=self._extract_err_message(err),
158
+ expected="FAIL",
159
+ stack=self._extract_stacktrace(err, test),
160
+ extra=extra,
161
+ group=self.group,
162
+ )
163
+
164
+ def addUnexpectedSuccess(self, test):
165
+ extra = self.call_callbacks(test, "PASS")
166
+ extra.update(self._get_class_method_name(test))
167
+ self.logger.test_end(
168
+ test.id(), "PASS", expected="FAIL", extra=extra, group=self.group
169
+ )
170
+
171
+ def addSkip(self, test, reason):
172
+ extra = self.call_callbacks(test, "SKIP")
173
+ extra.update(self._get_class_method_name(test))
174
+ self.logger.test_end(
175
+ test.id(),
176
+ "SKIP",
177
+ message=reason,
178
+ expected="PASS",
179
+ extra=extra,
180
+ group=self.group,
181
+ )
182
+
183
+
184
+ class StructuredTestRunner(unittest.TextTestRunner):
185
+ resultclass = StructuredTestResult
186
+
187
+ def __init__(self, **kwargs):
188
+ """TestRunner subclass designed for structured logging.
189
+
190
+ :params logger: A ``StructuredLogger`` to use for logging the test run.
191
+ :params test_list: An optional list of tests that will be passed along
192
+ the `suite_start` message.
193
+
194
+ """
195
+
196
+ self.logger = kwargs.pop("logger")
197
+ self.test_list = kwargs.pop("test_list", [])
198
+ self.result_callbacks = kwargs.pop("result_callbacks", [])
199
+ unittest.TextTestRunner.__init__(self, **kwargs)
200
+
201
+ def _makeResult(self):
202
+ return self.resultclass(
203
+ self.stream,
204
+ self.descriptions,
205
+ self.verbosity,
206
+ logger=self.logger,
207
+ test_list=self.test_list,
208
+ )
209
+
210
+ def run(self, test):
211
+ """Run the given test case or test suite."""
212
+ result = self._makeResult()
213
+ result.failfast = self.failfast
214
+ result.buffer = self.buffer
215
+ startTime = time.time()
216
+ startTestRun = getattr(result, "startTestRun", None)
217
+ if startTestRun is not None:
218
+ startTestRun()
219
+ try:
220
+ test(result)
221
+ finally:
222
+ stopTestRun = getattr(result, "stopTestRun", None)
223
+ if stopTestRun is not None:
224
+ stopTestRun()
225
+ stopTime = time.time()
226
+ if hasattr(result, "time_taken"):
227
+ result.time_taken = stopTime - startTime
228
+
229
+ return result
moztest/assertions.py ADDED
@@ -0,0 +1,250 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ import re
6
+
7
+
8
+ class AssertionFailureParser:
9
+ """Parses native assertion failures out of a process output stream and
10
+ emits one ``assertion_failure`` structured-log action per failure.
11
+
12
+ Recognized headers (mfbt/Assertions.h and xpcom/base/nsDebugImpl.cpp):
13
+
14
+ [<pid>] Assertion failure: <condition>, at <file>:<line>
15
+ [<pid>] Hit MOZ_CRASH(<reason>) at <file>:<line>
16
+ [<desc> <pid>, <thread>] ###!!! ASSERTION: <str>: '<expr>', file <file>:<line>
17
+ [<pid>, <thread>] ###!!! ABORT: <str>: '<expr>', file <file>:<line>
18
+
19
+ Each header is followed by the frames MozWalkTheStack prints, one per
20
+ line, as post-processed by the harness's stack fixer:
21
+
22
+ #01: <function> [<file>:<line>] (breakpad symbols, CI)
23
+ #01: <function> (<file>:<line>) (native symbols)
24
+ #01: <function> [<library> + 0x<offset>]
25
+ #01: ???[<library> +0x<offset>] (unfixed)
26
+
27
+ There is no terminator: a report ends on the first line that is neither a
28
+ frame nor tolerated noise (a few lines from other processes can land in
29
+ the middle of a stack when the output of several processes is merged),
30
+ on a new header, or on flush().
31
+
32
+ With XPCOM_DEBUG_BREAK=stack-and-abort (xpcshell), an NS_ASSERTION is
33
+ followed by ``Hit MOZ_CRASH([...] ###!!! ASSERTION: ...)`` and a second
34
+ stack. That crash line is folded into the pending assertion, which becomes
35
+ fatal, and its stack is swallowed, so one failure yields one action.
36
+
37
+ In-progress state is keyed by the emitting stream (``pid``), so reports
38
+ from streams that interleave stay separate.
39
+ """
40
+
41
+ # Lines from other processes tolerated inside a report before giving up.
42
+ MAX_SLACK = 3
43
+
44
+ mozAssertRegExp = re.compile(
45
+ r"^(?:\[(?P<pid>\d+)\] )?Assertion failure: (?P<message>.*), at "
46
+ r"(?P<file>.+?):(?P<lineno>\d+)\s*$"
47
+ )
48
+ mozCrashRegExp = re.compile(
49
+ r"^(?:\[(?P<pid>\d+)\] )?Hit MOZ_CRASH\((?P<message>.*)\) at "
50
+ r"(?P<file>.+?):(?P<lineno>\d+)\s*$"
51
+ )
52
+ # The process description set by nsDebugImpl::SetMultiprocessMode is free
53
+ # form ("Parent", "PKCS11ModuleChild", "MF Media Engine CDM"), so the pid
54
+ # is the last token before the thread name.
55
+ nsDebugRegExp = re.compile(
56
+ r"^\[(?:(?P<process_type>[^\]]+?) )?(?P<pid>\d+), (?P<thread>[^\]]+)\] "
57
+ r"###!!! (?P<severity>ASSERTION|ABORT): (?P<rest>.*)$"
58
+ )
59
+ # The message is "<str>: '<expr>'", "<str>", "'<expr>'" or empty, and the
60
+ # location is optional (nsDebugImpl.cpp prints each piece when present).
61
+ nsDebugRestRegExp = re.compile(
62
+ r"^(?:(?P<message>.*)(?:, |: ))?file (?P<file>.+?)(?::|, line )"
63
+ r"(?P<lineno>\d+)\s*$"
64
+ )
65
+ frameRegExp = re.compile(r"^#(?P<n>\d+): (?P<body>.*\S)\s*$")
66
+ # The function name can itself contain (), [] and spaces, so the location
67
+ # is the bracketed group that ends the line.
68
+ frameTailRegExp = re.compile(
69
+ r"^(?P<function>.*?)\s*(?:\[(?P<bloc>[^\[\]]*)\]|\((?P<ploc>[^()]*)\))$"
70
+ )
71
+ fileLineRegExp = re.compile(r"^(?P<file>.+?):(?P<line>\d+)$")
72
+ moduleOffsetRegExp = re.compile(r"^(?P<module>.+?) \+ ?(?P<offset>0x[0-9A-Fa-f]+)$")
73
+ # Rust frames carry a trailing ::h<hex> that changes with compiler
74
+ # versions; see bug 1507350.
75
+ rustRegExp = re.compile(r"::h[a-f0-9]{16}$")
76
+ # NS_DebugBreak rings the terminal bell before an assertion; harnesses
77
+ # that escape control characters (xpcshell) turn it into a literal "\x07".
78
+ bellRegExp = re.compile(r"^(?:\x07|\\x07)")
79
+
80
+ FATAL_KINDS = frozenset({"MOZ_ASSERT", "MOZ_CRASH", "NS_ABORT"})
81
+
82
+ def __init__(self, logger):
83
+ self.logger = logger
84
+ # stream id -> in-progress report dict
85
+ self._reports = {}
86
+
87
+ def log(self, line, pid=None, test=None, time=None):
88
+ """Feed one output line from stream ``pid``.
89
+
90
+ Returns True when the line was consumed (a header, a frame, or the
91
+ folded crash of a pending assertion), False otherwise.
92
+ """
93
+ line = self.bellRegExp.sub("", line.rstrip("\r\n"))
94
+ report = self._reports.get(pid)
95
+
96
+ if report is not None and line.startswith("#"):
97
+ frame = self._parse_frame(line)
98
+ if frame is not None:
99
+ report["slack"] = 0
100
+ if not report["swallow"]:
101
+ report["stack"].append(frame)
102
+ return True
103
+
104
+ header = self._parse_header(line)
105
+ if header is not None:
106
+ if report is not None and self._folds_into(report, header):
107
+ report["fatal"] = True
108
+ report["swallow"] = True
109
+ report["slack"] = 0
110
+ return True
111
+ self._finish(pid)
112
+ self._reports[pid] = {
113
+ **header,
114
+ "test": test,
115
+ "time": time,
116
+ "stack": [],
117
+ "slack": 0,
118
+ "swallow": False,
119
+ }
120
+ return True
121
+
122
+ if report is not None:
123
+ report["slack"] += 1
124
+ if report["slack"] > self.MAX_SLACK:
125
+ self._finish(pid)
126
+ return False
127
+
128
+ def flush(self):
129
+ """Emit any reports left open by truncated output."""
130
+ for pid in list(self._reports):
131
+ self._finish(pid)
132
+
133
+ def discard(self, key):
134
+ """Drop the pending report whose (message, file, lineno) is ``key``.
135
+
136
+ Returns True when one was dropped.
137
+ """
138
+ for pid, report in list(self._reports.items()):
139
+ if self.key_of(report) == key:
140
+ del self._reports[pid]
141
+ return True
142
+ return False
143
+
144
+ @staticmethod
145
+ def key_of(report):
146
+ return (report["message"], report.get("file"), report.get("lineno"))
147
+
148
+ def _finish(self, pid):
149
+ report = self._reports.pop(pid, None)
150
+ if report is None:
151
+ return
152
+ kwargs = {
153
+ "kind": report["kind"],
154
+ "message": report["message"],
155
+ "file": report["file"],
156
+ "lineno": report["lineno"],
157
+ "pid": report["pid"],
158
+ "process_type": report["process_type"],
159
+ "thread": report["thread"],
160
+ "fatal": report["fatal"],
161
+ "stack": report["stack"] or None,
162
+ "test": report["test"],
163
+ }
164
+ if report["time"] is not None:
165
+ kwargs["time"] = report["time"]
166
+ self.logger.assertion_failure(**kwargs)
167
+
168
+ def _folds_into(self, report, header):
169
+ if header["kind"] != "MOZ_CRASH" or report["kind"] not in (
170
+ "NS_ASSERTION",
171
+ "NS_ABORT",
172
+ ):
173
+ return False
174
+ inner = self._parse_ns_debug(header["message"])
175
+ return inner is not None and self.key_of(inner) == self.key_of(report)
176
+
177
+ def _parse_header(self, line):
178
+ header = None
179
+ if "Hit MOZ_CRASH(" in line:
180
+ header = self._match_location(self.mozCrashRegExp, line, "MOZ_CRASH")
181
+ if header is None and "Assertion failure: " in line:
182
+ header = self._match_location(self.mozAssertRegExp, line, "MOZ_ASSERT")
183
+ if header is None and "###!!! " in line:
184
+ header = self._parse_ns_debug(line)
185
+ return header
186
+
187
+ def _match_location(self, regexp, line, kind):
188
+ match = regexp.match(line)
189
+ if not match:
190
+ return None
191
+ pid = match.group("pid")
192
+ return {
193
+ "kind": kind,
194
+ "message": match.group("message"),
195
+ "file": match.group("file"),
196
+ "lineno": int(match.group("lineno")),
197
+ "pid": int(pid) if pid else None,
198
+ "process_type": None,
199
+ "thread": None,
200
+ "fatal": kind in self.FATAL_KINDS,
201
+ }
202
+
203
+ def _parse_ns_debug(self, line):
204
+ match = self.nsDebugRegExp.match(line)
205
+ if not match:
206
+ return None
207
+ kind = "NS_ASSERTION" if match.group("severity") == "ASSERTION" else "NS_ABORT"
208
+ rest = match.group("rest")
209
+ location = self.nsDebugRestRegExp.match(rest)
210
+ if location:
211
+ message = location.group("message") or ""
212
+ file_ = location.group("file")
213
+ lineno = int(location.group("lineno"))
214
+ else:
215
+ message = rest.rstrip(", ")
216
+ file_ = None
217
+ lineno = None
218
+ return {
219
+ "kind": kind,
220
+ "message": message,
221
+ "file": file_,
222
+ "lineno": lineno,
223
+ "pid": int(match.group("pid")),
224
+ "process_type": match.group("process_type"),
225
+ "thread": match.group("thread"),
226
+ "fatal": kind in self.FATAL_KINDS,
227
+ }
228
+
229
+ def _parse_frame(self, line):
230
+ match = self.frameRegExp.match(line)
231
+ if not match:
232
+ return None
233
+ tail = self.frameTailRegExp.match(match.group("body"))
234
+ if not tail:
235
+ return None
236
+ function = self.rustRegExp.sub("", tail.group("function"))
237
+ location = tail.group("bloc")
238
+ if location is None:
239
+ location = tail.group("ploc")
240
+ frame = {}
241
+ if file_line := self.fileLineRegExp.match(location):
242
+ frame["file"] = file_line.group("file")
243
+ frame["line"] = int(file_line.group("line"))
244
+ elif module := self.moduleOffsetRegExp.match(location):
245
+ frame["module"] = module.group("module")
246
+ frame["module_offset"] = int(module.group("offset"), 16)
247
+ # An unsymbolicated frame is best named by its offset in the profiler.
248
+ if function != "???" or "module_offset" not in frame:
249
+ frame["function"] = function
250
+ return frame
moztest/outcome.py ADDED
@@ -0,0 +1,37 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ from __future__ import annotations
6
+
7
+ import enum
8
+ from collections.abc import Mapping
9
+ from typing import Any
10
+
11
+
12
+ class Outcome(enum.IntEnum):
13
+ """Classification of a test_status or test_end record, from the least to
14
+ the most severe, so the worst outcome of a run is max() of its records'.
15
+
16
+ A record carries ``expected`` only when its ``status`` differs from the
17
+ expected one, ``known_intermittent`` lists the other statuses the test is
18
+ known to produce, and ``will_retry`` marks a run the harness will retry.
19
+ A test fails when its test_end or any of its test_status records is
20
+ UNEXPECTED.
21
+ """
22
+
23
+ EXPECTED = 0
24
+ KNOWN_INTERMITTENT = 1
25
+ WILL_RETRY = 2
26
+ UNEXPECTED = 3
27
+
28
+ @classmethod
29
+ def from_log(cls, data: Mapping[str, Any]) -> Outcome:
30
+ if data.get("will_retry"):
31
+ return cls.WILL_RETRY
32
+ status = data.get("status")
33
+ if "expected" not in data or data["expected"] == status:
34
+ return cls.EXPECTED
35
+ if status in (data.get("known_intermittent") or []):
36
+ return cls.KNOWN_INTERMITTENT
37
+ return cls.UNEXPECTED