pytest-report-extras 1.0.0__tar.gz

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.
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.3
2
+ Name: pytest-report-extras
3
+ Version: 1.0.0
4
+ Summary: Pytest plugin to enhance pytest-html and allure reports by adding comments, screenshots and webpage sources.
5
+ Keywords: pytest,selenium,playwright,webtest,webtesting
6
+ Author-email: Harmin Parra Rueda <harmin.rueda@gmail.com>
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ Classifier: Framework :: Pytest
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Topic :: Software Development :: Quality Assurance
12
+ Classifier: Topic :: Software Development :: Testing
13
+ Requires-Dist: pytest >= 7.0.0
14
+ Requires-Dist: pytest-html >= 4.0.0
15
+ Requires-Dist: pyyaml >= 6.0.2
16
+
17
+ # pytest-webtest-extras
18
+
19
+ Pytest plugin to enhance pytest-html and Allure reports of webtest projects with screenshots, comments and webpage sources.
20
+
21
+ ![](https://img.shields.io/badge/license-MIT%202.0-blue.svg)
22
+
23
+ ## Resources ##
24
+
25
+ - [Documentation](https://pytest-webtest-extras.readthedocs.io/en/stable/)
26
+ - [Issue tracker](https://github.com/harmin-parra/pytest-webtest-extras/issues)
27
+ - [Source code](https://github.com/harmin-parra/pytest-webtest-extras)
28
+
29
+ <br/>
30
+
31
+ If you like this software, consider contributing to the project through [buy me a coffee](https://www.buymeacoffee.com/harmin)
32
+
@@ -0,0 +1,15 @@
1
+ # pytest-webtest-extras
2
+
3
+ Pytest plugin to enhance pytest-html and Allure reports of webtest projects with screenshots, comments and webpage sources.
4
+
5
+ ![](https://img.shields.io/badge/license-MIT%202.0-blue.svg)
6
+
7
+ ## Resources ##
8
+
9
+ - [Documentation](https://pytest-webtest-extras.readthedocs.io/en/stable/)
10
+ - [Issue tracker](https://github.com/harmin-parra/pytest-webtest-extras/issues)
11
+ - [Source code](https://github.com/harmin-parra/pytest-webtest-extras)
12
+
13
+ <br/>
14
+
15
+ If you like this software, consider contributing to the project through [buy me a coffee](https://www.buymeacoffee.com/harmin)
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["flit_core >=3.4"]
3
+ build-backend = "flit_core.buildapi"
4
+
5
+
6
+ [project]
7
+ name = "pytest-report-extras"
8
+ version = "1.0.0"
9
+ description = "Pytest plugin to enhance pytest-html and allure reports by adding comments, screenshots and webpage sources."
10
+ readme = "README.md"
11
+ #license = "MIT"
12
+ authors = [
13
+ {name = "Harmin Parra Rueda", email="harmin.rueda@gmail.com"},
14
+ ]
15
+ requires-python = ">=3.10"
16
+ dependencies = [
17
+ 'pytest >= 7.0.0',
18
+ 'pytest-html >= 4.0.0',
19
+ 'pyyaml >= 6.0.2',
20
+ ]
21
+ classifiers = [
22
+ "Framework :: Pytest",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Topic :: Software Development :: Quality Assurance",
25
+ "Topic :: Software Development :: Testing",
26
+ ]
27
+ keywords = [
28
+ "pytest",
29
+ "selenium",
30
+ "playwright",
31
+ "webtest",
32
+ "webtesting",
33
+ ]
34
+
35
+
36
+ [project.entry-points.pytest11]
37
+ pytest_report_extras = "pytest_report_extras.plugin"
@@ -0,0 +1,204 @@
1
+ import base64
2
+ import html
3
+ import importlib
4
+ import json
5
+ import re
6
+ import xml.parsers.expat as expat
7
+ import xml.dom.minidom as xdom
8
+ import yaml
9
+ from . import utils
10
+
11
+
12
+ # Counter used for image and page source files naming
13
+ count = 0
14
+
15
+
16
+ def counter() -> int:
17
+ """ Returns a suffix used for image and webpage source file naming """
18
+ global count
19
+ count += 1
20
+ return count
21
+
22
+
23
+ class CodeBlockText:
24
+ """
25
+ Class to represent text to be formatted as code-block in a <pre> HTML tag.
26
+ """
27
+ def __init__(self, text: str = None, mime: str = "text/plain"):
28
+ self.text = None if text is None or text == "" else text
29
+ self.mime = mime
30
+
31
+ def __str__(self):
32
+ if self.text is None:
33
+ return ""
34
+ return f'<pre class="extras_pre">{utils.escape_html(self.text)}</pre>'
35
+
36
+ def get_escaped_text(self):
37
+ return utils.escape_html(self.text)
38
+
39
+ def get_html_tag(self):
40
+ if self.text is None:
41
+ return ""
42
+ return f'<pre class="extras_pre">{utils.escape_html(self.text)}</pre>'
43
+
44
+
45
+ class Extras:
46
+ """
47
+ Class to hold pytest-html 'extras' to be added for each test in the HTML report.
48
+ """
49
+
50
+ def __init__(self, report_folder, fx_screenshots, fx_sources, report_allure):
51
+ """
52
+ Args:
53
+ report_folder (str): The 'report_folder' fixture.
54
+ fx_screenshots (str): The 'screenshots' fixture.
55
+ fx_sources (bool): The 'sources' fixture.
56
+ report_allure (str): The 'report_allure' fixture.
57
+ """
58
+ self.images = []
59
+ self.sources = []
60
+ self.comments = []
61
+ self.target = None
62
+ self._fx_screenshots = fx_screenshots
63
+ self._fx_sources = fx_sources
64
+ self._folder = report_folder
65
+ self._allure = report_allure
66
+
67
+ def step(
68
+ self,
69
+ comment: str = None,
70
+ target=None,
71
+ code_block: CodeBlockText = None,
72
+ full_page: bool = True,
73
+ page_source: bool = False,
74
+ escape_html: bool = False
75
+ ):
76
+ """
77
+ Adds a step in the pytest-html report: screenshot, comment and webpage source.
78
+ The screenshot is saved in <forder_report>/screenshots folder.
79
+ The webpage source is saved in <forder_report>/sources folder.
80
+
81
+ Args:
82
+ comment (str): The comment of the test step.
83
+ target (WebDriver | WebElement | Page | Locator): The target of the screenshot.
84
+ code_block (CodeBlockText): The code-block formatted content to be added.
85
+ full_page (bool): Whether to take a full-page screenshot.
86
+ page_source (bool): Whether to include the page source. Overrides the global `sources` fixture.
87
+ escape_html (bool): Whether to escape HTML characters in the comment.
88
+ """
89
+ if target is not None:
90
+ if importlib.util.find_spec('selenium') is not None:
91
+ from selenium.webdriver.remote.webdriver import WebDriver
92
+ if isinstance(target, WebDriver) and self.target is None:
93
+ self.target = target
94
+
95
+ if importlib.util.find_spec('playwright') is not None:
96
+ from playwright.sync_api import Page
97
+ if isinstance(target, Page) and self.target is None:
98
+ self.target = target
99
+
100
+ if self._fx_screenshots == "last" and target is not None:
101
+ return
102
+
103
+ # Get the 3 parts of the test step: image, comment and source
104
+ image, source = utils.get_screenshot(target, full_page, self._fx_sources or page_source)
105
+ comment = "" if comment is None else comment
106
+ comment = html.escape(comment, quote=True) if escape_html else comment
107
+
108
+ # Add extras to Allure report if allure-pytest plugin is being used.
109
+ if self._allure and importlib.util.find_spec('allure') is not None:
110
+ import allure
111
+ if image is not None:
112
+ allure.attach(image, name=comment, attachment_type=allure.attachment_type.PNG)
113
+ # Attach the webpage source
114
+ if source is not None:
115
+ allure.attach(source, name="page source", attachment_type=allure.attachment_type.TEXT)
116
+ if code_block is not None and code_block.text is not None:
117
+ allure.attach(code_block.text, name=comment, attachment_type=code_block.mime)
118
+
119
+ # Add extras to pytest-html report
120
+ self._save_screenshot(image, source)
121
+ if code_block is not None and code_block.text is not None:
122
+ comment += '\n' + code_block.get_html_tag()
123
+ self.comments.append(comment)
124
+
125
+ def _save_screenshot(self, image: bytes | str, source: str):
126
+ """
127
+ Saves the pytest-html 'extras': screenshot, comment and webpage source.
128
+ The screenshot is saved in <forder_report>/screenshots folder.
129
+ The webpage source is saved in <forder_report>/sources folder.
130
+
131
+ Args:
132
+ image (bytes | str): The screenshot as bytes or base64 string.
133
+ source (str): The webpage source code.
134
+ """
135
+ if isinstance(image, str):
136
+ try:
137
+ image = base64.b64decode(image.encode())
138
+ except:
139
+ image = None
140
+ index = -1 if image is None else counter()
141
+ link_image = utils.get_image_link(self._folder, index, image)
142
+ self.images.append(link_image)
143
+ link_source = None
144
+ if source is not None:
145
+ link_source = utils.get_source_link(self._folder, index, source)
146
+ self.sources.append(link_source)
147
+
148
+ def format_code_block(self, text: str, mime="text/plain") -> CodeBlockText:
149
+ return CodeBlockText(text, mime)
150
+
151
+ def format_json_file(self, filepath: str, indent=4) -> CodeBlockText:
152
+ """
153
+ Formats the contents of a JSON file.
154
+ """
155
+ f = open(filepath, 'r')
156
+ content = f.read()
157
+ f.close()
158
+ return self.format_json_str(content, indent)
159
+
160
+ def format_json_str(self, text: str, indent: int = 4) -> CodeBlockText:
161
+ """
162
+ Formats a string holding a JSON document.
163
+ """
164
+ text = json.loads(text)
165
+ return CodeBlockText(json.dumps(text, indent=indent), "application/json")
166
+
167
+ def format_xml_file(self, filepath: str, indent: int = 4) -> CodeBlockText:
168
+ """
169
+ Formats the contents of a XML file.
170
+ """
171
+ f = open(filepath, 'r')
172
+ content = f.read()
173
+ f.close()
174
+ return self.format_xml_str(content, indent)
175
+
176
+ def format_xml_str(self, text: str, indent: int = 4) -> CodeBlockText:
177
+ """
178
+ Formats a string holding a XML document.
179
+ """
180
+ result = None
181
+ try:
182
+ result = (xdom.parseString(re.sub(r"\n\s+", '', text).replace('\n', ''))
183
+ .toprettyxml(indent=" " * indent))
184
+ except expat.ExpatError:
185
+ if text is None:
186
+ text = 'None'
187
+ result = "Raw text:\n" + text
188
+ return CodeBlockText(result, "application/xml")
189
+
190
+ def format_yaml_file(self, filepath: str, indent: int = 4) -> CodeBlockText:
191
+ """
192
+ Formats the contents of a YAML file.
193
+ """
194
+ f = open(filepath, 'r')
195
+ content = f.read()
196
+ f.close()
197
+ return self.format_yaml_str(content, indent)
198
+
199
+ def format_yaml_str(self, text: str, indent: int = 4) -> CodeBlockText:
200
+ """
201
+ Formats a string containing a YAML document.
202
+ """
203
+ text = yaml.safe_load(text)
204
+ return CodeBlockText(yaml.dump(text, indent=indent), "application/yaml")
@@ -0,0 +1,301 @@
1
+ import pathlib
2
+ import pytest
3
+ import re
4
+ from . import utils
5
+ from .extras import Extras
6
+
7
+
8
+ #
9
+ # Definition of test options
10
+ #
11
+ def pytest_addoption(parser):
12
+ parser.addini(
13
+ "extras_screenshots",
14
+ type="string",
15
+ default="all",
16
+ help="The screenshots to include in the report. Accepted values: all, last."
17
+ )
18
+ parser.addini(
19
+ "extras_sources",
20
+ type="bool",
21
+ default=False,
22
+ help="Whether to include webpage sources."
23
+ )
24
+ parser.addini(
25
+ "extras_description_tag",
26
+ type="string",
27
+ default="pre",
28
+ help="HTML tag for the test description. Accepted values: h1, h2, h3, p or pre.",
29
+ )
30
+ parser.addini(
31
+ "extras_issue_link_pattern",
32
+ type="string",
33
+ default=None,
34
+ help="The issue link pattern. Example: https://jira.com/issues/{}",
35
+ )
36
+ parser.addini(
37
+ "extras_issue_key_pattern",
38
+ type="string",
39
+ default=None,
40
+ help="The issue key pattern. Example: PROJ-\\d{1,4}",
41
+ )
42
+
43
+
44
+ fx_issue_link = None
45
+ fx_issue_key = None
46
+
47
+
48
+ #
49
+ # Read test parameters
50
+ #
51
+ @pytest.fixture(scope='session')
52
+ def screenshots(request):
53
+ value = request.config.getini("extras_screenshots")
54
+ if value in ("all", "last"):
55
+ return value
56
+ else:
57
+ return "all"
58
+
59
+
60
+ @pytest.fixture(scope='session')
61
+ def report_folder(request):
62
+ """ The folder storing the pytest-html report """
63
+ htmlpath = request.config.getoption("--html")
64
+ return utils.get_folder(htmlpath)
65
+
66
+
67
+ @pytest.fixture(scope='session')
68
+ def report_allure(request):
69
+ """ Whether the allure-pytest plugin is being used """
70
+ return request.config.getoption("--alluredir", default=None) is not None
71
+
72
+
73
+ @pytest.fixture(scope='session')
74
+ def report_css(request):
75
+ """ The filepath of the CSS to include in the report. """
76
+ return request.config.getoption("--css")
77
+
78
+
79
+ @pytest.fixture(scope='session')
80
+ def description_tag(request):
81
+ """ The HTML tag for the description of each test. """
82
+ tag = request.config.getini("extras_description_tag")
83
+ return tag if tag in ("h1", "h2", "h3", "p", "pre") else "h2"
84
+
85
+
86
+ @pytest.fixture(scope='session')
87
+ def sources(request):
88
+ """ Whether to include webpage sources in the report. """
89
+ return request.config.getini("extras_sources")
90
+
91
+
92
+ @pytest.fixture(scope='session')
93
+ def issue_link_pattern(request):
94
+ """ The issue link pattern. """
95
+ global fx_issue_link
96
+ fx_issue_link = request.config.getini("extras_issue_link_pattern")
97
+ return fx_issue_link
98
+
99
+
100
+ @pytest.fixture(scope='session')
101
+ def issue_key_pattern(request):
102
+ """ The issue link pattern. """
103
+ global fx_issue_key
104
+ fx_issue_key = request.config.getini("extras_issue_key_pattern")
105
+ return fx_issue_key
106
+
107
+
108
+ @pytest.fixture(scope='session')
109
+ def check_options(request, report_folder):
110
+ """ Verifies preconditions before using this plugin. """
111
+ utils.check_html_option(report_folder)
112
+ utils.create_assets(report_folder)
113
+
114
+
115
+ #
116
+ # Test fixture
117
+ #
118
+ @pytest.fixture(scope='function')
119
+ def report(request, report_folder, screenshots, sources, report_allure, check_options):
120
+ return Extras(report_folder, screenshots, sources, report_allure)
121
+
122
+
123
+ #
124
+ # Hookers
125
+ #
126
+ passed = 0
127
+ failed = 0
128
+ xfailed = 0
129
+ skipped = 0
130
+ xpassed = 0
131
+ error_setup = 0
132
+ error_teardown = 0
133
+
134
+
135
+ def pytest_sessionfinish(session, exitstatus):
136
+ global skipped, failed, xfailed, passed, xpassed, error_setup, error_teardown
137
+ if xpassed >= 0 and failed == 0 and error_setup == 0:
138
+ session.exitstatus = 0
139
+ if (xfailed + skipped + error_teardown + error_setup > 0) and failed == 0:
140
+ session.exitstatus = 6
141
+
142
+
143
+ @pytest.hookimpl(hookwrapper=True)
144
+ def pytest_runtest_makereport(item, call):
145
+ global skipped, failed, xfailed, passed, xpassed, error_setup, error_teardown
146
+ global fx_issue_link, fx_issue_key
147
+
148
+ """ Override report generation. """
149
+ pytest_html = item.config.pluginmanager.getplugin('html')
150
+ outcome = yield
151
+ report = outcome.get_result()
152
+ extras = getattr(report, 'extras', [])
153
+ issues = []
154
+
155
+ # Is the test item using the 'report' fixtures?
156
+ # if not ("request" in item.funcargs and "report" in item.funcargs):
157
+ # return
158
+
159
+ try:
160
+ feature_request = item.funcargs['request']
161
+ fx_issue_link = feature_request.getfixturevalue("issue_link_pattern")
162
+ fx_issue_key = feature_request.getfixturevalue("issue_key_pattern")
163
+ except:
164
+ pass
165
+
166
+ # Update status variables
167
+ if call.when == 'setup':
168
+ # For tests with the pytest.mark.skip fixture
169
+ if (report.skipped and hasattr(call, 'excinfo')
170
+ and call.excinfo is not None
171
+ and call.excinfo.typename == 'Skipped'):
172
+ issues = re.sub(r"[^\w-]", " ", call.excinfo.value.msg).split()
173
+ skipped += 1
174
+ # For setup fixture
175
+ if report.failed and call.excinfo is not None:
176
+ error_setup += 1
177
+
178
+ # Update status variables
179
+ if call.when == 'teardown':
180
+ if report.failed and call.excinfo is not None:
181
+ error_teardown += 1
182
+
183
+ if report.when == 'call':
184
+ # Update status variables
185
+ if report.failed:
186
+ failed += 1
187
+ if report.skipped and not hasattr(report, "wasxfail"):
188
+ skipped += 1
189
+ if report.skipped and hasattr(report, "wasxfail"):
190
+ xfailed += 1
191
+ if report.passed and hasattr(report, "wasxfail"):
192
+ xpassed += 1
193
+ if report.passed and not hasattr(report, "wasxfail"):
194
+ passed += 1
195
+
196
+ # Check for issue links to add
197
+ # For tests with pytest.fail, pytest.xfail or pytest.skip call
198
+ if (hasattr(call, 'excinfo')
199
+ and call.excinfo is not None
200
+ and (call.excinfo.typename in ('Failed', 'XFailed', 'Skipped'))):
201
+ issues = re.sub(r"[^\w-]", " ", call.excinfo.value.msg).split()
202
+ # For tests with the pytest.mark.xfail fixture
203
+ elif hasattr(report, 'wasxfail'):
204
+ issues = re.sub(r"[^\w-]", " ", report.wasxfail).split()
205
+
206
+ # Is the test item using the 'report' fixtures?
207
+ if "request" in item.funcargs and "report" in item.funcargs:
208
+
209
+ # Get test fixture values
210
+ feature_request = item.funcargs['request']
211
+ fx_report = feature_request.getfixturevalue("report")
212
+ fx_description_tag = feature_request.getfixturevalue("description_tag")
213
+ fx_screenshots = feature_request.getfixturevalue("screenshots")
214
+ # fx_issue_link = feature_request.getfixturevalue("issue_link_pattern")
215
+ # fx_issue_key = feature_request.getfixturevalue("issue_key_pattern")
216
+ target = fx_report.target
217
+
218
+ # Append test description and execution exception trace, if any.
219
+ description = item.function.__doc__ if hasattr(item, 'function') else None
220
+ utils.append_header(call, report, extras, pytest_html, description, fx_description_tag)
221
+
222
+ if not utils.check_lists_length(report, fx_report):
223
+ return
224
+
225
+ # Generate HTML code for the extras to be added in the report
226
+ rows = "" # The HTML table rows of the test report
227
+
228
+ # To check test failure/skip
229
+ xfail = hasattr(report, 'wasxfail')
230
+ wasxpassed = xfail and report.wasxfail == "xpassed"
231
+ wasxfailure = xfail and report.wasxfail == "xfailure"
232
+ failure = xfail or report.outcome in ("failed", "skipped")
233
+
234
+ # Add steps in the report
235
+ for i in range(len(fx_report.images)):
236
+ rows += utils.get_table_row_tag(
237
+ fx_report.comments[i],
238
+ fx_report.images[i],
239
+ fx_report.sources[i]
240
+ )
241
+
242
+ # Add screenshot for last step
243
+ if fx_screenshots == "last" and failure is False and target is not None:
244
+ fx_report._fx_screenshots = "all" # To force screenshot gathering
245
+ fx_report.step(f"Last screenshot", target)
246
+ rows += utils.get_table_row_tag(
247
+ fx_report.comments[-1],
248
+ fx_report.images[-1],
249
+ fx_report.sources[-1]
250
+ )
251
+
252
+ # Add screenshot for test failure/skip
253
+ if failure and target is not None:
254
+ if report.outcome == "failed" or wasxpassed:
255
+ event_class = "failure"
256
+ else:
257
+ event_class = "skip"
258
+ if report.outcome == "failed" or wasxfailure or wasxpassed or (report.skipped and xfail):
259
+ event_label = "failure"
260
+ else:
261
+ event_label = "skip"
262
+ fx_report._fx_screenshots = "all" # To force screenshot gathering
263
+ fx_report.step(f"Last screenshot before {event_label}", target)
264
+ rows += utils.get_table_row_tag(
265
+ fx_report.comments[-1],
266
+ fx_report.images[-1],
267
+ fx_report.sources[-1],
268
+ event_class
269
+ )
270
+
271
+ # Add horizontal line between the header and the comments/screenshots
272
+ if len(extras) > 0 and len(rows) > 0:
273
+ extras.append(pytest_html.extras.html(f'<hr class="extras_separator">'))
274
+
275
+ # Append extras
276
+ if rows != "":
277
+ table = (
278
+ '<table style="width: 100%;">'
279
+ + rows +
280
+ "</table>"
281
+ )
282
+ extras.append(pytest_html.extras.html(table))
283
+
284
+ # Identify issue patterns and add issue links to extras
285
+ if fx_issue_key is not None and fx_issue_link is not None:
286
+ for issue in issues:
287
+ if re.match(rf"^{fx_issue_key}$", issue):
288
+ extras.append(pytest_html.extras.url(fx_issue_link.replace("{}", issue), name=issue))
289
+
290
+ report.extras = extras
291
+
292
+
293
+ @pytest.hookimpl(trylast=False)
294
+ def pytest_configure(config):
295
+ # Add CSS file to --css request option for pytest-html
296
+ # This code doesn't always run before pytest-html configuration
297
+ report_css = config.getoption("--css")
298
+ resources_path = pathlib.Path(__file__).parent.joinpath("resources")
299
+ style_css = pathlib.Path(resources_path, "style.css")
300
+ # report_css.insert(0, style_css)
301
+ report_css.append(style_css)
@@ -0,0 +1,60 @@
1
+ .logwrapper {
2
+ max-height: 100px;
3
+ }
4
+
5
+ .extras_td {
6
+ width: 320px;
7
+ /* text-align: center; */
8
+ }
9
+
10
+ .extras_td_div {
11
+ text-align: center;
12
+ }
13
+
14
+ .extras_separator {
15
+ height:2px;
16
+ background-color: gray;
17
+ /* display: none; */
18
+ }
19
+
20
+ .extras_description {
21
+ color: black;
22
+ font-size: larger
23
+ }
24
+
25
+ .extras_exception {
26
+ color: red;
27
+ }
28
+
29
+ .extras_comment {
30
+ font-family: monospace;
31
+ color: blue;
32
+ }
33
+
34
+ .extras_pre {
35
+ margin-left: 30px;
36
+ color: black;
37
+ }
38
+
39
+ .extras_failure {
40
+ font-family: monospace;
41
+ color: red;
42
+ }
43
+
44
+ .extras_skip {
45
+ font-family: monospace;
46
+ color: orange;
47
+ }
48
+
49
+ .extras_image {
50
+ border: 1px solid black;
51
+ width: 300px;
52
+ height: 170px;
53
+ object-fit: cover;
54
+ object-position: top;
55
+ }
56
+
57
+ .extras_page_src {
58
+ font-size: 12px;
59
+ color: #999;
60
+ }
@@ -0,0 +1,405 @@
1
+ import base64
2
+ import html
3
+ import importlib
4
+ import os
5
+ import pathlib
6
+ import pytest
7
+ import shutil
8
+ import sys
9
+ import traceback
10
+
11
+
12
+ #
13
+ # Auxiliary functions to check options and fixtures
14
+ #
15
+ def check_html_option(htmlpath):
16
+ """ Verifies if the --html has been set by the user. """
17
+ if htmlpath is None:
18
+ msg = ("It seems you are using pytest-report-extras plugin.\n"
19
+ "pytest-html plugin is required.\n"
20
+ "'--html' option is missing.\n")
21
+ print(msg, file=sys.stderr)
22
+ sys.exit(pytest.ExitCode.USAGE_ERROR)
23
+
24
+
25
+ def getini(config, name):
26
+ """ Workaround for bug https://github.com/pytest-dev/pytest/issues/11282 """
27
+ value = config.getini(name)
28
+ if not isinstance(value, str):
29
+ value = None
30
+ return value
31
+
32
+
33
+ def get_folder(filepath):
34
+ """
35
+ Returns the folder of a filepath.
36
+
37
+ Args:
38
+ filepath (str): The filepath.
39
+ """
40
+ folder = None
41
+ if filepath is not None:
42
+ folder = os.path.dirname(filepath)
43
+ return folder
44
+
45
+
46
+ def check_lists_length(report, fx_extras):
47
+ """ Verifies if the images, comments and page sources lists have the same lenght """
48
+ message = ('"images", "comments" and "sources" lists don\'t have the same length. '
49
+ "Screenshots won't be logged for this test in pytest-html report.")
50
+ if not (len(fx_extras.images) == len(fx_extras.comments) == len(fx_extras.sources)):
51
+ log_error_message(report, message)
52
+ return False
53
+ else:
54
+ return True
55
+
56
+
57
+ def create_assets(report_folder):
58
+ """ Recreate screenshots and webpage sources folders. """
59
+ # Recreate screenshots_folder
60
+ folder = ""
61
+ if report_folder is not None and report_folder != '':
62
+ folder = f"{report_folder}{os.sep}"
63
+ # Create page sources folder
64
+ shutil.rmtree(f"{folder}sources", ignore_errors=True)
65
+ pathlib.Path(f"{folder}sources").mkdir(parents=True)
66
+ # Create screenshots folder
67
+ shutil.rmtree(f"{folder}screenshots", ignore_errors=True)
68
+ pathlib.Path(f"{folder}screenshots").mkdir(parents=True)
69
+ # Copy error.png to screenshots folder
70
+ resources_path = pathlib.Path(__file__).parent.joinpath("resources")
71
+ error_img = pathlib.Path(resources_path, "error.png")
72
+ shutil.copy(str(error_img), f"{folder}screenshots")
73
+
74
+
75
+ #
76
+ # Persistence functions
77
+ #
78
+ def get_full_page_screenshot_chromium(driver):
79
+ # get window size
80
+ page_rect = driver.execute_cdp_cmd("Page.getLayoutMetrics", {})
81
+ # parameters needed for full page screenshot
82
+ # note we are setting the width and height of the viewport to screenshot, same as the site's content size
83
+ screenshot_config = {
84
+ 'captureBeyondViewport': True,
85
+ 'fromSurface': True,
86
+ 'format': "png",
87
+ 'clip': {
88
+ 'x': 0,
89
+ 'y': 0,
90
+ 'width': page_rect['contentSize']['width'],
91
+ 'height': page_rect['contentSize']['height'],
92
+ 'scale': 1,
93
+ },
94
+ }
95
+ # Dictionary with 1 key: data
96
+ base_64_png = driver.execute_cdp_cmd("Page.captureScreenshot", screenshot_config)
97
+ return base64.urlsafe_b64decode(base_64_png['data'])
98
+
99
+
100
+ def get_screenshot(target, full_page=True, page_source=False):
101
+ image = None
102
+ source = None
103
+
104
+ if target is not None:
105
+ if importlib.util.find_spec('selenium') is not None:
106
+ from selenium.webdriver.remote.webdriver import WebDriver
107
+ from selenium.webdriver.remote.webelement import WebElement
108
+ if isinstance(target, WebElement) or isinstance(target, WebDriver):
109
+ image, source = _get_selenium_screenshot(target, full_page, page_source)
110
+
111
+ if importlib.util.find_spec('playwright') is not None:
112
+ from playwright.sync_api import Page
113
+ from playwright.sync_api import Locator
114
+ if isinstance(target, Page) or isinstance(target, Locator):
115
+ image, source = _get_playwright_screenshot(target, full_page, page_source)
116
+
117
+ return image, source
118
+
119
+
120
+ def _get_selenium_screenshot(target, full_page=True, page_source=False):
121
+ """
122
+ Returns the screenshot in PNG format as bytes and the HTML source code.
123
+ target (WebDriver | WebElement): The target of the screenshot.
124
+ full_page (bool): Whether to take a full-page screenshot if the target is a Page instance.
125
+ Defaults to True.
126
+ """
127
+ image = None
128
+ source = None
129
+
130
+ if importlib.util.find_spec('selenium') is not None:
131
+ from selenium.webdriver.chrome.webdriver import WebDriver as WebDriver_Chrome
132
+ from selenium.webdriver.chromium.webdriver import ChromiumDriver as WebDriver_Chromium
133
+ from selenium.webdriver.edge.webdriver import WebDriver as WebDriver_Edge
134
+ from selenium.webdriver.remote.webelement import WebElement
135
+ else:
136
+ print("Selenium module is not installed.", file=sys.stderr)
137
+ return image, source
138
+
139
+ if isinstance(target, WebElement):
140
+ image = target.screenshot_as_png
141
+ else:
142
+ if full_page is True:
143
+ if hasattr(target, "get_full_page_screenshot_as_png"):
144
+ image = target.get_full_page_screenshot_as_png()
145
+ else:
146
+ if type(target) in (WebDriver_Chrome, WebDriver_Chromium, WebDriver_Edge):
147
+ try:
148
+ image = get_full_page_screenshot_chromium(target)
149
+ except:
150
+ image = target.get_screenshot_as_png()
151
+ else:
152
+ image = target.get_screenshot_as_png()
153
+ else:
154
+ image = target.get_screenshot_as_png()
155
+ if page_source:
156
+ source = target.page_source
157
+ return image, source
158
+
159
+
160
+ def _get_playwright_screenshot(target, full_page=True, page_source=False):
161
+ """
162
+ Returns a screenshot in PNG format as bytes.
163
+ target (Page | Locator): The target of the screenshot.
164
+ full_page (bool): Whether to take a full-page screenshot if the target is a Page instance.
165
+ Defaults to True.
166
+ """
167
+ image = None
168
+ source = None
169
+
170
+ if importlib.util.find_spec('playwright') is not None:
171
+ from playwright.sync_api import Page
172
+ from playwright.sync_api import Locator
173
+ assert isinstance(target, Page) or isinstance(target, Locator)
174
+ else:
175
+ print("Playwright module is not installed.", file=sys.stderr)
176
+ return image, source
177
+
178
+ if isinstance(target, Page):
179
+ image = target.screenshot(full_page=full_page)
180
+ if page_source:
181
+ source = target.content()
182
+ else:
183
+ image = target.screenshot()
184
+
185
+ return image, source
186
+
187
+
188
+ def get_image_link(report_folder, index, image):
189
+ if image is None:
190
+ return None
191
+ link = f"screenshots{os.sep}image-{index}.png"
192
+ folder = ""
193
+ if report_folder is not None and report_folder != '':
194
+ folder = f"{report_folder}{os.sep}"
195
+ filename = folder + link
196
+ try:
197
+ f = open(filename, 'wb')
198
+ f.write(image)
199
+ f.close()
200
+ except Exception as e:
201
+ trace = traceback.format_exc()
202
+ link = f"screenshots{os.sep}error.png"
203
+ print(f"{str(e)}\n\n{trace}", file=sys.stderr)
204
+ finally:
205
+ return link
206
+
207
+
208
+ def get_source_link(report_folder, index, source):
209
+ link = f"sources{os.sep}page-{index}.txt"
210
+ folder = ""
211
+ if report_folder is not None and report_folder != '':
212
+ folder = f"{report_folder}{os.sep}"
213
+ filename = folder + link
214
+ try:
215
+ f = open(filename, 'w', encoding="utf-8")
216
+ f.write(source)
217
+ f.close()
218
+ except Exception as e:
219
+ trace = traceback.format_exc()
220
+ link = None
221
+ print(f"{str(e)}\n\n{trace}", file=sys.stderr)
222
+ finally:
223
+ return link
224
+
225
+
226
+ #
227
+ # Auxiliary functions for the report generation
228
+ #
229
+ def append_header(call, report, extras, pytest_html,
230
+ description, description_tag):
231
+ """
232
+ Appends the description and the test execution exception trace, if any, to a test report.
233
+
234
+ Args:
235
+ description (str): The test function docstring.
236
+ description_tag (str): The HTML tag to use.
237
+ """
238
+ clazz = "extras_exception"
239
+ # Append description
240
+ if description is not None:
241
+ description = escape_html(description).strip().replace('\n', "<br>")
242
+ description = description.strip().replace('\n', "<br>")
243
+ extras.append(pytest_html.extras.html(f'<{description_tag} class="extras_description">{description}</{description_tag}>'))
244
+
245
+ # Catch explicit pytest.fail and pytest.skip calls
246
+ if (
247
+ hasattr(call, 'excinfo') and
248
+ call.excinfo is not None and
249
+ call.excinfo.typename in ('Failed', 'Skipped') and
250
+ hasattr(call.excinfo, "value") and
251
+ hasattr(call.excinfo.value, "msg")
252
+ ):
253
+ extras.append(pytest_html.extras.html(
254
+ "<pre>"
255
+ f'<span class="{clazz}">{escape_html(call.excinfo.typename)}</span><br>'
256
+ f"reason = {escape_html(call.excinfo.value.msg)}"
257
+ "</pre>"
258
+ )
259
+ )
260
+ # Catch XFailed tests
261
+ if report.skipped and hasattr(report, 'wasxfail'):
262
+ extras.append(pytest_html.extras.html(
263
+ "<pre>"
264
+ f'<span class="{clazz}">XFailed</span><br>'
265
+ f"reason = {escape_html(report.wasxfail)}"
266
+ "</pre>"
267
+ )
268
+ )
269
+ # Catch XPassed tests
270
+ if report.passed and hasattr(report, 'wasxfail'):
271
+ extras.append(pytest_html.extras.html(
272
+ "<pre>"
273
+ f'<span class="{clazz}">XPassed</span><br>'
274
+ f"reason = {escape_html(report.wasxfail)}"
275
+ "</pre>"
276
+ )
277
+ )
278
+ # Catch explicit pytest.xfail calls and runtime exceptions in failed tests
279
+ if (
280
+ hasattr(call, 'excinfo') and
281
+ call.excinfo is not None and
282
+ call.excinfo.typename not in ('Failed', 'Skipped') and
283
+ hasattr(call.excinfo, '_excinfo') and
284
+ call.excinfo._excinfo is not None and
285
+ isinstance(call.excinfo._excinfo, tuple) and
286
+ len(call.excinfo._excinfo) > 1
287
+ ):
288
+ extras.append(pytest_html.extras.html(
289
+ "<pre>"
290
+ f'<span class="{clazz}">Exception:</span><br>'
291
+ f"{escape_html(call.excinfo.typename)}<br>"
292
+ f"{escape_html(call.excinfo._excinfo[1])}"
293
+ "</pre>"
294
+ )
295
+ )
296
+ report.extras = extras
297
+
298
+
299
+ def escape_html(text, quote=False):
300
+ """ Escapes HTML characters in a text. """
301
+ if text is None:
302
+ return ""
303
+ return html.escape(str(text), quote)
304
+
305
+
306
+ def get_table_row_tag(comment, image, source, clazz_comment="comment"):
307
+ """
308
+ Returns the HTML table row of a test step.
309
+
310
+ Args:
311
+ comment (str): The comment of the test step.
312
+ image (str): The screenshot anchor element.
313
+ source (str): The page source anchor element.
314
+ clazz_comment (str): The CSS class to apply to the comment table cell.
315
+
316
+ Returns:
317
+ str: The <tr> element.
318
+ """
319
+ clazz = f"extras_{clazz_comment}"
320
+ if isinstance(comment, str):
321
+ comment = decorate_label(comment, clazz)
322
+ else:
323
+ comment = ""
324
+ if image is not None:
325
+ image = decorate_screenshot(image)
326
+ if source is not None:
327
+ source = decorate_page_source(source)
328
+ return (
329
+ f"<tr>"
330
+ f"<td>{comment}</td>"
331
+ f'<td class="extras_td"><div class="extras_td_div">{image}<br>{source}</div></td>'
332
+ f"</tr>"
333
+ )
334
+ else:
335
+ return (
336
+ f"<tr>"
337
+ f"<td>{comment}</td>"
338
+ f'<td class="extras_td"><div class="extras_td_div">{image}</div></td>'
339
+ "</tr>"
340
+ )
341
+ else:
342
+ return (
343
+ f"<tr>"
344
+ f'<td colspan="2">{comment}</td>'
345
+ f"</tr>"
346
+ )
347
+
348
+
349
+ def decorate_label(label, clazz):
350
+ """
351
+ Applies a CSS style to a text.
352
+
353
+ Args:
354
+ label (str): The text to decorate.
355
+ clazz (str): The CSS class to apply.
356
+
357
+ Returns:
358
+ The <span> element decorated with the CSS class.
359
+ """
360
+ return f'<span class="{clazz}">{label}</span>'
361
+
362
+
363
+ # def decorate_anchors(image, source):
364
+ # if image is None:
365
+ # return ''
366
+ # """ Applies CSS style to a screenshot and page source anchor elements. """
367
+ # image = decorate_screenshot(image)
368
+ # if source is not None:
369
+ # source = decorate_page_source(source)
370
+ # return f'<div class="extras_div">{image}<br>{source}</div>'
371
+ # else:
372
+ # return image
373
+
374
+
375
+ def decorate_screenshot(filename):
376
+ if filename is None:
377
+ return ''
378
+ """ Applies CSS class to a screenshot anchor element. """
379
+ clazz = "extras_image"
380
+ return f'<a href="{filename}" target="_blank"><img src ="{filename}" class="{clazz}"></a>'
381
+
382
+
383
+ def decorate_page_source(filename):
384
+ """ Applies CSS class to a page source anchor element. """
385
+ clazz = "extras_page_src"
386
+ return f'<a href="{filename}" target="_blank" class="{clazz}">[page source]</a>'
387
+
388
+
389
+ def log_error_message(report, message):
390
+ """ Appends error message in stderr section of a test report. """
391
+ try:
392
+ i = -1
393
+ for x in range(len(report.sections)):
394
+ if "stderr call" in report.sections[x][0]:
395
+ i = x
396
+ break
397
+ if i != -1:
398
+ report.sections[i] = (
399
+ report.sections[i][0],
400
+ report.sections[i][1] + '\n' + message + '\n'
401
+ )
402
+ else:
403
+ report.sections.append(('Captured stderr call', message))
404
+ except:
405
+ pass