pytest-report-extras 1.2.0__tar.gz → 1.2.2__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.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: pytest-report-extras
3
- Version: 1.2.0
4
- Summary: Pytest plugin to enhance pytest-html and allure reports by adding comments, screenshots and webpage sources.
3
+ Version: 1.2.2
4
+ Summary: Pytest plugin to enhance pytest-html and allure reports by adding comments, screenshots, webpage sources and attachments.
5
5
  Keywords: pytest,selenium,playwright,webtest,webtesting
6
6
  Author-email: Harmin Parra Rueda <harmin.rueda@gmail.com>
7
7
  Requires-Python: >=3.10
@@ -5,8 +5,8 @@ build-backend = "flit_core.buildapi"
5
5
 
6
6
  [project]
7
7
  name = "pytest-report-extras"
8
- version = "1.2.0"
9
- description = "Pytest plugin to enhance pytest-html and allure reports by adding comments, screenshots and webpage sources."
8
+ version = "1.2.2"
9
+ description = "Pytest plugin to enhance pytest-html and allure reports by adding comments, screenshots, webpage sources and attachments."
10
10
  readme = "README.md"
11
11
  #license = "MIT"
12
12
  authors = [
@@ -1,3 +1,4 @@
1
+ import base64
1
2
  import csv
2
3
  import io
3
4
  import json
@@ -12,22 +13,49 @@ from . import utils
12
13
 
13
14
  class Mime:
14
15
  """
15
- Class to hold mime type enums.
16
+ Class to hold mime type values.
16
17
  """
17
- text_plain = "text/plain"
18
+ image_bmp = "image/png"
19
+ image_gif = "image/gif"
20
+ image_jpeg = "image/jpeg"
21
+ image_png = "image/png"
22
+ image_svg_xml = "image/svg+xml"
23
+ image_tiff = "image/tiff"
24
+ text_csv = "text/csv"
18
25
  text_html = "text/html"
26
+ text_plain = "text/plain"
27
+ text_uri_list = "text/uri-list"
19
28
  application_json = "application/json"
20
29
  application_xml = "application/xml"
21
30
  application_yaml = "application/yaml"
22
- text_csv = "text/csv"
23
- text_uri_list = "text/uri-list"
31
+
32
+ @staticmethod
33
+ def is_supported(mime: str):
34
+ return mime in (Mime.image_bmp, Mime.image_gif, Mime.image_jpeg, Mime.image_png,
35
+ Mime.image_svg_xml, mime == Mime.image_tiff, Mime.text_csv,
36
+ Mime.text_html, Mime.text_plain, Mime.text_uri_list, Mime.application_json,
37
+ Mime.application_xml, Mime.application_yaml)
38
+
39
+ @staticmethod
40
+ def is_unsupported(mime: str):
41
+ return not Mime.is_supported(mime)
42
+
43
+ @staticmethod
44
+ def isimage(mime: str):
45
+ return mime is not None and mime.startswith("image/")
24
46
 
25
47
 
26
48
  class Attachment:
27
49
  """
28
- Class to represent text to be formatted as code-block in a <pre> HTML tag.
50
+ Class to represent attachments.
29
51
  """
30
- def __init__(self, body: str = None, source: str = None, mime: str = None, inner_html: str = None):
52
+ def __init__(
53
+ self,
54
+ body: str | List[str] | bytes = None,
55
+ source: str = None,
56
+ mime: str = None,
57
+ inner_html: str = None
58
+ ):
31
59
  self.body = body
32
60
  self.source = source
33
61
  self.mime = mime
@@ -42,22 +70,24 @@ class Attachment:
42
70
  ):
43
71
  if body is not None and isinstance(body, List):
44
72
  mime = Mime.text_uri_list
73
+ if Mime.isimage(mime):
74
+ return _attachment_image(body, mime)
45
75
  match mime:
46
76
  case Mime.application_json:
47
- return _format_json(body, indent)
77
+ return _attachment_json(body, indent)
48
78
  case Mime.application_xml:
49
- return _format_xml(body, indent)
79
+ return _attachment_xml(body, indent)
50
80
  case Mime.application_yaml:
51
- return _format_yaml(body, indent)
81
+ return _attachment_yaml(body, indent)
52
82
  case Mime.text_csv:
53
- return _format_csv(body, delimiter=delimiter)
83
+ return _attachment_csv(body, delimiter=delimiter)
54
84
  case Mime.text_uri_list:
55
- return _format_uri_list(body)
85
+ return _attachment_uri_list(body)
56
86
  case _:
57
- return _format_txt(body)
87
+ return _attachment_txt(body)
58
88
 
59
89
 
60
- def _format_json(text: str | Dict, indent: int = 4) -> Attachment:
90
+ def _attachment_json(text: str | Dict, indent: int = 4) -> Attachment:
61
91
  """
62
92
  Returns an attachment object with a string holding a JSON document.
63
93
  """
@@ -68,7 +98,7 @@ def _format_json(text: str | Dict, indent: int = 4) -> Attachment:
68
98
  return Attachment(body="Error formatting JSON.\n" + str(text), mime=Mime.text_plain)
69
99
 
70
100
 
71
- def _format_xml(text: str, indent: int = 4) -> Attachment:
101
+ def _attachment_xml(text: str, indent: int = 4) -> Attachment:
72
102
  """
73
103
  Returns an attachment object with a string holding an XML document.
74
104
  """
@@ -83,25 +113,25 @@ def _format_xml(text: str, indent: int = 4) -> Attachment:
83
113
  return Attachment(body=result, mime=Mime.application_xml)
84
114
 
85
115
 
86
- def _format_yaml(text: str, indent: int = 4) -> Attachment:
116
+ def _attachment_yaml(text: str, indent: int = 4) -> Attachment:
87
117
  """
88
118
  Returns an attachment object with a string holding a YAML document.
89
119
  """
90
120
  try:
91
121
  text = yaml.safe_load(text)
92
- return Attachment(body=yaml.dump(text, indent=indent), mime=Mime.application_yaml)
122
+ return Attachment(body=yaml.dump(text), mime=Mime.application_yaml)
93
123
  except:
94
124
  return Attachment(body="Error formatting YAML.\n" + str(text), mime=Mime.text_plain)
95
125
 
96
126
 
97
- def _format_txt(text: str) -> Attachment:
127
+ def _attachment_txt(text: str) -> Attachment:
98
128
  """
99
129
  Returns an attachment object with a plain/body string.
100
130
  """
101
131
  return Attachment(body=text, mime=Mime.text_plain)
102
132
 
103
133
 
104
- def _format_csv(text: str, delimiter=',') -> Attachment:
134
+ def _attachment_csv(text: str, delimiter=',') -> Attachment:
105
135
  """
106
136
  Returns an attachment object with a string holding a CVS document.
107
137
  """
@@ -124,7 +154,7 @@ def _format_csv(text: str, delimiter=',') -> Attachment:
124
154
  return Attachment(body=text, mime=Mime.text_csv, inner_html=inner_html)
125
155
 
126
156
 
127
- def _format_uri_list(text: str | List[str]) -> Attachment:
157
+ def _attachment_uri_list(text: str | List[str]) -> Attachment:
128
158
  """
129
159
  Returns an attachment object with a uri list.
130
160
  """
@@ -141,3 +171,15 @@ def _format_uri_list(text: str | List[str]) -> Attachment:
141
171
  return Attachment(body=body, mime=Mime.text_uri_list, inner_html=inner_html)
142
172
  except:
143
173
  return Attachment(body="Error parsing uri list.", mime=Mime.text_plain)
174
+
175
+
176
+ def _attachment_image(data: bytes | str, mime: Mime) -> Attachment:
177
+ """
178
+ Returns an attachment object with bytes representing an image.
179
+ """
180
+ if isinstance(data, str):
181
+ try:
182
+ data = base64.b64decode(data)
183
+ except:
184
+ return Attachment(body="Error parsing image bytes.", mime=Mime.text_plain)
185
+ return Attachment(body=data, mime=mime)
@@ -56,12 +56,13 @@ class Extras:
56
56
  Class to hold pytest-html 'extras' to be added for each test in the HTML report.
57
57
  """
58
58
 
59
- def __init__(self, report_html, fx_screenshots, fx_sources, report_allure, indent):
59
+ def __init__(self, report_html, single_page, screenshots, sources, report_allure, indent):
60
60
  """
61
61
  Args:
62
62
  report_html (str): The 'report_html' fixture.
63
- fx_screenshots (str): The 'screenshots' fixture.
64
- fx_sources (bool): The 'sources' fixture.
63
+ single_page (bool): The 'single_page' fixture.
64
+ screenshots (str): The 'screenshots' fixture.
65
+ sources (bool): The 'sources' fixture.
65
66
  report_allure (str): The 'report_allure' fixture.
66
67
  indent: The 'indent' fixture.
67
68
  """
@@ -70,24 +71,57 @@ class Extras:
70
71
  self.comments = []
71
72
  self.links = []
72
73
  self.target = None
73
- self._fx_screenshots = fx_screenshots
74
- self._fx_sources = fx_sources
74
+ self._fx_screenshots = screenshots
75
+ self._fx_sources = sources
76
+ self._fx_single_page = single_page
75
77
  self._html = report_html
76
78
  self._allure = report_allure
77
79
  self._indent = indent
78
80
  self.Mime = Mime
79
81
 
80
82
  def screenshot(
81
- self,
82
- comment: str,
83
- target = None,
84
- full_page: bool = True,
85
- page_source: bool = False,
86
- escape_html: bool = False
83
+ self,
84
+ comment: str,
85
+ target = None,
86
+ full_page: bool = True,
87
+ page_source: bool = False,
88
+ escape_html: bool = False
87
89
  ):
88
90
  """
89
91
  Adds a step with a screenshot in the report.
90
- The screenshot is saved in <report_html>/screenshots folder.
92
+ The screenshot is saved in <report_html>/images folder.
93
+ The webpage source is saved in <report_html>/sources folder.
94
+
95
+ Args:
96
+ comment (str): The comment of the test step.
97
+ target (WebDriver | WebElement | Page | Locator): The target of the screenshot.
98
+ full_page (bool): Whether to take a full-page screenshot.
99
+ page_source (bool): Whether to include the page source. Overrides the global `sources` fixture.
100
+ escape_html (bool): Whether to escape HTML characters in the comment.
101
+ """
102
+ self._add_image_step(
103
+ comment=comment,
104
+ target=target,
105
+ full_page=full_page,
106
+ page_source=page_source,
107
+ data=None,
108
+ mime=None,
109
+ escape_html=escape_html
110
+ )
111
+
112
+ def _add_image_step(
113
+ self,
114
+ comment: str,
115
+ target = None,
116
+ full_page: bool = True,
117
+ page_source: bool = False,
118
+ data: bytes = None,
119
+ mime: Mime = None,
120
+ escape_html: bool = False
121
+ ):
122
+ """
123
+ Adds a step with an image in the report.
124
+ The image/screenshot is saved in <report_html>/images folder.
91
125
  The webpage source is saved in <report_html>/sources folder.
92
126
 
93
127
  Args:
@@ -95,6 +129,8 @@ class Extras:
95
129
  target (WebDriver | WebElement | Page | Locator): The target of the screenshot.
96
130
  full_page (bool): Whether to take a full-page screenshot.
97
131
  page_source (bool): Whether to include the page source. Overrides the global `sources` fixture.
132
+ data (bytes): The image to attach as bytes.
133
+ mime (str): The mime type of the image that was passed as bytes.
98
134
  escape_html (bool): Whether to escape HTML characters in the comment.
99
135
  """
100
136
  if target is not None:
@@ -108,11 +144,16 @@ class Extras:
108
144
  if isinstance(target, Page) and self.target is None:
109
145
  self.target = target
110
146
 
111
- if self._fx_screenshots == "last" and target is not None:
147
+ if self._fx_screenshots == "last" and target is not None and data is None:
112
148
  return
113
149
 
114
150
  # Get the 3 parts of the test step: image, comment and source
115
- image, source = utils.get_screenshot(target, full_page, self._fx_sources or page_source)
151
+ if target is not None:
152
+ image, source = utils.get_screenshot(target, full_page, self._fx_sources or page_source)
153
+ mime = "image/png"
154
+ else: # data is not None
155
+ image, source = data, None
156
+
116
157
  comment = "" if comment is None else comment
117
158
  comment = html.escape(comment, quote=True) if escape_html else comment
118
159
 
@@ -127,37 +168,45 @@ class Extras:
127
168
 
128
169
  # Add extras to pytest-html report if pytest-html plugin is being used.
129
170
  if self._html:
130
- self._save_screenshot(image, source)
171
+ self._save_image(image, source, mime)
131
172
  self.comments.append(comment)
132
173
 
133
174
  def attach(
134
- self,
135
- comment: str,
136
- body: str = None,
137
- source: str = None,
138
- mime: str = None,
139
- csv_delimiter=',',
140
- escape_html: bool = False
175
+ self,
176
+ comment: str,
177
+ body: str | bytes | Dict | List[str] = None,
178
+ source: str = None,
179
+ mime: str = None,
180
+ csv_delimiter=',',
181
+ escape_html: bool = False
141
182
  ):
142
183
  """
143
- Adds a step in the pytest-html report: screenshot, comment and webpage source.
144
- The screenshot is saved in <report_html>/screenshots folder.
184
+ Adds a step with an attachment to the report.
185
+ The image is saved in <report_html>/images folder.
145
186
  The webpage source is saved in <report_html>/sources folder.
146
187
  The 'body' and 'source' parameters are exclusive.
147
188
 
148
189
  Args:
149
190
  comment (str): The comment of the test step.
150
- body (str | Dict | List[str]): The content/body of the attachment.
191
+ body (str | bytes | Dict | List[str]): The content/body of the attachment.
151
192
  Can be of type 'Dict' for JSON mime type.
152
193
  Can be of type 'List[str]' for uri-list mime type.
194
+ Can be of type 'bytes' for image mime type.
153
195
  source (str): The filepath of the source to attach.
154
196
  mime (str): The attachment mime type.
155
197
  csv_delimiter (str): The delimiter for CSV documents.
156
198
  escape_html (bool): Whether to escape HTML characters in the comment.
157
199
  """
200
+ if Mime.is_unsupported(mime):
201
+ mime = None
202
+ attachment = self._get_attachment(body, source, mime, csv_delimiter)
203
+ mime = attachment.mime
204
+ if Mime.isimage(mime):
205
+ self._add_image_step(comment=comment, data=attachment.body, mime=mime, escape_html=escape_html)
206
+ return
207
+
158
208
  comment = "" if comment is None else comment
159
209
  comment = html.escape(comment, quote=True) if escape_html else comment
160
- attachment = self._get_attachment(body, source, mime, csv_delimiter)
161
210
 
162
211
  # Add extras to Allure report if allure-pytest plugin is being used.
163
212
  if self._allure and importlib.util.find_spec('allure') is not None:
@@ -178,98 +227,51 @@ class Extras:
178
227
  comment += ' ' + attachment.inner_html
179
228
  else:
180
229
  comment += '\n' + utils.decorate_attachment(attachment)
181
- self._save_screenshot(None, None)
230
+ self._save_image(None, None)
182
231
  self.comments.append(comment)
183
232
 
184
- # Deprecated method
185
- def step(
186
- self,
187
- comment: str = None,
188
- target=None,
189
- code_block: CodeBlockText = None,
190
- full_page: bool = True,
191
- page_source: bool = False,
192
- escape_html: bool = False
193
- ):
194
- """
195
- Adds a step in the pytest-html report: screenshot, comment and webpage source.
196
- The screenshot is saved in <report_html>/screenshots folder.
197
- The webpage source is saved in <report_html>/sources folder.
198
-
199
- Args:
200
- comment (str): The comment of the test step.
201
- target (WebDriver | WebElement | Page | Locator): The target of the screenshot.
202
- code_block (CodeBlockText): The code-block formatted content to be added.
203
- full_page (bool): Whether to take a full-page screenshot.
204
- page_source (bool): Whether to include the page source. Overrides the global `sources` fixture.
205
- escape_html (bool): Whether to escape HTML characters in the comment.
206
- """
207
- if target is not None:
208
- if importlib.util.find_spec('selenium') is not None:
209
- from selenium.webdriver.remote.webdriver import WebDriver
210
- if isinstance(target, WebDriver) and self.target is None:
211
- self.target = target
212
-
213
- if importlib.util.find_spec('playwright') is not None:
214
- from playwright.sync_api import Page
215
- if isinstance(target, Page) and self.target is None:
216
- self.target = target
217
-
218
- if self._fx_screenshots == "last" and target is not None:
219
- return
220
-
221
- # Get the 3 parts of the test step: image, comment and source
222
- image, source = utils.get_screenshot(target, full_page, self._fx_sources or page_source)
223
- comment = "" if comment is None else comment
224
- comment = html.escape(comment, quote=True) if escape_html else comment
225
-
226
- # Add extras to Allure report if allure-pytest plugin is being used.
227
- if self._allure and importlib.util.find_spec('allure') is not None:
228
- import allure
229
- if image is not None:
230
- allure.attach(image, name=comment, attachment_type=allure.attachment_type.PNG)
231
- # Attach the webpage source
232
- if source is not None:
233
- allure.attach(source, name="page source", attachment_type=allure.attachment_type.TEXT)
234
- if code_block is not None and code_block.body is not None:
235
- allure.attach(code_block.body, name=comment, attachment_type=code_block.mime)
236
-
237
- # Add extras to pytest-html report if pytest-html plugin is being used.
238
- if self._html:
239
- self._save_screenshot(image, source)
240
- if code_block is not None and code_block.body is not None:
241
- comment += '\n' + utils.decorate_attachment(code_block)
242
- self.comments.append(comment)
243
-
244
- # Deprecation warning
245
- warnings.warn(deprecation_msg, DeprecationWarning)
246
-
247
- def _save_screenshot(self, image: bytes | str, source: str):
233
+ def _save_image(self, image: bytes | str, source: str, mime = None):
248
234
  """
249
235
  Saves the pytest-html 'extras': screenshot, comment and webpage source.
250
- The screenshot is saved in <report_html>/screenshots folder.
236
+ The image is saved in <report_html>/images folder.
251
237
  The webpage source is saved in <report_html>/sources folder.
252
238
 
253
239
  Args:
254
240
  image (bytes | str): The screenshot as bytes or base64 string.
255
241
  source (str): The webpage source code.
256
242
  """
243
+ link_image = None
244
+ link_source = None
245
+ index = 0 if self._fx_single_page else counter()
246
+
257
247
  if isinstance(image, str):
258
248
  try:
259
249
  image = base64.b64decode(image.encode())
260
250
  except:
261
251
  image = None
262
- index = -1 if image is None else counter()
263
- link_image = utils.get_image_link(self._html, index, image)
264
- self.images.append(link_image)
265
- link_source = None
252
+ # Get the image uri
253
+ if image is not None:
254
+ if self._fx_single_page is False:
255
+ link_image = utils.get_image_link(self._html, index, image)
256
+ else:
257
+ mime = "image/*" if mime is None else mime
258
+ try:
259
+ data_uri = f"data:{mime};base64,{base64.b64encode(image).decode()}"
260
+ except:
261
+ data_uri = None
262
+ link_image = data_uri
263
+ # Get the webpage source uri
266
264
  if source is not None:
267
- link_source = utils.get_source_link(self._html, index, source)
265
+ if self._fx_single_page is False:
266
+ link_source = utils.get_source_link(self._html, index, source)
267
+ else:
268
+ link_source = f"data:text/plain;base64,{base64.b64encode(source.encode()).decode()}"
269
+ self.images.append(link_image)
268
270
  self.sources.append(link_source)
269
271
 
270
272
  def _get_attachment(
271
273
  self,
272
- body: str | Dict | List[str] = None,
274
+ body: str | Dict | List[str] | bytes = None,
273
275
  source: str = None,
274
276
  mime: str = None,
275
277
  delimiter=',',
@@ -278,9 +280,11 @@ class Extras:
278
280
  Creates an attachment.
279
281
 
280
282
  Args:
281
- body (str | Dict | List[str]): The content/body of the attachment.
283
+ comment (str): The comment of the test step.
284
+ body (str | bytes | Dict | List[str]): The content/body of the attachment.
282
285
  Can be of type 'Dict' for JSON mime type.
283
286
  Can be of type 'List[str]' for uri-list mime type.
287
+ Can be of type 'bytes' for image mime type.
284
288
  source (str): The filepath of the source to attach.
285
289
  mime (str): The attachment mime type.
286
290
  delimiter (str): The delimiter for CSV documents.
@@ -296,9 +300,14 @@ class Extras:
296
300
  inner_html = utils.decorate_uri(self.add_to_downloads(source))
297
301
  return Attachment(source=source, inner_html=inner_html)
298
302
  else:
299
- f = open(source, 'r')
300
- body = f.read()
301
- f.close()
303
+ if Mime.isimage(mime):
304
+ f = open(source, "rb")
305
+ body = f.read()
306
+ f.close()
307
+ else:
308
+ f = open(source, 'r')
309
+ body = f.read()
310
+ f.close()
302
311
  except Exception as err:
303
312
  body = f"Error reading file: {source}\n{err}"
304
313
  mime = Mime.text_plain
@@ -323,22 +332,82 @@ class Extras:
323
332
  """
324
333
  self.links.append((uri, name))
325
334
 
326
- def add_to_downloads(self, filepath: str = None) -> str:
335
+ def add_to_downloads(self, target: str | bytes = None) -> str:
327
336
  """
328
- When using pytest-html, copies a file into the report's download folder, make it available to download.
337
+ When using pytest-html, copies a file into the report's download folder, making it available to download.
329
338
 
330
339
  Args:
331
- filepath (str): The file to add to download folder.
340
+ target (str | bytes): The file or the bytes content to add into the download folder.
332
341
 
333
342
  Returns:
334
343
  The uri of the downloadable file.
335
344
  """
345
+ return utils.get_download_link(self._html, target)
346
+
347
+
348
+ # Deprecated code from here onwards
349
+ def step(
350
+ self,
351
+ comment: str = None,
352
+ target=None,
353
+ code_block: CodeBlockText = None,
354
+ full_page: bool = True,
355
+ page_source: bool = False,
356
+ escape_html: bool = False
357
+ ):
358
+ """
359
+ Adds a step in the pytest-html report: screenshot, comment and webpage source.
360
+ The screenshot is saved in <report_html>/images folder.
361
+ The webpage source is saved in <report_html>/sources folder.
362
+
363
+ Args:
364
+ comment (str): The comment of the test step.
365
+ target (WebDriver | WebElement | Page | Locator): The target of the screenshot.
366
+ code_block (CodeBlockText): The code-block formatted content to be added.
367
+ full_page (bool): Whether to take a full-page screenshot.
368
+ page_source (bool): Whether to include the page source. Overrides the global `sources` fixture.
369
+ escape_html (bool): Whether to escape HTML characters in the comment.
370
+ """
371
+ if target is not None:
372
+ if importlib.util.find_spec('selenium') is not None:
373
+ from selenium.webdriver.remote.webdriver import WebDriver
374
+ if isinstance(target, WebDriver) and self.target is None:
375
+ self.target = target
376
+
377
+ if importlib.util.find_spec('playwright') is not None:
378
+ from playwright.sync_api import Page
379
+ if isinstance(target, Page) and self.target is None:
380
+ self.target = target
381
+
382
+ if self._fx_screenshots == "last" and target is not None:
383
+ return
384
+
385
+ # Get the 3 parts of the test step: image, comment and source
386
+ image, source = utils.get_screenshot(target, full_page, self._fx_sources or page_source)
387
+ comment = "" if comment is None else comment
388
+ comment = html.escape(comment, quote=True) if escape_html else comment
389
+
390
+ # Add extras to Allure report if allure-pytest plugin is being used.
391
+ if self._allure and importlib.util.find_spec('allure') is not None:
392
+ import allure
393
+ if image is not None:
394
+ allure.attach(image, name=comment, attachment_type=allure.attachment_type.PNG)
395
+ # Attach the webpage source
396
+ if source is not None:
397
+ allure.attach(source, name="page source", attachment_type=allure.attachment_type.TEXT)
398
+ if code_block is not None and code_block.body is not None:
399
+ allure.attach(code_block.body, name=comment, attachment_type=code_block.mime)
400
+
401
+ # Add extras to pytest-html report if pytest-html plugin is being used.
336
402
  if self._html:
337
- return utils.get_download_link(self._html, filepath)
338
- else:
339
- return None
403
+ self._save_image(image, source, None)
404
+ if code_block is not None and code_block.body is not None:
405
+ comment += '\n' + utils.decorate_attachment(code_block)
406
+ self.comments.append(comment)
407
+
408
+ # Deprecation warning
409
+ warnings.warn(deprecation_msg, DeprecationWarning)
340
410
 
341
- # Deprecated code from here downwards
342
411
  def format_code_block(self, text: str, mime="text/plain") -> Attachment:
343
412
  return Attachment(text, mime)
344
413
 
@@ -74,6 +74,12 @@ def report_html(request):
74
74
  return fx_html
75
75
 
76
76
 
77
+ @pytest.fixture(scope='session')
78
+ def single_page(request):
79
+ """ Whether to generate a single HTML page for pytest-html report """
80
+ return request.config.getoption("--self-contained-html", default=False)
81
+
82
+
77
83
  @pytest.fixture(scope='session')
78
84
  def report_allure(request):
79
85
  """ Whether the allure-pytest plugin is being used """
@@ -128,19 +134,19 @@ def issue_key_pattern(request):
128
134
 
129
135
 
130
136
  @pytest.fixture(scope='session')
131
- def check_options(request, report_html, report_allure):
137
+ def check_options(request, report_html, report_allure, single_page):
132
138
  """ Verifies preconditions before using this plugin. """
133
139
  utils.check_options(report_html, report_allure)
134
140
  if report_html is not None:
135
- utils.create_assets(report_html)
141
+ utils.create_assets(report_html, single_page)
136
142
 
137
143
 
138
144
  #
139
145
  # Test fixture
140
146
  #
141
147
  @pytest.fixture(scope='function')
142
- def report(request, report_html, screenshots, sources, report_allure, indent, check_options):
143
- return Extras(report_html, screenshots, sources, report_allure, indent)
148
+ def report(request, report_html, single_page, screenshots, sources, report_allure, indent, check_options):
149
+ return Extras(report_html, single_page, screenshots, sources, report_allure, indent)
144
150
 
145
151
 
146
152
  #
@@ -264,6 +270,7 @@ def pytest_runtest_makereport(item, call):
264
270
  # Get test fixture values
265
271
  feature_request = item.funcargs['request']
266
272
  fx_report = feature_request.getfixturevalue("report")
273
+ fx_single_page = feature_request.getfixturevalue("single_page")
267
274
  fx_description_tag = feature_request.getfixturevalue("description_tag")
268
275
  fx_screenshots = feature_request.getfixturevalue("screenshots")
269
276
  target = fx_report.target
@@ -287,17 +294,19 @@ def pytest_runtest_makereport(item, call):
287
294
  rows += utils.get_table_row_tag(
288
295
  fx_report.comments[i],
289
296
  fx_report.images[i],
290
- fx_report.sources[i]
297
+ fx_report.sources[i],
298
+ fx_single_page
291
299
  )
292
300
 
293
301
  # Add screenshot for last step
294
302
  if fx_screenshots == "last" and failure is False and target is not None:
295
303
  fx_report._fx_screenshots = "all" # To force screenshot gathering
296
- fx_report.step(f"Last screenshot", target)
304
+ fx_report.screenshot(f"Last screenshot", target)
297
305
  rows += utils.get_table_row_tag(
298
306
  fx_report.comments[-1],
299
307
  fx_report.images[-1],
300
- fx_report.sources[-1]
308
+ fx_report.sources[-1],
309
+ fx_single_page
301
310
  )
302
311
 
303
312
  # Add screenshot for test failure/skip
@@ -311,11 +320,12 @@ def pytest_runtest_makereport(item, call):
311
320
  else:
312
321
  event_label = "skip"
313
322
  fx_report._fx_screenshots = "all" # To force screenshot gathering
314
- fx_report.step(f"Last screenshot before {event_label}", target)
323
+ fx_report.screenshot(f"Last screenshot before {event_label}", target)
315
324
  rows += utils.get_table_row_tag(
316
325
  fx_report.comments[-1],
317
326
  fx_report.images[-1],
318
327
  fx_report.sources[-1],
328
+ fx_single_page,
319
329
  event_class
320
330
  )
321
331
 
@@ -26,12 +26,12 @@ def check_options(htmlpath, allurepath):
26
26
  sys.exit(pytest.ExitCode.USAGE_ERROR)
27
27
 
28
28
 
29
- def getini(config, name):
30
- """ Workaround for bug https://github.com/pytest-dev/pytest/issues/11282 """
31
- value = config.getini(name)
32
- if not isinstance(value, str):
33
- value = None
34
- return value
29
+ #def getini(config, name):
30
+ # """ Workaround for bug https://github.com/pytest-dev/pytest/issues/11282 """
31
+ # value = config.getini(name)
32
+ # if not isinstance(value, str):
33
+ # value = None
34
+ # return value
35
35
 
36
36
 
37
37
  def get_folder(filepath):
@@ -59,27 +59,29 @@ def check_lists_length(report, fx_extras):
59
59
  return True
60
60
 
61
61
 
62
- def create_assets(report_html):
63
- """ Recreate screenshots and webpage sources folders. """
62
+ def create_assets(report_html, single_page):
63
+ """ Recreate images and webpage sources folders. """
64
64
  if report_html is None:
65
65
  return
66
- # Recreate screenshots_folder
66
+ # Recreate report_folder
67
67
  folder = ""
68
68
  if report_html is not None and report_html != '':
69
69
  folder = f"{report_html}{os.sep}"
70
- # Create page sources folder
71
- shutil.rmtree(f"{folder}sources", ignore_errors=True)
72
- pathlib.Path(f"{folder}sources").mkdir(parents=True)
73
- # Create screenshots folder
74
- shutil.rmtree(f"{folder}screenshots", ignore_errors=True)
75
- pathlib.Path(f"{folder}screenshots").mkdir(parents=True)
76
70
  # Create downloads folder
77
71
  shutil.rmtree(f"{folder}downloads", ignore_errors=True)
78
72
  pathlib.Path(f"{folder}downloads").mkdir(parents=True)
79
- # Copy error.png to screenshots folder
80
- resources_path = pathlib.Path(__file__).parent.joinpath("resources")
81
- error_img = pathlib.Path(resources_path, "error.png")
82
- shutil.copy(str(error_img), f"{folder}screenshots")
73
+ if single_page:
74
+ return
75
+ # Create page sources folder
76
+ shutil.rmtree(f"{folder}sources", ignore_errors=True)
77
+ pathlib.Path(f"{folder}sources").mkdir(parents=True)
78
+ # Create images folder
79
+ shutil.rmtree(f"{folder}images", ignore_errors=True)
80
+ pathlib.Path(f"{folder}images").mkdir(parents=True)
81
+ # Copy error.png to images folder
82
+ # resources_path = pathlib.Path(__file__).parent.joinpath("resources")
83
+ # error_img = pathlib.Path(resources_path, "error.png")
84
+ # shutil.copy(str(error_img), f"{folder}images")
83
85
 
84
86
 
85
87
  #
@@ -194,11 +196,19 @@ def _get_playwright_screenshot(target, full_page=True, page_source=False):
194
196
 
195
197
  return image, source
196
198
 
197
-
199
+
198
200
  def get_image_link(report_html, index, image):
201
+ """
202
+ Saves an image in the 'images' folder and returns its relative path to the report folder.
203
+
204
+ Args:
205
+ report_html (str): The report folder.
206
+ index (int): The file name suffix.
207
+ image (bytes) : The image to save.
208
+ """
199
209
  if image is None:
200
210
  return None
201
- link = f"screenshots{os.sep}image-{index}.png"
211
+ link = f"images{os.sep}image-{index}.png"
202
212
  folder = ""
203
213
  if report_html is not None and report_html != '':
204
214
  folder = f"{report_html}{os.sep}"
@@ -209,13 +219,22 @@ def get_image_link(report_html, index, image):
209
219
  f.close()
210
220
  except Exception as err:
211
221
  trace = traceback.format_exc()
212
- link = f"screenshots{os.sep}error.png"
222
+ link = None # f"images{os.sep}error.png"
213
223
  print(f"{str(err)}\n\n{trace}", file=sys.stderr)
214
224
  finally:
215
225
  return link
216
226
 
217
227
 
218
228
  def get_source_link(report_html, index, source):
229
+ """
230
+ Saves a webpage source in the 'sources' folder and returns its relative path to the report folder.
231
+ Args:
232
+ report_html (str): The report folder.
233
+ index (int): The file name suffix.
234
+ source (str) : The webpage source to save.
235
+ """
236
+ if source is None:
237
+ return None
219
238
  link = f"sources{os.sep}page-{index}.txt"
220
239
  folder = ""
221
240
  if report_html is not None and report_html != '':
@@ -233,10 +252,26 @@ def get_source_link(report_html, index, source):
233
252
  return link
234
253
 
235
254
 
236
- def get_download_link(report_html, filepath: str = None):
255
+ def get_download_link(report_html, target: str | bytes = None):
256
+ """
257
+ Saves a file or bytes in the 'downloads' folder and returns its relative path to the report folder.
258
+
259
+ Args:
260
+ report_html (str): The report folder.
261
+ target (file | bytes): The name of the file or the bytes to save.
262
+ image (buyes) : The image to save.
263
+ """
264
+ if target is None:
265
+ return None
266
+ filename = str(uuid.uuid4())
237
267
  try:
238
- filename = uuid.uuid4()
239
- subprocess.run(["cp", filepath, f"{report_html}{os.sep}downloads{os.sep}{filename}"]).check_returncode()
268
+ destination = f"{report_html}{os.sep}downloads{os.sep}{filename}"
269
+ if isinstance(target, str):
270
+ subprocess.run(["cp", target, destination]).check_returncode()
271
+ else: # bytes
272
+ f = open(destination, 'wb')
273
+ f.write(target)
274
+ f.close()
240
275
  return f"downloads{os.sep}{filename}"
241
276
  except:
242
277
  raise
@@ -322,7 +357,7 @@ def escape_html(text, quote=False) -> str:
322
357
  return html.escape(str(text), quote)
323
358
 
324
359
 
325
- def get_table_row_tag(comment, image, source, clazz_comment="comment") -> str:
360
+ def get_table_row_tag(comment, image, source, single_page, clazz_comment="comment") -> str:
326
361
  """
327
362
  Returns the HTML table row of a test step.
328
363
 
@@ -330,6 +365,7 @@ def get_table_row_tag(comment, image, source, clazz_comment="comment") -> str:
330
365
  comment (str): The comment of the test step.
331
366
  image (str): The screenshot anchor element.
332
367
  source (str): The page source anchor element.
368
+ single_page (bool): Whether to generate the HTML report in a single page.
333
369
  clazz_comment (str): The CSS class to apply to the comment table cell.
334
370
 
335
371
  Returns:
@@ -341,7 +377,7 @@ def get_table_row_tag(comment, image, source, clazz_comment="comment") -> str:
341
377
  else:
342
378
  comment = ""
343
379
  if image is not None:
344
- image = decorate_screenshot(image)
380
+ image = decorate_image(image, single_page)
345
381
  if source is not None:
346
382
  source = decorate_page_source(source)
347
383
  return (
@@ -383,7 +419,7 @@ def decorate_label(label, clazz) -> str:
383
419
  # if image is None:
384
420
  # return ''
385
421
  # """ Applies CSS style to a screenshot and page source anchor elements. """
386
- # image = decorate_screenshot(image)
422
+ # image = decorate_image(image)
387
423
  # if source is not None:
388
424
  # source = decorate_page_source(source)
389
425
  # return f'<div class="extras_div">{image}<br>{source}</div>'
@@ -391,12 +427,26 @@ def decorate_label(label, clazz) -> str:
391
427
  # return image
392
428
 
393
429
 
394
- def decorate_screenshot(filename) -> str:
395
- if filename is None:
430
+ def decorate_image(uri: str, single_page: bool) -> str:
431
+ """ Applies CSS class to an image anchor element. """
432
+ if single_page:
433
+ return decorate_image_from_base64(uri)
434
+ else:
435
+ return decorate_image_from_file(uri)
436
+
437
+
438
+ def decorate_image_from_file(uri: str) -> str:
439
+ clazz = "extras_image"
440
+ if uri is None:
396
441
  return ""
397
- """ Applies CSS class to a screenshot anchor element. """
442
+ return f'<a href="{uri}" target="_blank" rel="noopener noreferrer"><img src ="{uri}" class="{clazz}"></a>'
443
+
444
+
445
+ def decorate_image_from_base64(uri: str) -> str:
398
446
  clazz = "extras_image"
399
- return f'<a href="{filename}" target="_blank"><img src ="{filename}" class="{clazz}"></a>'
447
+ if uri is None:
448
+ return ""
449
+ return f'<img src ="{uri}" class="{clazz}">'
400
450
 
401
451
 
402
452
  def decorate_page_source(filename) -> str:
@@ -404,7 +454,7 @@ def decorate_page_source(filename) -> str:
404
454
  if filename is None:
405
455
  return ""
406
456
  clazz = "extras_page_src"
407
- return f'<a href="{filename}" target="_blank" class="{clazz}">[page source]</a>'
457
+ return f'<a href="{filename}" target="_blank" rel="noopener noreferrer" class="{clazz}">[page source]</a>'
408
458
 
409
459
 
410
460
  def decorate_uri(uri: str) -> str:
@@ -412,9 +462,9 @@ def decorate_uri(uri: str) -> str:
412
462
  if uri is None or uri == '':
413
463
  return ""
414
464
  if uri.startswith("downloads"):
415
- return f'<a href="{uri}" target="_blank">{pathlib.Path(uri).name}</a>'
465
+ return f'<a href="{uri}" target="_blank" rel="noopener noreferrer">{pathlib.Path(uri).name}</a>'
416
466
  else:
417
- return f'<a href="{uri}" target="_blank">{uri}</a>'
467
+ return f'<a href="{uri}" target="_blank" rel="noopener noreferrer">{uri}</a>'
418
468
 
419
469
 
420
470
  def decorate_uri_list(uris: List[str]) -> str:
@@ -428,18 +478,20 @@ def decorate_uri_list(uris: List[str]) -> str:
428
478
 
429
479
  def decorate_attachment(attachment) -> str:
430
480
  """ Applies CSS class to an attachment. """
431
- clazz1 = "extras_pre"
432
- clazz2 = "extras_iframe"
481
+ clazz_pre = "extras_pre"
482
+ clazz_frm = "extras_iframe"
433
483
  if attachment.inner_html is None:
434
484
  if attachment.body in (None, ""):
435
485
  return ""
436
486
  else:
437
- return f'<pre class="{clazz1}">{escape_html(attachment.body)}</pre>'
487
+ return f'<pre class="{clazz_pre}">{escape_html(attachment.body)}</pre>'
438
488
  else:
439
489
  if attachment.mime == "text/html":
440
- return f'<iframe class="{clazz2}" src="{attachment.inner_html}"></iframe>'
490
+ return f'<iframe class="{clazz_frm}" src="{attachment.inner_html}"></iframe>'
491
+ if attachment.mime.startswith("image"):
492
+ return attachment.inner_html
441
493
  else:
442
- return f'<pre class="{clazz1}">{attachment.inner_html}</pre>'
494
+ return f'<pre class="{clazz_pre}">{attachment.inner_html}</pre>'
443
495
 
444
496
 
445
497
  def log_error_message(report, message):