Skip to content

Commit 80b9b17

Browse files
authored
Merge pull request #2 from matslindh/add-xpath-to-screenshot-regression-and-windows-compatibility-fix
feat: allow xpath for test regression against element + Windows support
2 parents 674c06a + 031f4fb commit 80b9b17

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

pytest_image_diff/splinter.py

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import os
2+
import pathlib
13
import pytest
24
from tempfile import NamedTemporaryFile
35
from typing import Optional, Generator
@@ -19,6 +21,7 @@ def __call__(
1921
browser: Optional[Browser] = None,
2022
threshold: Optional[float] = None,
2123
suffix: Optional[str] = None,
24+
xpath: Optional[str] = "",
2225
) -> bool:
2326
pass
2427

@@ -36,22 +39,46 @@ def screenshot_regression(
3639
:param browser: optional, by default from `browser` fixture
3740
:param threshold: float, by default from `image_diff_threshold`
3841
: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
3943
"""
4044
default_browser = browser
4145

4246
def _factory(
4347
browser: Optional[Browser] = None,
4448
threshold: Optional[float] = None,
4549
suffix: Optional[str] = "",
50+
xpath: Optional[str] = "",
4651
) -> bool:
4752
if browser is None:
4853
browser = default_browser
4954

5055
if threshold is None:
5156
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+
5683

5784
yield _factory

0 commit comments

Comments
 (0)