Debian Codegraph @

tests/conftest.py

raw
1 import os
2 import sys
3 import tempfile
4
5 # Isolate every DisplayCAL user path (preferences/config file, logs, storage,
6 # cache, ...) under a throwaway per-session directory, so running the test
7 # suite never reads from or writes to the developer's real config (e.g.
8 # ~/Library/Preferences/DisplayCAL/DisplayCAL.ini on macOS, ~/.config/DisplayCAL
9 # on Linux). DisplayCAL computes these paths from $HOME (and the XDG_* /
10 # Windows equivalents) at *import time* (see DisplayCAL/defaultpaths.py), so
11 # this must run before the first import of any DisplayCAL module — hence it
12 # sits at the very top of this file, ahead of every other import.
13 _TEST_HOME = tempfile.mkdtemp(prefix="displaycal-test-home-")
14 os.environ["HOME"] = _TEST_HOME
15 # Force (not setdefault) these: CI runners (e.g. GitHub Actions) often already
16 # export XDG_CONFIG_HOME/XDG_CACHE_HOME/XDG_DATA_HOME pointing outside
17 # _TEST_HOME, which would defeat the isolation above.
18 os.environ["XDG_CACHE_HOME"] = os.path.join(_TEST_HOME, ".cache")
19 os.environ["XDG_CONFIG_HOME"] = os.path.join(_TEST_HOME, ".config")
20 os.environ["XDG_DATA_HOME"] = os.path.join(_TEST_HOME, ".local", "share")
21 if sys.platform == "win32":
22 # Best-effort: the pywin32 SHGetSpecialFolderPath lookup DisplayCAL uses on
23 # Windows queries the OS directly and ignores these, but the ctypes
24 # fallback and any other HOME-based logic still benefit.
25 os.environ["USERPROFILE"] = _TEST_HOME
26 os.environ.setdefault("APPDATA", os.path.join(_TEST_HOME, "AppData", "Roaming"))
27 os.environ.setdefault("LOCALAPPDATA", os.path.join(_TEST_HOME, "AppData", "Local"))
28
29 import glob
30 import platform
31 import pathlib
32 import shutil
33 import subprocess
34 import tarfile
35 import time
36 import zipfile
37
38 from urllib.error import URLError
39
40 from requests import HTTPError
41
42 from DisplayCAL.debughelpers import DownloadError
43 import pytest
44
45 from DisplayCAL import config
46 from DisplayCAL.util_os import which
47 from DisplayCAL.worker import Worker
48
49 import DisplayCAL
50 from DisplayCAL import real_display_size_mm
51 from DisplayCAL.argyll import (
52 get_argyll_latest_version,
53 get_argyll_version_string,
54 parse_argyll_version_string,
55 )
56 from DisplayCAL.colormath import get_rgb_space
57 from DisplayCAL.config import setcfg, writecfg
58 from DisplayCAL.icc_profile import ICCProfile
59
60
61 @pytest.fixture(scope="module")
62 def data_files():
63 """Generate data file list."""
64 # test/data
65 extensions = [
66 "*.cal",
67 "*.icc",
68 "*.lin",
69 "*.ti1",
70 "*.ti3",
71 "*.tsv",
72 "*.txt",
73 "*.vrml",
74 ]
75
76 displaycal_parent_dir = pathlib.Path(DisplayCAL.__file__).parent
77 search_paths = [
78 displaycal_parent_dir,
79 displaycal_parent_dir / "presets",
80 displaycal_parent_dir / "ti1",
81 displaycal_parent_dir.parent / "misc" / "ti3",
82 displaycal_parent_dir.parent / "tests" / "data",
83 displaycal_parent_dir.parent / "tests" / "data" / "sample",
84 displaycal_parent_dir.parent / "tests" / "data" / "sample" / "issue129",
85 displaycal_parent_dir.parent / "tests" / "data" / "sample" / "issue268",
86 displaycal_parent_dir.parent / "tests" / "data" / "icc",
87 ]
88 d_files = {}
89 for path in search_paths:
90 for extension in extensions:
91 # add files from DisplayCal/presets folder
92 for element in path.glob(extension):
93 d_files[element.name] = element
94
95 yield d_files
96
97
98 @pytest.fixture(scope="module")
99 def data_path():
100 """Return the tests/data folder path."""
101 displaycal_parent_dir = pathlib.Path(DisplayCAL.__file__).parent
102 return displaycal_parent_dir.parent / "tests" / "data"
103
104
105 @pytest.fixture(scope="session")
106 def setup_argyll():
107 """Setup ArgyllCMS.
108
109 This will search for ArgyllCMS binaries under ``.local/bin/Argyll*/bin`` and if it
110 can not find it, it will download from the source.
111 """
112 # check if ArgyllCMS is already installed
113 xicclu_path = which(f"xicclu{config.EXE_EXT}")
114 if xicclu_path:
115 # ArgyllCMS is already installed
116 argyll_path = pathlib.Path(xicclu_path).parent
117 setcfg("argyll.dir", str(argyll_path.absolute()))
118 argyll_version_string = get_argyll_version_string("xicclu", True, [str(argyll_path)])
119 argyll_version = parse_argyll_version_string(argyll_version_string)
120 print(f"argyll_version_string: {argyll_version_string}")
121 print(f"argyll_version: {argyll_version}")
122 setcfg("argyll.version", argyll_version_string)
123 writecfg()
124 yield argyll_path
125 return
126
127 # first look in to ~/local/bin/ArgyllCMS
128 home = pathlib.Path().home()
129 argyll_search_paths = glob.glob(str(home / ".local" / "bin" / "Argyll*" / "bin"))
130
131 argyll_path = None
132 for path in reversed(argyll_search_paths):
133 path = pathlib.Path(path)
134 if path.is_dir():
135 argyll_path = path
136 setcfg("argyll.dir", str(argyll_path.absolute()))
137 argyll_version_string = get_argyll_version_string(
138 "xicclu", True, [str(path)]
139 )
140 argyll_version = parse_argyll_version_string(argyll_version_string)
141 print(f"argyll_version_string: {argyll_version_string}")
142 print(f"argyll_version: {argyll_version}")
143 setcfg("argyll.version", argyll_version_string)
144 writecfg()
145 break
146
147 print(f"argyll_path: {argyll_path}")
148 if argyll_path:
149 yield argyll_path
150 return
151
152 # apparently argyll has not been found
153 # download from source
154 get_argyll_latest_version.cache_clear()
155 argyll_version = get_argyll_latest_version()
156 if argyll_version == config.DEFAULTS.get("argyll.version"):
157 # get_argyll_latest_version() couldn't reach the GitHub API (e.g. rate
158 # limited) and fell back to the unusable placeholder version, which
159 # would otherwise produce a guaranteed 404 download URL below. Fall
160 # back to the version pinned in the CI workflow (the same version
161 # used to pre-install ArgyllCMS on the runners) instead of giving up.
162 env_version = os.environ.get("ARGYLL_VERSION")
163 if env_version:
164 print(
165 f"Could not determine latest ArgyllCMS version, falling back "
166 f"to $ARGYLL_VERSION={env_version!r}"
167 )
168 argyll_version = env_version
169 argyll_domain = config.DEFAULTS.get("argyll.domain", "")
170 mac_suffix = (
171 "macOS11_arm64_bin.tgz"
172 if platform.machine().lower() in ("arm64", "aarch64")
173 else "osx10.6_x86_64_bin.tgz"
174 )
175 argyll_download_url = {
176 "win32": f"{argyll_domain}/releases/download/{argyll_version}/Argyll_V{argyll_version}_win64_exe.zip",
177 "darwin": f"{argyll_domain}/releases/download/{argyll_version}/Argyll_V{argyll_version}_{mac_suffix}",
178 "linux": f"{argyll_domain}/releases/download/{argyll_version}/Argyll_V{argyll_version}_linux_x86_64_bin.tgz",
179 }
180
181 url = argyll_download_url[sys.platform]
182
183 argyll_temp_path = tempfile.mkdtemp()
184 # store current working directory
185 current_working_directory = os.getcwd()
186
187 # change dir to argyll temp path
188 os.chdir(argyll_temp_path)
189
190 # Download the package file if it doesn't already exist
191 argyll_package_file_name = "Argyll.tgz" if sys.platform != "win32" else "Argyll.zip"
192 if not os.path.exists(argyll_package_file_name):
193 print(f"Downloading: {argyll_package_file_name}")
194 print(f"URL: {url}")
195 worker = Worker()
196 max_download_retries = 3
197 base_delay = 10
198 for download_attempt in range(max_download_retries):
199 result = worker.download(url, download_dir=argyll_temp_path)
200 if isinstance(result, (DownloadError, HTTPError, PermissionError, URLError)):
201 delay = base_delay * (2**download_attempt)
202 if download_attempt < max_download_retries - 1:
203 print(
204 f"Error downloading {url}: {result}. "
205 f"Waiting {delay}s before retry..."
206 )
207 time.sleep(delay)
208 else:
209 print(f"Error downloading {url}: {result}")
210 raise result
211 else:
212 break
213 download_path = result
214 print(f"Downloaded to: {download_path}")
215 if os.path.exists(download_path):
216 shutil.move(download_path, argyll_package_file_name)
217 else:
218 print(f"Package file already exists: {argyll_package_file_name}")
219 print("Not downloading it again!")
220
221 print(f"Decompressing Argyll Package: {argyll_package_file_name}")
222 if sys.platform == "win32":
223 with zipfile.ZipFile(argyll_package_file_name, "r") as zip_ref:
224 zip_ref.extractall()
225 else:
226 with tarfile.open(argyll_package_file_name) as tar:
227 tar.extractall()
228
229 def cleanup():
230 # cleanup the test
231 shutil.rmtree(argyll_temp_path, ignore_errors=True)
232 os.chdir(current_working_directory)
233
234 argyll_path = pathlib.Path(argyll_temp_path) / f"Argyll_V{argyll_version}" / "bin"
235 print(f"argyll_path: {argyll_path}")
236 if argyll_path.is_dir():
237 print("argyll_path is valid!")
238 setcfg("argyll.dir", str(argyll_path.absolute()))
239 argyll_version_string = get_argyll_version_string("xicclu", True, [str(argyll_path)])
240 argyll_version = parse_argyll_version_string(argyll_version_string)
241 print(f"argyll_version_string: {argyll_version_string}")
242 print(f"argyll_version: {argyll_version}")
243 setcfg("argyll.version", argyll_version_string)
244 writecfg()
245 os.environ["PATH"] = f"{argyll_path}{os.pathsep}{os.environ['PATH']}"
246 yield argyll_path
247 setcfg("argyll.dir", "")
248 writecfg()
249 cleanup()
250 else:
251 print("argyll_path is invalid!")
252 cleanup()
253 pytest.skip("ArgyllCMS can not be setup!")
254
255
256 @pytest.fixture(scope="function")
257 def random_icc_profile():
258 """Create a random ICCProfile suitable for modification."""
259 rec709_gamma18 = list(get_rgb_space("Rec. 709"))
260 icc_profile = ICCProfile.from_rgb_space(
261 rec709_gamma18, b"Rec. 709 gamma 1.8"
262 )
263 icc_profile_path = tempfile.mktemp(suffix=".icc")
264 icc_profile.write(icc_profile_path)
265
266 yield icc_profile, icc_profile_path
267
268 # clean the file
269 os.remove(icc_profile_path)
270
271
272 @pytest.fixture(scope="function")
273 def patch_subprocess():
274 """Patch subprocess.
275
276 Yields:
277 Any: The patched subprocess class.
278 """
279
280 class Process:
281 def __init__(self, output=None):
282 self.output = output
283
284 def communicate(self):
285 return self.output, None
286
287 class PatchedSubprocess:
288 passed_args = []
289 passed_kwargs = {}
290 STDOUT = None
291 PIPE = None
292 output = {}
293 wShowWindow = None
294 STARTUPINFO = subprocess.STARTUPINFO if sys.platform == "win32" else None
295 STARTF_USESHOWWINDOW = (
296 subprocess.STARTF_USESHOWWINDOW if sys.platform == "win32" else None
297 )
298 SW_HIDE = subprocess.SW_HIDE if sys.platform == "win32" else None
299
300 @classmethod
301 def Popen(cls, *args, **kwargs):
302 cls.passed_args += args
303 cls.passed_kwargs.update(kwargs)
304 process = Process(output=cls.output.get("".join(*args)))
305 return process
306
307 yield PatchedSubprocess
308
309
310 @pytest.fixture(scope="function")
311 def patch_argyll_util(monkeypatch):
312 """Patch argyll.
313
314 Yields:
315 Any: The patched argyll class.
316 """
317
318 class PatchedArgyll:
319 passed_util_name = []
320
321 @classmethod
322 def get_argyll_util(cls, util_name):
323 cls.passed_util_name.append(util_name)
324 return "dispwin"
325
326 monkeypatch.setattr("DisplayCAL.real_display_size_mm.argyll", PatchedArgyll)
327
328 yield PatchedArgyll
329
330
331 @pytest.fixture(scope="function")
332 def clear_displays():
333 """Clear real_display_size_mm._displays."""
334 real_display_size_mm._displays = None
335 assert real_display_size_mm._displays is None