Debian Codegraph @

tests/test_worker.py

raw
1 from __future__ import annotations
2
3 import configparser
4 import io
5 import pathlib
6 import os
7 import shutil
8 import sys
9 import tempfile
10 from unittest.mock import MagicMock
11 from urllib.error import URLError
12
13 import pytest
14
15 from DisplayCAL import config
16 from DisplayCAL.argyll import (
17 get_argyll_latest_version,
18 get_argyll_util,
19 make_argyll_compatible_path,
20 )
21 from DisplayCAL.cgats import CGATS
22 from DisplayCAL.config import getcfg, initcfg, setcfg
23 from DisplayCAL.debughelpers import Error
24 from DisplayCAL.dev.mocks import check_call_str
25 from DisplayCAL.icc_profile import ICCProfile, LUT16Type
26 from DisplayCAL.meta import DOMAIN
27 from DisplayCAL.worker import (
28 add_keywords_to_cgats,
29 check_cal_isfile,
30 check_create_dir,
31 check_file_isfile,
32 check_profile_isfile,
33 check_ti3_criteria1,
34 create_shaper_curves,
35 extract_device_gray_primaries,
36 get_argyll_version_string,
37 get_options_from_profile,
38 Sudo,
39 Worker,
40 )
41 from tests.data.display_data import DisplayData
42
43
44 def test_get_options_from_profile_1(data_files):
45 """Test ``DisplayCAL.worker.get_options_from_profile()`` function"""
46 profile_path = data_files[
47 "UP2516D #1 2022-03-23 16-06 D6500 2.2 F-S XYZLUT+MTX.icc"
48 ].absolute()
49 options = get_options_from_profile(profile=profile_path)
50 assert options == (
51 [
52 "t6500",
53 "g2.2",
54 "f1.0",
55 "A4.0",
56 "d1",
57 "c1",
58 "yl",
59 "P0.48923385077616427,0.8797619047619047,1.4894179894179895",
60 "H",
61 ],
62 ["qh", "aX", 'A "Dell, Inc."'],
63 )
64
65
66 def test_get_options_from_profile_2(data_files):
67 """Test ``DisplayCAL.worker.get_options_from_profile()`` function, for #69"""
68 profile_path = data_files["SW271 PM PenalNative_KB1_160_2022-03-17.icc"].absolute()
69 options = get_options_from_profile(profile=profile_path)
70 assert options == ([], []) # no options on that profile
71
72
73 def test_make_argyll_compatible_path_1():
74 """make_argyll_compatible_path is working properly with bytes input."""
75 test_value = "C:\\Program Files\\some path\\executable.exe"
76 result = make_argyll_compatible_path(test_value)
77 if sys.platform == "win32":
78 expected_result = "C:\\Program Files\\some path\\executable.exe"
79 else:
80 expected_result = "C_Program Files_some path_executable.exe"
81 assert result == expected_result
82
83
84 def test_make_argyll_compatible_path_2():
85 """make_argyll_compatible_path is working properly with bytes input."""
86 test_value = b"C:\\Program Files\\some path\\executable.exe"
87 result = make_argyll_compatible_path(test_value)
88 if sys.platform == "win32":
89 expected_result = b"C:\\Program Files\\some path\\executable.exe"
90 else:
91 expected_result = b"C_Program Files_some path_executable.exe"
92 assert result == expected_result
93
94
95 def test_make_argyll_compatible_path_is_name_strips_path_separators():
96 """A profile name/description containing '/' must not be able to smuggle
97 a path separator into the sanitized filename (#819)."""
98 test_value = "My Display / Profile"
99 result = make_argyll_compatible_path(test_value, is_name=True)
100 assert "/" not in result
101 assert os.path.sep not in result
102 assert result == "My Display _ Profile"
103
104
105 def test_make_argyll_compatible_path_is_name_strips_path_separators_bytes():
106 """Same as above but for bytes input."""
107 test_value = b"My Display / Profile"
108 result = make_argyll_compatible_path(test_value, is_name=True)
109 assert b"/" not in result
110 assert result == b"My Display _ Profile"
111
112
113 def test_make_argyll_compatible_path_is_name_strips_all_invalid_chars():
114 """is_name=True should strip the full set of filename-invalid characters,
115 not just path separators."""
116 test_value = 'a\\b/c:d;e*f?g"h<i>j|k'
117 result = make_argyll_compatible_path(test_value, is_name=True)
118 for char in '\\/:;*?"<>|':
119 assert char not in result
120
121
122 def test_worker_get_instrument_name_1():
123 """Worker.get_instrument_name() is working properly."""
124 worker = Worker()
125 result = worker.get_instrument_name()
126 expected_result = ""
127 assert result == expected_result
128
129
130 def test_worker_get_instrument_features():
131 """Worker.get_instrument_features() is working properly."""
132 worker = Worker()
133 result = worker.get_instrument_features()
134 assert result == {}
135
136
137 def test_worker_instrument_supports_css_1():
138 """testing if Worker.instrument_supports_ccss is working properly"""
139 worker = Worker()
140 result = worker.instrument_supports_ccss()
141 expected_result = None
142 assert result == expected_result
143
144 # @pytest.mark.skip(reason="Test segfaults with python 3.12 - further investigation required.")
145 def test_generate_b2a_from_inverse_table(data_files, setup_argyll):
146 """Test Worker.generate_B2A_from_inverse_table() method"""
147 import wx
148 from DisplayCAL.argyll import ARGYLL_UTILS
149 from DisplayCAL.config import setcfg, writecfg
150
151 # Other tests in this module call initcfg() which re-reads DisplayCAL.ini
152 # from disk. Under xdist, a concurrent worker may have overwritten that
153 # file with its own (now-deleted) temp Argyll path, poisoning our
154 # in-process config. Re-assert the path from the session fixture and
155 # flush the utility-lookup cache so get_argyll_util() searches fresh.
156 setcfg("argyll.dir", str(setup_argyll))
157 ARGYLL_UTILS.clear()
158 writecfg() # pool workers (SpawnPoolWorker-*) read config from disk
159
160 # for some reason we sometimes need to have a wx.App() running
161 _ = wx.GetApp() or wx.App()
162 worker = Worker()
163 icc_profile1 = ICCProfile(
164 profile=data_files[
165 "Monitor 1 #1 2022-03-09 16-13 D6500 2.2 F-S XYZLUT+MTX.icc"
166 ].absolute()
167 )
168 logfile = io.StringIO()
169 result = worker.generate_B2A_from_inverse_table(icc_profile1, logfile=logfile)
170 assert result is True
171
172
173 def test_apply_black_offset_signature_uses_logfile() -> None:
174 """ICCProfile/LUT16Type.apply_black_offset keep the ``logfile`` parameter.
175
176 Guards the contract the caller relies on (see the functional test below).
177 """
178 import inspect
179
180 for cls in (ICCProfile, LUT16Type):
181 params = inspect.signature(cls.apply_black_offset).parameters
182 assert "logfile" in params, (
183 f"{cls.__name__}.apply_black_offset lost its 'logfile' parameter"
184 )
185 assert "logfiles" not in params, (
186 f"{cls.__name__}.apply_black_offset must not use 'logfiles'"
187 )
188
189
190 def test_blend_profile_blackpoint_calls_apply_black_offset_with_logfile(
191 data_files, monkeypatch
192 ) -> None:
193 """blend_profile_blackpoint must call apply_black_offset with ``logfile=``.
194
195 Regression: it used ``logfiles=``, which raised
196 ``apply_black_offset() got an unexpected keyword argument 'logfiles'`` and
197 aborted 3D LUT creation whenever a black offset was applied. profile1's
198 apply_black_offset is replaced with a strict-signature stub (mirroring
199 ICCProfile.apply_black_offset) so that a ``logfiles=`` call would raise
200 TypeError here, exactly as it did in production.
201 """
202 icc_path = data_files[
203 "UP2516D #1 2022-03-20 02-08 D6500 2.2 F-S XYZLUT+MTX.icc"
204 ].absolute()
205 profile1 = ICCProfile(profile=icc_path)
206 profile2 = ICCProfile(profile=icc_path)
207
208 received = {}
209
210 def strict_apply_black_offset(
211 XYZbp,
212 power=40.0,
213 include_A2B=True,
214 set_blackpoint=True,
215 logfile=None,
216 thread_abort=None,
217 abortmessage="Aborted",
218 include_trc=True,
219 ):
220 received["logfile"] = logfile
221
222 profile1.apply_black_offset = strict_apply_black_offset
223
224 worker = Worker()
225 monkeypatch.setattr(
226 worker, "xicclu", lambda profile, idata, **kwargs: [[0.0, 0.0, 0.0]]
227 )
228 # apply_trc=False forces the branch that applies the black offset.
229 worker.blend_profile_blackpoint(profile1, profile2, apply_trc=False)
230
231 assert "logfile" in received, "apply_black_offset was not called"
232 assert received["logfile"] is not None
233
234
235 def test_generate_b2a_whitepoint_check_tolerance(data_files, monkeypatch) -> None:
236 """The whitepoint sanity check accepts near-D50 and rejects grossly wrong.
237
238 Regression: the check required the normalised white to round to exactly
239 D50 (0.964, 1.0, 0.825), so a real profile whose adapted white was off D50
240 by ~0.001 (chromatic adaptation / measurement / 16-bit encoding) was
241 wrongly rejected with "Invalid white XYZ". It now uses a 0.01 tolerance,
242 which still catches a grossly wrong white from a failed inverse lookup.
243 """
244 import wx
245
246 _ = wx.GetApp() or wx.App()
247 worker = Worker()
248 profile = ICCProfile(
249 profile=data_files[
250 "Monitor 1 #1 2022-03-09 16-13 D6500 2.2 F-S XYZLUT+MTX.icc"
251 ].absolute()
252 )
253 # xicclu returns [black, white, R, G, B] in XYZ for idata
254 # [[0,0,0],[1,1,1],[1,0,0],[0,1,0],[0,0,1]].
255 primaries = [[0.43, 0.22, 0.02], [0.38, 0.71, 0.10], [0.18, 0.07, 0.72]]
256
257 # White ~0.001 off D50 (normalises to ~0.965/1.0/0.824) - must be accepted.
258 def xicclu_near_d50(prof, idata, *args, **kwargs):
259 return [[0.001, 0.001, 0.001], [0.9647, 0.9995, 0.8240], *primaries]
260
261 monkeypatch.setattr(worker, "xicclu", xicclu_near_d50)
262 try:
263 worker.generate_B2A_from_inverse_table(profile, logfile=io.StringIO())
264 except Exception as exc: # may still fail later for unrelated reasons
265 assert "Invalid white" not in str(exc), (
266 "a near-D50 white was wrongly rejected by the sanity check"
267 )
268
269 # Grossly wrong white (normalises far from D50) - must still be rejected.
270 def xicclu_bad_white(prof, idata, *args, **kwargs):
271 return [[0.0, 0.0, 0.0], [0.5, 0.5, 0.4], *primaries]
272
273 monkeypatch.setattr(worker, "xicclu", xicclu_bad_white)
274 with pytest.raises(Error, match="Invalid white"):
275 worker.generate_B2A_from_inverse_table(profile, logfile=io.StringIO())
276
277
278 def test_create_rgb_xyz_clut_fwd_profile_rgb_in_within_device_range(
279 data_files, monkeypatch
280 ) -> None:
281 """The upsampled cLUT lookup grid must stay within device 0..100%.
282
283 Regression for the stale ``step`` bug in create_RGB_XYZ_cLUT_fwd_profile:
284 RGB_in was built with the previous low-resolution iclutres step, so its
285 coordinates ran far past device 100% (e.g. iclutres=5 -> 32 * 25 = 800).
286 xicclu(scale=100) then clamped those out-of-range inputs to the white
287 corner, filling most of the A2B cLUT with the white point.
288 """
289 setcfg("profile.quality", "h")
290 worker = Worker()
291 ti3 = CGATS(
292 str(
293 data_files[
294 "UP2516D #1 2022-03-20 02-08 D6500 2.2 F-S XYZLUT+MTX.ti3"
295 ].absolute()
296 )
297 )
298
299 captured = {}
300
301 def fake_xicclu(prof, idata, *args, **kwargs):
302 # Capture the first lookup (the upsampling grid) and return in-gamut XYZ
303 captured.setdefault("rgb_in", [list(row) for row in idata])
304 return [[50.0, 50.0, 50.0] for _ in idata]
305
306 monkeypatch.setattr(worker, "xicclu", fake_xicclu)
307 worker.create_RGB_XYZ_cLUT_fwd_profile(ti3, "test", "", "", "")
308
309 assert "rgb_in" in captured, "the cLUT upsampling lookup was never reached"
310 max_value = max(max(row) for row in captured["rgb_in"])
311 assert max_value <= 100.0 + 1e-6, (
312 f"RGB_in grid overshoots device 100% (max={max_value:.2f}) - "
313 "stale-step regression in create_RGB_XYZ_cLUT_fwd_profile"
314 )
315
316
317 def test_sudo_class_initialization():
318 """Test worker.Sudo class initialization"""
319 sudo = Sudo()
320 assert sudo is not None
321
322
323 def test_download_method_1():
324 """Test Worker.download() method."""
325 worker = Worker()
326 uri = f"https://{DOMAIN}/i1d3"
327 result = worker.download(uri)
328 assert result is not None
329
330
331 def test_download_method_2():
332 """Test Worker.download() method."""
333 worker = Worker()
334 uri = f"https://{DOMAIN}/i1d3"
335 result = worker.download(uri, force=True)
336 assert result is not None
337
338
339 def test_download_method_3():
340 """Test Worker.download() method."""
341 worker = Worker()
342 uri = f"https://{DOMAIN}/spyd2"
343 result = worker.download(uri)
344 assert result is not None
345
346
347 def test_download_method_4():
348 """Test Worker.download() method."""
349 worker = Worker()
350 uri = f"https://{DOMAIN}/spyd2"
351 result = worker.download(uri, force=True)
352 assert result is not None
353
354
355 def test_get_display_name_1():
356 """Testing Worker.get_display_name() method."""
357 initcfg()
358 setcfg("display.number", 1)
359 worker = Worker()
360 result = worker.get_display_name(False, True, False)
361 assert result == ""
362
363
364 def test_get_pwd():
365 """Testing Worker.get_display_name() method."""
366 initcfg()
367 worker = Worker()
368 test_value = "test_value"
369 worker.pwd = test_value
370 assert worker.pwd == test_value
371
372
373 def test_update_profile_1(random_icc_profile):
374 """Testing Worker.update_profile() method."""
375 from DisplayCAL import worker
376
377 worker.dbus_session = None
378 worker.dbus_system = None
379 initcfg()
380 worker = Worker()
381
382 icc_profile, icc_profile_path = random_icc_profile
383 with check_call_str(
384 "DisplayCAL.worker.Worker.get_display_edid", DisplayData.DISPLAY_DATA_2
385 ):
386 worker.update_profile(icc_profile_path, tags=True)
387
388
389 def test_exec_cmd_1():
390 """Test worker.exec_cmd() function for issue #73"""
391 # Command line:
392 cmd = "/home/eoyilmaz/.local/bin/Argyll_V2.3.0/bin/colprof"
393 args = [
394 "-v",
395 "-qh",
396 "-ax",
397 "-bn",
398 "-C",
399 b"No copyright. Created with DisplayCAL 3.8.9.3 and Argyll CMS 2.3.0",
400 "-A",
401 "Dell, Inc.",
402 "-D",
403 "UP2516D_#1_2022-04-01_00-26_2.2_F-S_XYZLUT+MTX",
404 "/tmp/DisplayCAL-i91d9z8_/UP2516D_#1_2022-04-01_00-26_2.2_F-S_XYZLUT+MTX",
405 ]
406 cwd = "/tmp/DisplayCAL-i91d9z8_"
407 worker = Worker()
408 worker.exec_cmd(cmd=cmd, args=args)
409
410
411 def test_is_allowed_1():
412 """Test Sudo.is_allowed() function for issue #76"""
413 sudo = Sudo()
414 result = sudo.is_allowed()
415 assert result != ""
416
417
418 def test_ti3_lookup_to_ti1_1(data_files, setup_argyll):
419 """Test Worker.ti3_lookup_to_ti1() function for #129"""
420 ti3_path = data_files["0_16_from_issue_129.ti3"].absolute()
421 profile_path = data_files[
422 "UP2516D #1 2022-03-23 16-06 D6500 2.2 F-S XYZLUT+MTX.icc"
423 ].absolute()
424
425 ti3_cgat = CGATS(ti3_path)
426 icc_profile = ICCProfile(profile_path)
427 config.initcfg()
428 worker = Worker()
429 ti1, ti3v = worker.ti3_lookup_to_ti1(ti3_cgat, icc_profile)
430 assert isinstance(ti1, CGATS)
431 assert isinstance(ti3v, CGATS)
432 assert ti1 == {
433 0: {
434 "COLOR_REP": b"RGB",
435 "DATA": {
436 0: {
437 "RGB_B": 99.9959,
438 "RGB_G": 100.0,
439 "RGB_R": 97.1526,
440 "SAMPLE_ID": 1,
441 "XYZ_X": 95.0104,
442 "XYZ_Y": 100.0,
443 "XYZ_Z": 92.7202,
444 },
445 1: {
446 "RGB_B": 9.1428,
447 "RGB_G": 5.8338,
448 "RGB_R": 5.842,
449 "SAMPLE_ID": 2,
450 "XYZ_X": 0.277593,
451 "XYZ_Y": 0.255279,
452 "XYZ_Z": 0.423145,
453 },
454 2: {
455 "RGB_B": 11.6181,
456 "RGB_G": 9.1081,
457 "RGB_R": 8.0801,
458 "SAMPLE_ID": 3,
459 "XYZ_X": 0.51238,
460 "XYZ_Y": 0.536117,
461 "XYZ_Z": 0.705578,
462 },
463 },
464 "DATA_FORMAT": {
465 0: b"SAMPLE_ID",
466 1: b"RGB_R",
467 2: b"RGB_G",
468 3: b"RGB_B",
469 4: b"XYZ_X",
470 5: b"XYZ_Y",
471 6: b"XYZ_Z",
472 },
473 "DESCRIPTOR": b"Argyll Calibration Target chart information 1",
474 "KEYWORDS": {0: b"COLOR_REP"},
475 "NUMBER_OF_FIELDS": None,
476 "NUMBER_OF_SETS": None,
477 }
478 }
479
480 assert ti3v == {
481 "COLOR_REP": b"RGB_XYZ",
482 "CREATED": b"Sun Jun 5 13:08:54 2022",
483 "DATA": {
484 0: {
485 "RGB_B": 99.9959,
486 "RGB_G": 100.0,
487 "RGB_R": 97.1526,
488 "SAMPLE_ID": 1,
489 "XYZ_X": 95.0104,
490 "XYZ_Y": 100.0,
491 "XYZ_Z": 92.7202,
492 },
493 1: {
494 "RGB_B": 9.1428,
495 "RGB_G": 5.8338,
496 "RGB_R": 5.842,
497 "SAMPLE_ID": 2,
498 "XYZ_X": 0.277593,
499 "XYZ_Y": 0.255279,
500 "XYZ_Z": 0.423145,
501 },
502 2: {
503 "RGB_B": 11.6181,
504 "RGB_G": 9.1081,
505 "RGB_R": 8.0801,
506 "SAMPLE_ID": 3,
507 "XYZ_X": 0.51238,
508 "XYZ_Y": 0.536117,
509 "XYZ_Z": 0.705578,
510 },
511 },
512 "DATA_FORMAT": {
513 0: b"SAMPLE_ID",
514 1: b"RGB_R",
515 2: b"RGB_G",
516 3: b"RGB_B",
517 4: b"XYZ_X",
518 5: b"XYZ_Y",
519 6: b"XYZ_Z",
520 },
521 "DESCRIPTOR": b"Argyll Calibration Target chart information 3",
522 "DEVICE_CLASS": b"DISPLAY",
523 "DISPLAY_TYPE_BASE_ID": 1,
524 "DISPLAY_TYPE_REFRESH": b"NO",
525 "INSTRUMENT_TYPE_SPECTRAL": b"NO",
526 "LUMINANCE_XYZ_CDM2": b"42.204124 44.420532 41.186805",
527 "NORMALIZED_TO_Y_100": b"YES",
528 "NUMBER_OF_FIELDS": None,
529 "NUMBER_OF_SETS": None,
530 "ORIGINATOR": b"Argyll dispread",
531 "TARGET_INSTRUMENT": b"Datacolor Spyder3",
532 "VIDEO_LUT_CALIBRATION_POSSIBLE": b"YES",
533 }
534
535
536 def test_add_keywords_to_cgats(data_files) -> None:
537 """Test if keywords are added to cgats by add_keywords_to_cgats."""
538 path = data_files["0_16.ti3"].absolute()
539 cgats = CGATS(cgats=path)
540 assert "keyword" not in cgats[0]
541 options = {"keyword": "Value"}
542 alternated_cgats = add_keywords_to_cgats(cgats, options)
543 assert "keyword" in alternated_cgats[0]
544
545
546 def test_check_create_dir() -> None:
547 """Test function 'check_create_dir'."""
548 assert check_create_dir("test_dir") == True
549
550
551 @pytest.mark.parametrize("file", (True, False))
552 def test_check_cal_isfile(data_files, file: bool) -> None:
553 """Test 'check_cal_isfile'."""
554 path = data_files["Monitor.cal"].absolute() if file else "no_file"
555 assert check_cal_isfile(path) == True if file else "error.calibration.file_missing"
556
557
558 @pytest.mark.parametrize("file", (True, False))
559 def test_check_profile_isfile(data_files, file: bool) -> None:
560 """Test 'check_profile_isfile'."""
561 path = data_files["Monitor.cal"].absolute() if file else "no_file"
562 assert check_profile_isfile(path) == True if file else "error.profile.file_missing"
563
564
565 # todo: test is working locally but not on CI
566 @pytest.mark.skip(
567 reason="First execution of test fails on remote CI server. "
568 "All following tests are positive."
569 )
570 @pytest.mark.parametrize("silent", (True, False), ids=("silent", "not silent"))
571 @pytest.mark.parametrize(
572 "path,result",
573 (
574 ("data/cgats0.txt", ("True", "True")),
575 ("no_file", ("False", "file.missing")),
576 (".", ("False", "file.notfile")),
577 ),
578 )
579 def test_check_file_isfile(
580 data_files, silent: bool, path: str, result: tuple[str, str]
581 ) -> None:
582 """Test if file gets detected."""
583 assert (
584 str(check_file_isfile(path, silent=silent)) == result[0]
585 if silent
586 else result[1]
587 )
588
589
590 @pytest.mark.parametrize(
591 "sample,result",
592 (
593 (
594 {
595 "SAMPLE_ID": 1,
596 "RGB_R": 50,
597 "RGB_G": 50,
598 "RGB_B": 50,
599 "XYZ_X": 0.5,
600 "XYZ_Y": 0.5,
601 "XYZ_Z": 0.5,
602 },
603 True,
604 ),
605 (
606 {
607 "SAMPLE_ID": 2,
608 "RGB_R": 6,
609 "RGB_G": 6,
610 "RGB_B": 6,
611 "XYZ_X": 0.5,
612 "XYZ_Y": 0.5,
613 "XYZ_Z": 0.5,
614 },
615 False,
616 ),
617 ),
618 )
619 def test_check_ti3_criteria1(sample: dict[str:float], result: bool) -> None:
620 """Test for ti3 criteria1 check."""
621 black = (0, 0, 0)
622 white = (110, 110, 110)
623 criteria = check_ti3_criteria1(
624 (sample["RGB_R"], sample["RGB_G"], sample["RGB_B"]),
625 (sample["XYZ_X"], sample["XYZ_Y"], sample["XYZ_Z"]),
626 black,
627 white,
628 print_debuginfo=True,
629 )
630 assert criteria[3] == result
631
632
633 def test_prepare_colprof_for_271(monkeypatch, data_path):
634 """Bug report 271."""
635 assert isinstance(data_path, pathlib.Path)
636
637 def patched_getcfg(key):
638 """patched getcfg()"""
639 cfg = {
640 "argyll.version": "2.3.1",
641 "profile.name.expanded": "test_profile",
642 "profile.quality": "m",
643 "profile.type": "l",
644 "gamap_saturation": False,
645 "gamap_perceptual": False,
646 "profile.quality.b2a": "h",
647 "profile.b2a.hires": True,
648 "copyright": "",
649 "extra_args.colprof": "",
650 "profile.black_point_compensation": False,
651 "profile.black_point_correction": False,
652 "profile.b2a.hires.size": 17,
653 "profile.b2a.hires.smooth": True,
654 "measure.override_min_display_update_delay_ms": False,
655 "measure.override_display_settle_time_mult": False,
656 "patterngenerator.ffp_insertion": False,
657 "testchart.patch_sequence": "",
658 "3dlut.create": False,
659 }
660 return cfg[key]
661
662 monkeypatch.setattr("DisplayCAL.worker.getcfg", patched_getcfg)
663
664 def patched_os_path_exists(filepath):
665 return True
666
667 monkeypatch.setattr("DisplayCAL.worker.os.path.exists", patched_os_path_exists)
668
669 def patched_os_path_isfile(filepath):
670 return True
671
672 monkeypatch.setattr("DisplayCAL.worker.os.path.isfile", patched_os_path_isfile)
673
674 worker = Worker()
675 in_out_file = pathlib.Path(worker.setup_inout("test_profile")).with_suffix(".ti3")
676
677 # copy the test file to the target path
678 test_file_path = data_path / "sample" / "issue271" / "test_profile.ti3"
679 os.makedirs(in_out_file.parent, exist_ok=True)
680 shutil.copy(test_file_path, in_out_file)
681
682 # This should not raise the:
683 # TypeError: startswith first arg must be bytes or a tuple of bytes, not str
684 worker.prepare_colprof()
685
686
687 def test_prepare_dispcal_1():
688 """Worker.prepare_dispcal() return value should be quoted properly."""
689 # prepare_dispcal() builds its arg list from many getcfg() calls, which
690 # only fall back to config.DEFAULTS for options that were never set.
691 # Other tests (in this module and others) call setcfg()/writecfg() and
692 # leave options set for the rest of the pytest-xdist worker process;
693 # initcfg() alone does not clear them, it only merges whatever is on
694 # disk into the same in-memory CFG. Under xdist, which tests ran earlier
695 # on this worker is nondeterministic, so leftover options made the
696 # hardcoded expected_result below flaky (e.g. a stray
697 # "calibration.black_point_correction.auto" left truthy silently drops
698 # the "-k0.0" arg, shifting every index after it).
699 #
700 # Snapshot and clear every option currently set in config.CFG's
701 # "Default" section (the config module monkeypatches
702 # configparser.DEFAULTSECT to "Default", so that's the real section
703 # setcfg()/getcfg() read and write) so this test starts from a
704 # guaranteed config.DEFAULTS state, then restore the snapshot afterwards
705 # so we don't clobber session-scoped state other tests depend on (e.g.
706 # the setup_argyll fixture's "argyll.dir"/"argyll.version").
707 original_cfg = dict(config.CFG["Default"])
708 for name in list(config.CFG["Default"]):
709 setcfg(name, None)
710 try:
711 worker = Worker()
712 return_val = worker.prepare_dispcal()
713 expected_result = [
714 "-v2",
715 "-d0",
716 "-c1",
717 return_val[1][3], # '-yl',
718 return_val[1][4], # '-P0.5,0.5,1.0',
719 "-ql",
720 return_val[1][6], # '-t',
721 "-g2.2",
722 "-f1.0",
723 return_val[1][9], # '-k0.0',
724 "/var/folders/8l/xy1__ym94nn35x86xyg56xq80000gn/T/DisplayCAL-2fdjtyql/",
725 ]
726 assert return_val[0] == get_argyll_util("dispcal")
727 assert isinstance(return_val[1], list)
728 assert return_val[1][:-1] == expected_result[:-1] # don't check the final part
729 assert tempfile.gettempdir() in return_val[1][-1] # in a temp path
730 finally:
731 for name in list(config.CFG["Default"]):
732 setcfg(name, None)
733 for name, value in original_cfg.items():
734 setcfg(name, value)
735
736
737 @pytest.mark.skipif(
738 os.getenv("GITHUB_ACTIONS") == "true",
739 reason="Not working properly on GitHub.",
740 )
741 def test_get_argyll_version_string_returns_a_proper_value():
742 """get_argyll_version_string() returns a proper value."""
743 import wx
744
745 config.initcfg()
746 app = wx.GetApp() or wx.App()
747
748 assert "0.0.0" != get_argyll_version_string(name="ccxxmake", silent=False)
749
750
751 def test_get_argyll_latest_version_returns_str():
752 """get_argyll_latest_version() returns a str."""
753 result = get_argyll_latest_version()
754 assert isinstance(result, str)
755
756
757 @pytest.mark.skipif(
758 os.getenv("GITHUB_ACTIONS") == "true",
759 reason="Test is randomly failing on CI machines."
760 )
761 def test_get_argyll_latest_version_returns_latest_argyll_cms_version():
762 """get_argyll_latest_version() returns the latest argyll cms version."""
763 result = get_argyll_latest_version()
764 assert result == "3.5.0"
765
766
767 def test_get_argyll_latest_version_returns_the_default_version_if_no_internet_connect(
768 monkeypatch,
769 ):
770 """get_argyll_latest_version() returns the default argyll cms version if no internet connection."""
771
772 def patched_urlopen(*args, **kwargs):
773 raise URLError(
774 "<urlopen error [Errno 8] nodename nor servname provided, or not known>"
775 )
776
777 monkeypatch.setattr("DisplayCAL.argyll.urllib.request.urlopen", patched_urlopen)
778 monkeypatch.setattr("DisplayCAL.argyll.time.sleep", lambda _: None)
779 get_argyll_latest_version.cache_clear()
780 result = get_argyll_latest_version()
781 assert result == config.DEFAULTS.get("argyll.version")
782
783
784 @pytest.mark.skipif(
785 os.getenv("GITHUB_ACTIONS") == "true" and sys.platform == "linux",
786 reason="Not working properly on GitHub on Linux machines.",
787 )
788 def test_get_technology_strings_returns_dict(setup_argyll):
789 """Test get_technology_strings() returns a dict."""
790 worker = Worker()
791 result = worker.get_technology_strings()
792 assert isinstance(result, dict)
793
794
795 def test_get_technology_strings_without_argyll_returns_from_argyll_17():
796 """Test get_technology_strings() returns a dictionary from argyll 1.7."""
797 get_argyll_latest_version.cache_clear()
798 worker = Worker()
799 worker.argyll_version = [0, 0, 0]
800
801 result = worker.get_technology_strings()
802 assert result == {
803 "c": "CRT",
804 "m": "Plasma",
805 "l": "LCD",
806 "1": "LCD CCFL",
807 "2": "LCD CCFL IPS",
808 "3": "LCD CCFL VPA",
809 "4": "LCD CCFL TFT",
810 "L": "LCD CCFL Wide Gamut",
811 "5": "LCD CCFL Wide Gamut IPS",
812 "6": "LCD CCFL Wide Gamut VPA",
813 "7": "LCD CCFL Wide Gamut TFT",
814 "e": "LCD White LED",
815 "8": "LCD White LED IPS",
816 "9": "LCD White LED VPA",
817 "d": "LCD White LED TFT",
818 "b": "LCD RGB LED",
819 "f": "LCD RGB LED IPS",
820 "g": "LCD RGB LED VPA",
821 "i": "LCD RGB LED TFT",
822 "h": "LCD RG Phosphor",
823 "j": "LCD RG Phosphor IPS",
824 "k": "LCD RG Phosphor VPA",
825 "n": "LCD RG Phosphor TFT",
826 "o": "LED OLED",
827 "a": "LED AMOLED",
828 "p": "DLP Projector",
829 "q": "DLP Projector RGB Filter Wheel",
830 "r": "DPL Projector RGBW Filter Wheel",
831 "s": "DLP Projector RGBCMY Filter Wheel",
832 "u": "Unknown",
833 }
834
835 @pytest.mark.skipif(
836 os.getenv("GITHUB_ACTIONS") == "true" and sys.platform == "linux",
837 reason="Not working properly on GitHub on Linux machines.",
838 )
839 def test_get_technology_strings_with_argyll_returns_expected_data(setup_argyll):
840 """Test get_technology_strings() returns a dict with correct data."""
841 get_argyll_latest_version.cache_clear()
842 worker = Worker()
843 assert worker.argyll_version != [0, 0, 0]
844 result = worker.get_technology_strings()
845 expected = {
846 "c": "CRT",
847 "m": "Plasma",
848 "l": "LCD",
849 "1": "LCD CCFL",
850 "2": "LCD CCFL IPS",
851 "3": "LCD CCFL PVA",
852 "4": "LCD CCFL TFT",
853 "L": "LCD CCFL Wide Gamut",
854 "5": "LCD CCFL Wide Gamut IPS",
855 "6": "LCD CCFL Wide Gamut PVA",
856 "7": "LCD CCFL Wide Gamut TFT",
857 "e": "LCD White LED",
858 "8": "LCD White LED IPS",
859 "9": "LCD White LED PVA",
860 "d": "LCD White LED TFT",
861 "b": "LCD RGB LED",
862 "f": "LCD RGB LED IPS",
863 "g": "LCD RGB LED PVA",
864 "j": "LCD RGB LED TFT",
865 "h": "LCD RG Phosphor",
866 "k": "LCD RG Phosphor IPS",
867 "n": "LCD RG Phosphor PVA",
868 "q": "LCD RG Phosphor TFT",
869 "r": "LCD PFS Phosphor",
870 "s": "LCD PFS Phosphor IPS",
871 "t": "LCD PFS Phosphor PVA",
872 "v": "LCD PFS Phosphor TFT",
873 "i": "LCD GB-R Phosphor",
874 "x": "LCD GB-R Phosphor IPS",
875 "y": "LCD GB-R Phosphor PVA",
876 "z": "LCD GB-R Phosphor TFT",
877 "o": "LED OLED",
878 "a": "LED AMOLED",
879 "w": "LED WOLED",
880 "p": "DLP Projector",
881 "A": "DLP Projector RGB Filter Wheel",
882 "B": "DLP Projector RGBW Filter Wheel",
883 "C": "DLP Projector RGBCMY Filter Wheel",
884 "u": "Unknown",
885 }
886 assert result == expected
887
888
889 def test_get_technology_strings_parses_ccxxmake_output(monkeypatch):
890 """Technology parser should extract -t entries from ccxxmake output."""
891 worker = Worker()
892 worker.argyll_version = [3, 5, 0]
893
894 def patched_exec_cmd(*args, **kwargs):
895 worker.output = [
896 "-t c CRT",
897 "-t q LCD PFS Phosphor TFT",
898 "-t o LED OLED",
899 "-Y ignored option section",
900 ]
901 return True
902
903 monkeypatch.setattr(worker, "exec_cmd", patched_exec_cmd)
904 result = worker.get_technology_strings()
905 assert result == {
906 "c": "CRT",
907 "q": "LCD PFS Phosphor TFT",
908 "o": "LED OLED",
909 }
910
911
912 def _build_matrix_from_primaries(RGB_XYZ, remaining, white_scale=1.0):
913 """Build a from-chromaticities matrix profile like ``_create_simple_matrix_profile``.
914
915 ``white_scale`` lets the test simulate an inconsistency between the matrix
916 white and the gray-ramp white, which is what makes the shaper curve endpoint
917 drop below 1.0 (see issue #710).
918 """
919 from DisplayCAL import colormath
920
921 XYZbp = RGB_XYZ[(0, 0, 0)]
922 XYZwp = RGB_XYZ[(100, 100, 100)]
923 xy = []
924 for R, G, B in [(100, 0, 0), (0, 100, 0), (0, 0, 100), (100, 100, 100)]:
925 src = RGB_XYZ if R == G == B else remaining
926 X, Y, Z = src[(R, G, B)]
927 if XYZbp != (0, 0, 0):
928 X, Y, Z = colormath.blend_blackpoint(X, Y, Z, XYZbp, (0, 0, 0), XYZwp)
929 xy.append(colormath.XYZ2xyY(*(v / 100 for v in (X, Y, Z)))[:2])
930 profile = ICCProfile.from_chromaticities(
931 xy[0][0], xy[0][1], xy[1][0], xy[1][1], xy[2][0], xy[2][1],
932 xy[3][0], xy[3][1], 2.2, "t", "c", None, None, cat="Bradford",
933 )
934 if white_scale != 1.0:
935 # Make the matrix map device (1, 1, 1) to a brighter-than-media white,
936 # mimicking a matrix/gray-ramp white inconsistency.
937 for channel in "rgb":
938 tag = profile.tags[channel + "XYZ"]
939 tag.X /= white_scale
940 tag.Y /= white_scale
941 tag.Z /= white_scale
942 return profile
943
944
945 @pytest.mark.parametrize("white_scale", [1.0, 0.9757])
946 def test_create_shaper_curves_trc_endpoint_reaches_one(data_files, white_scale):
947 """Matrix display shaper curves must reach 1.0 at device max (issue #710).
948
949 A TRC endpoint below 1.0 makes device white map to a fraction of media
950 white, which causes a CMM to clip near-white source values to device white
951 when inverting the profile at limited precision.
952 """
953 from DisplayCAL import colormath
954
955 ti3 = CGATS(
956 str(data_files["UP2516D #1 2022-03-20 02-08 D6500 2.2 F-S XYZLUT+MTX.ti3"])
957 )[0]
958 _, RGB_XYZ, remaining = extract_device_gray_primaries(ti3, True, lambda *a: None)
959 profile = _build_matrix_from_primaries(RGB_XYZ, remaining, white_scale)
960 bwd_mtx = colormath.get_rgb_space(profile.get_rgb_space("pcs", 1))[-1].inverted()
961
962 curves = create_shaper_curves(
963 RGB_XYZ,
964 bwd_mtx,
965 single_curve=True,
966 bpc=False,
967 profile=profile,
968 options_dispcal=[],
969 optimize=True,
970 cat="Bradford",
971 )
972
973 for curve in curves:
974 # Endpoint reaches device max ...
975 assert curve[-1] == pytest.approx(1.0, abs=1e-9)
976 # ... and the curve is still monotonically increasing.
977 assert all(curve[i] <= curve[i + 1] + 1e-9 for i in range(len(curve) - 1))
978
979
980 @pytest.mark.parametrize(
981 "viewgam_output,expected_coverage",
982 [
983 # Unix-style paths (forward slash)
984 (
985 [
986 "Intersecting volume = 1198577.5 cubic units",
987 "'/usr/share/DisplayCAL/ref/ClayRGB1998.gam' volume = 1209985.9 cubic units, intersect = 99.06%",
988 "'/home/user/profile.gam' volume = 1411797.2 cubic units, intersect = 84.90%",
989 ],
990 0.9906,
991 ),
992 # Windows-style paths (backslash) -- issue #693
993 (
994 [
995 "Intersecting volume = 1198577.5 cubic units",
996 r"'C:\Program Files\DisplayCAL\ref\ClayRGB1998.gam' volume = 1209985.9 cubic units, intersect = 99.06%",
997 r"'C:\Users\user\profile.gam' volume = 1411797.2 cubic units, intersect = 84.90%",
998 ],
999 0.9906,
1000 ),
1001 ],
1002 )
1003 def test_create_gamut_view_worker_parses_coverage(viewgam_output, expected_coverage):
1004 """Coverage percentage is parsed from both Unix and Windows viewgam output paths.
1005
1006 Regression test for issue #693: on Windows, viewgam outputs backslash paths
1007 which the old regex only matched forward slashes and missed Windows paths.
1008 """
1009 mock_worker = MagicMock()
1010 mock_worker.exec_cmd.return_value = True
1011 mock_worker.output = viewgam_output
1012
1013 gamut_coverage = {}
1014 Worker.create_gamut_view_worker(
1015 mock_worker,
1016 viewgam="viewgam",
1017 args=[],
1018 key="adobe-rgb",
1019 src="ClayRGB1998",
1020 gamut_coverage=gamut_coverage,
1021 )
1022
1023 assert "adobe-rgb" in gamut_coverage
1024 assert gamut_coverage["adobe-rgb"] == pytest.approx(expected_coverage, rel=1e-4)
1025
1026
1027 @pytest.mark.parametrize(
1028 "old_value, expected",
1029 [
1030 ("2012_2", "2015_2"),
1031 ("2012_10", "2015_10"),
1032 ],
1033 ids=["2012_2->2015_2", "2012_10->2015_10"],
1034 )
1035 def test_enumerate_displays_migrates_cie2012_observer_names_for_argyll_34(
1036 monkeypatch, request, old_value, expected
1037 ):
1038 """ArgyllCMS 3.4.0 renamed the "2012_*" observers to "2015_*".
1039
1040 Stored config values must be migrated automatically on first run with the new
1041 ArgyllCMS so they don't silently revert to the default "1931_2" observer.
1042 Without migration, getcfg("observer") sees "2012_2" as invalid (not in
1043 VALID_VALUES) and returns the default "1931_2", which means the -Q flag is never
1044 passed to dispcal/dispread, producing wrong calibration and measurement results
1045 (issue #623).
1046 """
1047 from DisplayCAL import config as _config
1048
1049 observer_keys = [
1050 "observer",
1051 "colorimeter_correction.observer",
1052 "colorimeter_correction.observer.reference",
1053 ]
1054
1055 # Save existing CFG values so the test doesn't pollute global config state.
1056 originals = {
1057 k: _config.CFG.get(configparser.DEFAULTSECT, k, fallback=None)
1058 for k in observer_keys
1059 }
1060
1061 def restore_cfg():
1062 for key, val in originals.items():
1063 if val is None:
1064 _config.CFG.remove_option(configparser.DEFAULTSECT, key)
1065 else:
1066 _config.CFG.set(configparser.DEFAULTSECT, key, val)
1067
1068 request.addfinalizer(restore_cfg)
1069
1070 # Preserve VALID_VALUES entries so monkeypatch restores them after the test.
1071 for key in observer_keys:
1072 monkeypatch.setitem(
1073 _config.VALID_VALUES, key, list(_config.VALID_VALUES.get(key, []))
1074 )
1075
1076 # Write old-style names directly to CFG, bypassing VALID_VALUES validation,
1077 # to simulate a config saved with ArgyllCMS < 3.4.0.
1078 for key in observer_keys:
1079 _config.CFG.set(configparser.DEFAULTSECT, key, old_value)
1080
1081 worker = Worker()
1082 monkeypatch.setattr("DisplayCAL.worker.check_argyll_bin", lambda: True)
1083 monkeypatch.setattr("DisplayCAL.worker.writecfg", lambda *a, **kw: None)
1084
1085 def fake_exec_cmd(*args, **kwargs):
1086 worker.output = ["dispcal - Display calibration Version 3.4.0"]
1087 return True
1088
1089 monkeypatch.setattr(worker, "exec_cmd", fake_exec_cmd)
1090
1091 worker.enumerate_displays_and_ports(
1092 silent=True, check_lut_access=False, enumerate_ports=False
1093 )
1094
1095 for key in observer_keys:
1096 result = getcfg(key)
1097 assert result == expected, (
1098 f"{key!r} should have been migrated from {old_value!r} "
1099 f"to {expected!r}, got {result!r}"
1100 )
1101
1102
1103 # ---------------------------------------------------------------------------
1104 # check_instrument_calibration tests (issue #617 – ColorMunki infinite loop)
1105 # ---------------------------------------------------------------------------
1106
1107 COLORMUNKI_CAL_MSG = "Set instrument sensor to calibration position"
1108
1109
1110 def _make_worker_for_cal_test(monkeypatch):
1111 """Return a Worker with do_instrument_calibration and safe_send mocked."""
1112 worker = Worker()
1113 # These attributes are normally set in the worker-thread setup; init them
1114 # manually so the calibration method can be called without a running subprocess.
1115 worker.instrument_calibration_complete = False
1116 worker._last_calibration_msg = None
1117 worker.do_instrument_calibration_calls = []
1118 worker.safe_send_calls = []
1119
1120 def fake_do_instrument_calibration(failed=False):
1121 worker.do_instrument_calibration_calls.append(failed)
1122
1123 def fake_safe_send(data):
1124 worker.safe_send_calls.append(data)
1125
1126 monkeypatch.setattr(worker, "do_instrument_calibration", fake_do_instrument_calibration)
1127 monkeypatch.setattr(worker, "safe_send", fake_safe_send)
1128 return worker
1129
1130
1131 def test_check_instrument_calibration_first_prompt_shows_dialog(monkeypatch):
1132 """First occurrence of a calibration prompt must show the dialog."""
1133 worker = _make_worker_for_cal_test(monkeypatch)
1134 worker.check_instrument_calibration(COLORMUNKI_CAL_MSG)
1135 assert len(worker.do_instrument_calibration_calls) == 1
1136 assert worker.do_instrument_calibration_calls[0] is False
1137 assert worker.safe_send_calls == []
1138 assert worker._last_calibration_msg == COLORMUNKI_CAL_MSG
1139
1140
1141 def test_check_instrument_calibration_duplicate_prompt_auto_retries(monkeypatch):
1142 """Second occurrence of the same prompt must auto-send a space, not show dialog."""
1143 worker = _make_worker_for_cal_test(monkeypatch)
1144 worker.check_instrument_calibration(COLORMUNKI_CAL_MSG)
1145 worker.check_instrument_calibration(COLORMUNKI_CAL_MSG)
1146 # Dialog shown only once; second call triggers a silent keypress
1147 assert len(worker.do_instrument_calibration_calls) == 1
1148 assert worker.safe_send_calls == [" "]
1149
1150
1151 def test_check_instrument_calibration_complete_stops_further_dialogs(monkeypatch):
1152 """After calibration complete, subsequent prompts must be ignored."""
1153 worker = _make_worker_for_cal_test(monkeypatch)
1154 worker.check_instrument_calibration(COLORMUNKI_CAL_MSG)
1155 worker.check_instrument_calibration("Calibration complete")
1156 assert worker.instrument_calibration_complete is True
1157 assert worker._last_calibration_msg is None
1158 # A further prompt arrives – must be silently ignored
1159 worker.check_instrument_calibration(COLORMUNKI_CAL_MSG)
1160 assert len(worker.do_instrument_calibration_calls) == 1
1161 assert worker.safe_send_calls == []
1162
1163
1164 def test_check_instrument_calibration_failure_allows_retry_dialog(monkeypatch):
1165 """After a calibration failure, the next calibration prompt must show a dialog.
1166
1167 The duplicate-suppression state is reset on failure so the user is not stuck
1168 in a silent auto-retry loop after a failed calibration attempt.
1169 """
1170 worker = _make_worker_for_cal_test(monkeypatch)
1171 # First prompt: dialog shown, duplicate tracking starts
1172 worker.check_instrument_calibration(COLORMUNKI_CAL_MSG)
1173 assert len(worker.do_instrument_calibration_calls) == 1
1174 # Simulate duplicate that would normally be auto-retried silently
1175 worker.check_instrument_calibration(COLORMUNKI_CAL_MSG)
1176 assert worker.safe_send_calls == [" "]
1177 # Calibration fails: reset state so the NEXT prompt opens the dialog again
1178 worker._last_calibration_msg = None # mirrors what do_instrument_calibration does on cancel
1179 worker.check_instrument_calibration(COLORMUNKI_CAL_MSG)
1180 assert len(worker.do_instrument_calibration_calls) == 2
1181 assert worker.do_instrument_calibration_calls[1] is False
1182 # No additional silent retries should have been sent
1183 assert len(worker.safe_send_calls) == 1