1
+ import os
2
+ import pathlib
1
3
import pytest
2
4
from tempfile import NamedTemporaryFile
3
5
from typing import Optional , Generator
@@ -19,6 +21,7 @@ def __call__(
19
21
browser : Optional [Browser ] = None ,
20
22
threshold : Optional [float ] = None ,
21
23
suffix : Optional [str ] = None ,
24
+ xpath : Optional [str ] = "" ,
22
25
) -> bool :
23
26
pass
24
27
@@ -36,22 +39,46 @@ def screenshot_regression(
36
39
:param browser: optional, by default from `browser` fixture
37
40
:param threshold: float, by default from `image_diff_threshold`
38
41
:param suffix: str, need for multiple checks by one test
42
+ :param xpath: str, optional xpath expression to select an element to screenshot instead of page
39
43
"""
40
44
default_browser = browser
41
45
42
46
def _factory (
43
47
browser : Optional [Browser ] = None ,
44
48
threshold : Optional [float ] = None ,
45
49
suffix : Optional [str ] = "" ,
50
+ xpath : Optional [str ] = "" ,
46
51
) -> bool :
47
52
if browser is None :
48
53
browser = default_browser
49
54
50
55
if threshold is None :
51
56
threshold = image_diff_threshold
52
- tf = NamedTemporaryFile (suffix = ".png" )
53
- image = tf .name
54
- browser .driver .save_screenshot (image )
55
- return image_regression (image , threshold , suffix )
57
+
58
+ with NamedTemporaryFile (suffix = ".png" , delete = False ) as tf :
59
+ temp_image_path = pathlib .Path (tf .name )
60
+
61
+ try :
62
+ screenshot_path = os .fspath (temp_image_path )
63
+
64
+ if xpath :
65
+ # `unique_file=False` since we already have a temporary file
66
+ #
67
+ # Since an xpath screenshot composes its own file name, we need to give it the prefix and
68
+ # suffix as separate parameters. `:-4` for the path without extension, then suffix given manually.
69
+ browser .find_by_xpath (xpath ).first .screenshot (screenshot_path [:- 4 ],
70
+ suffix = screenshot_path [- 4 :],
71
+ unique_file = False ,
72
+ full = True ,
73
+ )
74
+ else :
75
+ browser .driver .save_screenshot (screenshot_path )
76
+
77
+ result = image_regression (screenshot_path , threshold , suffix )
78
+ finally :
79
+ temp_image_path .unlink (missing_ok = True )
80
+
81
+ return result
82
+
56
83
57
84
yield _factory
0 commit comments