-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathbasereport.py
More file actions
325 lines (267 loc) · 11.3 KB
/
basereport.py
File metadata and controls
325 lines (267 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import datetime
import json
import math
import os
import re
import warnings
from pathlib import Path
import pytest
from pytest_html import __version__
from pytest_html import extras
from pytest_html.util import cleanup_unserializable
class BaseReport:
def __init__(self, report_path, config, report_data, template, css):
self._report_path = (
Path.cwd() / Path(os.path.expandvars(report_path)).expanduser()
)
self._report_path.parent.mkdir(parents=True, exist_ok=True)
self._config = config
self._template = template
self._css = css
self._max_asset_filename_length = int(
config.getini("max_asset_filename_length")
)
self._report = report_data
self._report.title = self._report_path.name
@property
def css(self):
# implement in subclasses
return
def _asset_filename(self, test_id, extra_index, test_index, file_extension):
return "{}_{}_{}.{}".format(
re.sub(r"[^\w.]", "_", test_id),
str(extra_index),
str(test_index),
file_extension,
)[-self._max_asset_filename_length :]
def _generate_report(self, self_contained=False):
generated = datetime.datetime.now()
test_data = cleanup_unserializable(self._report.data)
test_data = json.dumps(test_data)
rendered_report = self._template.render(
title=self._report.title,
date=generated.strftime("%d-%b-%Y"),
time=generated.strftime("%H:%M:%S"),
version=__version__,
styles=self.css,
run_count=self._run_count(),
running_state=self._report.running_state,
self_contained=self_contained,
outcomes=self._report.outcomes,
test_data=test_data,
table_head=self._report.table_header,
additional_summary=self._report.additional_summary,
)
self._write_report(rendered_report)
def _generate_environment(self):
try:
from pytest_metadata.plugin import metadata_key
metadata = self._config.stash[metadata_key]
except ImportError:
# old version of pytest-metadata
metadata = self._config._metadata
warnings.warn(
"'pytest-metadata < 3.0.0' is deprecated and support will be dropped in next major version",
DeprecationWarning,
)
for key in metadata.keys():
value = metadata[key]
if self._is_redactable_environment_variable(key):
black_box_ascii_value = 0x2593
metadata[key] = "".join(chr(black_box_ascii_value) for _ in str(value))
return metadata
def _is_redactable_environment_variable(self, environment_variable):
redactable_regexes = self._config.getini("environment_table_redact_list")
for redactable_regex in redactable_regexes:
if re.match(redactable_regex, environment_variable):
return True
return False
def _data_content(self, *args, **kwargs):
pass
def _media_content(self, *args, **kwargs):
pass
def _process_extras(self, report, test_id):
test_index = hasattr(report, "rerun") and report.rerun + 1 or 0
report_extras = getattr(report, "extras", [])
for extra_index, extra in enumerate(report_extras):
content = extra["content"]
asset_name = self._asset_filename(
test_id.encode("utf-8").decode("unicode_escape"),
extra_index,
test_index,
extra["extension"],
)
if extra["format_type"] == extras.FORMAT_JSON:
content = json.dumps(content)
extra["content"] = self._data_content(
content, asset_name=asset_name, mime_type=extra["mime_type"]
)
if extra["format_type"] == extras.FORMAT_TEXT:
if isinstance(content, bytes):
content = content.decode("utf-8")
extra["content"] = self._data_content(
content, asset_name=asset_name, mime_type=extra["mime_type"]
)
if extra["format_type"] in [extras.FORMAT_IMAGE, extras.FORMAT_VIDEO]:
extra["content"] = self._media_content(
content, asset_name=asset_name, mime_type=extra["mime_type"]
)
return report_extras
def _write_report(self, rendered_report):
with self._report_path.open("w", encoding="utf-8") as f:
f.write(rendered_report)
def _run_count(self):
relevant_outcomes = ["passed", "failed", "xpassed", "xfailed"]
counts = 0
for outcome in self._report.outcomes.keys():
if outcome in relevant_outcomes:
counts += self._report.outcomes[outcome]["value"]
plural = counts > 1
duration = _format_duration(self._report.total_duration)
if self._report.running_state == "finished":
return f"{counts} {'tests' if plural else 'test'} took {duration}."
return f"{counts}/{self._report.collected_items} {'tests' if plural else 'test'} done."
def _hydrate_data(self, data, cells):
table_len = len(self._report.table_header)
for index, cell in enumerate(cells):
# extract column name and data if column is sortable
if index < table_len and "sortable" in self._report.table_header[index]:
name_match = re.search(r"col-(\w+)", cell)
data_match = re.search(r"<td.*?>(.*?)</td>", cell)
if name_match and data_match:
data[name_match.group(1)] = data_match.group(1)
@pytest.hookimpl(trylast=True)
def pytest_sessionstart(self, session):
self._report.set_data("environment", self._generate_environment())
session.config.hook.pytest_html_report_title(report=self._report)
headers = self._report.table_header
session.config.hook.pytest_html_results_table_header(cells=headers)
self._report.table_header = _fix_py(headers)
self._report.running_state = "started"
self._generate_report()
@pytest.hookimpl(trylast=True)
def pytest_sessionfinish(self, session):
session.config.hook.pytest_html_results_summary(
prefix=self._report.additional_summary["prefix"],
summary=self._report.additional_summary["summary"],
postfix=self._report.additional_summary["postfix"],
session=session,
)
self._report.running_state = "finished"
self._generate_report()
@pytest.hookimpl(trylast=True)
def pytest_terminal_summary(self, terminalreporter):
terminalreporter.write_sep(
"-",
f"Generated html report: {self._report_path.as_uri()}",
)
@pytest.hookimpl(trylast=True)
def pytest_collection_finish(self, session):
self._report.collected_items = len(session.items)
@pytest.hookimpl(trylast=True)
def pytest_runtest_logreport(self, report):
if hasattr(report, "duration_formatter"):
warnings.warn(
"'duration_formatter' has been removed and no longer has any effect!"
"Please use the 'pytest_html_duration_format' hook instead.",
DeprecationWarning,
)
outcome = _process_outcome(report)
try:
# hook returns as list for some reason
duration = self._config.hook.pytest_html_duration_format(
duration=report.duration
)[0]
except IndexError:
duration = _format_duration(report.duration)
self._report.total_duration += report.duration
test_id = report.nodeid
if report.when != "call":
test_id += f"::{report.when}"
data = {
"extras": self._process_extras(report, test_id),
}
links = [
extra
for extra in data["extras"]
if extra["format_type"] in ["json", "text", "url"]
]
cells = [
f'<td class="col-result">{outcome}</td>',
f'<td class="col-testId">{test_id}</td>',
f'<td class="col-duration">{duration}</td>',
f'<td class="col-links">{_process_links(links)}</td>',
]
self._config.hook.pytest_html_results_table_row(report=report, cells=cells)
if not cells:
return
cells = _fix_py(cells)
self._hydrate_data(data, cells)
data["resultsTableRow"] = cells
# don't count passed setups and teardowns
if not (report.when in ["setup", "teardown"] and report.outcome == "passed"):
self._report.outcomes = outcome
processed_logs = _process_logs(report)
self._config.hook.pytest_html_results_table_html(
report=report, data=processed_logs
)
if self._report.add_test(data, report, processed_logs):
self._generate_report()
def _format_duration(duration):
if duration < 1:
return "{} ms".format(round(duration * 1000))
hours = math.floor(duration / 3600)
remaining_seconds = duration % 3600
minutes = math.floor(remaining_seconds / 60)
remaining_seconds = remaining_seconds % 60
seconds = round(remaining_seconds)
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
def _is_error(report):
return report.when in ["setup", "teardown"] and report.outcome == "failed"
def _process_logs(report):
log = []
if report.longreprtext:
log.append(report.longreprtext.replace("<", "<").replace(">", ">") + "\n")
# Don't add captured output to reruns
if report.outcome != "rerun":
for section in report.sections:
header, content = section
log.append(f"{' ' + header + ' ':-^80}\n{content}")
# weird formatting related to logs
if "log" in header:
log.append("")
if "call" in header:
log.append("")
if not log:
log.append("No log output captured.")
return log
def _process_outcome(report):
if _is_error(report):
return "Error"
if hasattr(report, "wasxfail"):
if report.outcome in ["passed", "failed"]:
return "XPassed"
if report.outcome == "skipped":
return "XFailed"
return report.outcome.capitalize()
def _process_links(links):
a_tag = '<a target="_blank" href="{content}" class="col-links__extra {format_type}">{name}</a>'
return "".join([a_tag.format_map(link) for link in links])
def _fix_py(cells):
# backwards-compat
new_cells = []
for html in cells:
if not isinstance(html, str):
if html.__module__.startswith("py."):
warnings.warn(
"The 'py' module is deprecated and support "
"will be removed in a future release.",
DeprecationWarning,
)
html = str(html)
html = html.replace("col=", "data-column-type=")
new_cells.append(html)
return new_cells