| 1 |
import io |
| 2 |
import json |
| 3 |
import os |
| 4 |
import platform |
| 5 |
import sys |
| 6 |
import zipfile |
| 7 |
from pathlib import Path |
| 8 |
from unittest.mock import MagicMock |
| 9 |
from zlib import crc32 |
| 10 |
|
| 11 |
import pytest |
| 12 |
import requests |
| 13 |
import wx |
| 14 |
from wx import AppConsole, Button |
| 15 |
|
| 16 |
from DisplayCAL import display_cal, config |
| 17 |
from DisplayCAL import localization as lang |
| 18 |
from DisplayCAL.cgats import CGATS |
| 19 |
from DisplayCAL.config import get_ccxx_testchart, get_icon, getcfg, setcfg |
| 20 |
from DisplayCAL.dev.mocks import check_call, check_call_str |
| 21 |
from DisplayCAL.display_cal import ( |
| 22 |
app_update_check, |
| 23 |
app_up_to_date, |
| 24 |
check_donation, |
| 25 |
colorimeter_correction_check_overwrite, |
| 26 |
colorimeter_correction_web_check_choose, |
| 27 |
donation_message, |
| 28 |
ExtraArgsFrame, |
| 29 |
GamapFrame, |
| 30 |
get_cgats_measurement_mode, |
| 31 |
get_cgats_path, |
| 32 |
get_profile_load_on_login_label, |
| 33 |
IncrementingInt, |
| 34 |
install_scope_handler, |
| 35 |
MainFrame, |
| 36 |
MeasurementFileCheckSanityDialog, |
| 37 |
show_ccxx_error_dialog, |
| 38 |
StartupFrame, |
| 39 |
webbrowser_open, |
| 40 |
) |
| 41 |
from DisplayCAL.icc_profile import ICCProfile |
| 42 |
from DisplayCAL.util_str import universal_newlines |
| 43 |
from DisplayCAL.util_list import intlist |
| 44 |
from DisplayCAL.worker import Worker, check_ti3 |
| 45 |
from DisplayCAL.wx_windows import ConfirmDialog, BaseInteractiveDialog, InfoDialog |
| 46 |
|
| 47 |
|
| 48 |
@pytest.fixture(scope="session", name="app", autouse=True) |
| 49 |
def fixture_app() -> AppConsole: |
| 50 |
"""Return app for tests.""" |
| 51 |
return wx.GetApp() or wx.App() |
| 52 |
|
| 53 |
|
| 54 |
@pytest.fixture(scope="module", name="mainframe") |
| 55 |
def fixture_mainframe() -> MainFrame: |
| 56 |
"""Return mainframe for tests. |
| 57 |
|
| 58 |
Module-scoped (not class-scoped) because MainFrame() also creates hidden |
| 59 |
child top-level windows (infoframe, measureframe, ...) that wx never |
| 60 |
fully releases without a running MainLoop(); building a fresh MainFrame() |
| 61 |
per test function leaked dozens of native windows over the file and |
| 62 |
caused multi-minute stalls on macOS CI runners (#778). |
| 63 |
""" |
| 64 |
worker = Worker() |
| 65 |
return display_cal.MainFrame(worker=worker) |
| 66 |
|
| 67 |
|
| 68 |
def test_update_colorimeter_correction_matrix_ctrl_items_1( |
| 69 |
mainframe: MainFrame, |
| 70 |
) -> None: |
| 71 |
"""MainFrame.update_colorimeter_correction_matrix_ctrl_items() method.""" |
| 72 |
# I have no idea how it works, let's see... |
| 73 |
assert mainframe.colorimeter_correction_matrix_ctrl.Items != [] |
| 74 |
before_items = mainframe.colorimeter_correction_matrix_ctrl.Items |
| 75 |
before_length = len(before_items) |
| 76 |
mainframe.update_colorimeter_correction_matrix_ctrl_items() |
| 77 |
after_items = mainframe.colorimeter_correction_matrix_ctrl.Items |
| 78 |
after_length = len(after_items) |
| 79 |
assert before_length == after_length |
| 80 |
assert before_items == after_items # Really don't know anything about the method |
| 81 |
# but it was raising errors before, now it is fixed. |
| 82 |
|
| 83 |
|
| 84 |
def test_show_ccxx_error_dialog(mainframe: MainFrame) -> None: |
| 85 |
"""Test if error message is shown.""" |
| 86 |
with check_call_str("DisplayCAL.display_cal.show_result_dialog"): |
| 87 |
show_ccxx_error_dialog(Exception("Malformed demo"), "path", mainframe) |
| 88 |
|
| 89 |
|
| 90 |
@pytest.mark.skipif( |
| 91 |
sys.platform == "darwin" and os.getenv("GITHUB_ACTIONS") == "true", |
| 92 |
reason="ShowResultDialog is failing on CI macOS machines, skipping test.", |
| 93 |
) |
| 94 |
@pytest.mark.parametrize("argyll", (True, False), ids=("With argyll", "without argyll")) |
| 95 |
@pytest.mark.parametrize("snapshot", (True, False), ids=("Snapshot", "No snapshot")) |
| 96 |
@pytest.mark.parametrize("silent", (True, False), ids=("Silent", "Not silent")) |
| 97 |
def test_app_update_check( |
| 98 |
mainframe: MainFrame, silent: bool, snapshot: bool, argyll: bool |
| 99 |
) -> None: |
| 100 |
"""Test the application update check.""" |
| 101 |
with check_call(wx, "CallAfter", call_count=1): |
| 102 |
app_update_check(mainframe, silent, snapshot, argyll) |
| 103 |
|
| 104 |
|
| 105 |
def test_check_donation(mainframe: MainFrame) -> None: |
| 106 |
"""Test check for user disabled donation.""" |
| 107 |
with check_call(wx, "CallAfter", call_count=-1): |
| 108 |
check_donation(mainframe, False) |
| 109 |
|
| 110 |
|
| 111 |
def test_app_up_to_date(mainframe: MainFrame) -> None: |
| 112 |
"""Test if 'up to date' messagebox is shown.""" |
| 113 |
with check_call(BaseInteractiveDialog, "ShowModalThenDestroy", call_count=1): |
| 114 |
app_up_to_date(mainframe) |
| 115 |
|
| 116 |
|
| 117 |
@pytest.mark.parametrize("response", (wx.ID_OK, wx.ID_NO), ids=("Ok", "Cancel")) |
| 118 |
def test_donation_message(mainframe: MainFrame, response: int) -> None: |
| 119 |
"""Test if donation messagebox is shown as expected.""" |
| 120 |
with check_call(BaseInteractiveDialog, "ShowModal", response, call_count=1): |
| 121 |
with check_call_str( |
| 122 |
"DisplayCAL.display_cal.launch_file", |
| 123 |
call_count=1 if response == wx.ID_OK else 0, |
| 124 |
): |
| 125 |
donation_message(mainframe) |
| 126 |
|
| 127 |
|
| 128 |
@pytest.mark.skipif( |
| 129 |
os.getenv("GITHUB_ACTIONS") == "true", |
| 130 |
reason="Seems like the first call of ShowWindowModalBlocking always fails on remote." |
| 131 |
"Locally however the problem cannot be reproduced, skipping test for now." |
| 132 |
) |
| 133 |
@pytest.mark.parametrize( |
| 134 |
"update", |
| 135 |
(True, False), |
| 136 |
ids=("update comports", "don't update comports"), |
| 137 |
) |
| 138 |
@pytest.mark.parametrize( |
| 139 |
"response, value", ( |
| 140 |
(wx.ID_OK, True), |
| 141 |
(wx.ID_NO, False), |
| 142 |
), |
| 143 |
ids=("Ok", "Cancel"), |
| 144 |
) |
| 145 |
def test_colorimeter_correction_check_overwrite( |
| 146 |
data_files, mainframe: MainFrame, response: int, value: bool, update: bool |
| 147 |
) -> None: |
| 148 |
"""Test if function reacts as expected to user input.""" |
| 149 |
path = data_files["0_16.ti3"].absolute() |
| 150 |
with open(path, "rb") as cgatsfile: |
| 151 |
cgats = universal_newlines(cgatsfile.read()) |
| 152 |
# Pre-create the target file so os.path.isfile() returns True and the |
| 153 |
# overwrite dialog is always triggered, making the test self-contained. |
| 154 |
target_path = get_cgats_path(cgats) |
| 155 |
os.makedirs(os.path.dirname(target_path), exist_ok=True) |
| 156 |
with open(target_path, "wb") as f: |
| 157 |
f.write(b"placeholder") |
| 158 |
try: |
| 159 |
with check_call(BaseInteractiveDialog, "ShowWindowModalBlocking", response): |
| 160 |
assert colorimeter_correction_check_overwrite(mainframe, cgats, update) == value |
| 161 |
finally: |
| 162 |
if os.path.exists(target_path): |
| 163 |
os.remove(target_path) |
| 164 |
|
| 165 |
|
| 166 |
def test_colorimeter_correction_web_check_choose_observer_column( |
| 167 |
mainframe: MainFrame, |
| 168 |
) -> None: |
| 169 |
"""Regression test: REFERENCE_OBSERVER bytes vs str mismatch. |
| 170 |
|
| 171 |
``CGATS.queryv1()`` returns bytes for "REFERENCE_OBSERVER", but |
| 172 |
``MainFrame.observers_ab`` (built from ``config.VALID_VALUES["observer"]``) |
| 173 |
is keyed by str. Looking the bytes value up directly always missed, so the |
| 174 |
web-check dialog's "observer" column silently fell back to "unknown" for |
| 175 |
every CCMX correction instead of resolving the real label. |
| 176 |
""" |
| 177 |
cgats_text = ( |
| 178 |
'CCMX\n\n' |
| 179 |
'DESCRIPTOR "test"\n' |
| 180 |
'DISPLAY "LCD Monitor"\n' |
| 181 |
'REFERENCE_OBSERVER "1931_2"\n' |
| 182 |
'FIT_METHOD "xy"\n' |
| 183 |
) |
| 184 |
entry = { |
| 185 |
"cgats": cgats_text, |
| 186 |
"type": "ccmx", |
| 187 |
"display": "Dell U2413", |
| 188 |
"manufacturer": "Dell", |
| 189 |
"reference": "i1 Pro", |
| 190 |
"description": "i1 DisplayPro, ColorMunki Display", |
| 191 |
} |
| 192 |
resp = io.BytesIO(json.dumps([entry]).encode("utf-8")) |
| 193 |
expected_label = mainframe.observers_ab["1931_2"] |
| 194 |
# On GTK3, wx.ListCtrl is DisplayCAL.wx_fixes.ListCtrl, a DataViewListCtrl |
| 195 |
# shim whose SetStringItem() only creates the real row once every column |
| 196 |
# has been set. Spy on it (call through to the original) rather than |
| 197 |
# replacing it outright, otherwise the shim never gets a real row and the |
| 198 |
# dialog's later GetItem(0) call crashes with a wx assertion error. |
| 199 |
original_set_string_item = wx.ListCtrl.SetStringItem |
| 200 |
with check_call(BaseInteractiveDialog, "ShowWindowModalBlocking", wx.ID_CANCEL): |
| 201 |
with check_call( |
| 202 |
wx.ListCtrl, "SetStringItem", original_set_string_item, call_count=-1 |
| 203 |
) as calls: |
| 204 |
colorimeter_correction_web_check_choose(resp, mainframe) |
| 205 |
# SetStringItem(index, col, label) is called on the ListCtrl instance, so |
| 206 |
# the recorded args are (self, index, col, label). |
| 207 |
observer_values = [args[3] for args, _kwargs in calls if args[2] == 5] |
| 208 |
assert observer_values |
| 209 |
assert expected_label in observer_values |
| 210 |
assert lang.getstr("unknown") not in observer_values |
| 211 |
|
| 212 |
|
| 213 |
def test_upload_colorimeter_correction_accepts_str_cgats(mainframe: MainFrame) -> None: |
| 214 |
"""Regression test: a str ``cgats`` argument must not raise ``TypeError``. |
| 215 |
|
| 216 |
``upload_colorimeter_correction_handler`` reads the file as str |
| 217 |
(``.decode()``) before calling ``MainFrame.upload_colorimeter_correction``, |
| 218 |
but that method ran a bytes-pattern regex directly against it, raising |
| 219 |
``TypeError`` for every manually-chosen upload file. |
| 220 |
""" |
| 221 |
cgats_text = 'CCMX\n\nORIGINATOR "Argyll dispcal"\nDISPLAY "LCD Monitor"\n' |
| 222 |
with check_call(BaseInteractiveDialog, "ShowWindowModalBlocking", wx.ID_OK): |
| 223 |
with check_call(Worker, "start", call_count=1): |
| 224 |
mainframe.upload_colorimeter_correction(cgats_text) |
| 225 |
|
| 226 |
|
| 227 |
@pytest.mark.parametrize("file", ("0_16.ti3", "0_16_with_refresh.ti3", "default.ti3")) |
| 228 |
@pytest.mark.parametrize( |
| 229 |
"instrument,modes", |
| 230 |
( |
| 231 |
("ColorHug", ("F", "c", None)), |
| 232 |
("ColorHug2", ("F", "c", None)), |
| 233 |
("ColorMunki Smile", ("f", "c", None)), |
| 234 |
("Colorimtre HCFR", ("R", "c", None)), |
| 235 |
("K-10", ("F", "c", None)), |
| 236 |
("fake_instrument", ("l", "c", None)), |
| 237 |
), |
| 238 |
) |
| 239 |
def test_get_cgats_measurement_mode( |
| 240 |
data_files, instrument: str, file: str, modes: tuple[str, str, None] |
| 241 |
) -> None: |
| 242 |
"""Test if expected measurement mode is returned.""" |
| 243 |
path = data_files[file].absolute() |
| 244 |
cgats = CGATS(cgats=path) |
| 245 |
if file == "0_16.ti3": |
| 246 |
mode = modes[0] |
| 247 |
elif file == "0_16_with_refresh.ti3": |
| 248 |
mode = modes[1] |
| 249 |
else: |
| 250 |
mode = modes[2] |
| 251 |
assert get_cgats_measurement_mode(cgats, instrument) == mode |
| 252 |
|
| 253 |
|
| 254 |
def test_get_cgats_path(data_files) -> None: |
| 255 |
"""Test if correct cgats path is returned.""" |
| 256 |
path = data_files["default.ti3"].absolute() |
| 257 |
with open(path, "rb") as cgatsfile: |
| 258 |
cgats = universal_newlines(cgatsfile.read()) |
| 259 |
assert Path( |
| 260 |
config.get_argyll_data_dir() |
| 261 |
) / "Argyll Calibration Target chart information 3.cti3" == Path( |
| 262 |
get_cgats_path(cgats) |
| 263 |
) |
| 264 |
|
| 265 |
|
| 266 |
def test_restore_testchart_clears_crash_state(mainframe: MainFrame) -> None: |
| 267 |
"""restore_testchart() should clear testchart.file.backup left by a crash. |
| 268 |
|
| 269 |
If DisplayCAL crashes during a CCXX measurement, testchart.file is set to |
| 270 |
the CCXX testchart and testchart.file.backup holds the original path. |
| 271 |
restore_testchart() must restore the original and clear the backup so that |
| 272 |
is_ccxx_testchart() returns False and the correction section is shown. |
| 273 |
""" |
| 274 |
from DisplayCAL.config import is_ccxx_testchart |
| 275 |
|
| 276 |
original_testchart = getcfg("testchart.file") |
| 277 |
ccxx_testchart = get_ccxx_testchart() |
| 278 |
|
| 279 |
# Simulate the config state left after a crash mid-CCXX measurement. |
| 280 |
setcfg("testchart.file.backup", original_testchart) |
| 281 |
setcfg("testchart.file", ccxx_testchart) |
| 282 |
|
| 283 |
try: |
| 284 |
assert is_ccxx_testchart(), "Pre-condition: should look like a CCXX testchart" |
| 285 |
mainframe.restore_testchart() |
| 286 |
assert not is_ccxx_testchart(), "After restore, should no longer be CCXX testchart" |
| 287 |
assert getcfg("testchart.file") == original_testchart |
| 288 |
assert getcfg("testchart.file.backup", False) is None |
| 289 |
finally: |
| 290 |
# Ensure clean state for other tests regardless of assertion outcome. |
| 291 |
setcfg("testchart.file", original_testchart) |
| 292 |
setcfg("testchart.file.backup", None) |
| 293 |
|
| 294 |
|
| 295 |
def test_restore_measurement_mode_clears_crash_state(mainframe: MainFrame) -> None: |
| 296 |
"""restore_measurement_mode() should clear backup values left by a crash. |
| 297 |
|
| 298 |
If DisplayCAL crashes during a CCXX measurement, measurement_mode.backup |
| 299 |
holds the original mode. restore_measurement_mode() must restore it and |
| 300 |
clear the backup. |
| 301 |
""" |
| 302 |
original_mode = getcfg("measurement_mode") |
| 303 |
|
| 304 |
setcfg("measurement_mode.backup", original_mode) |
| 305 |
setcfg("measurement_mode", "c") # Simulate mode changed for CCXX measurement. |
| 306 |
|
| 307 |
try: |
| 308 |
mainframe.restore_measurement_mode() |
| 309 |
assert getcfg("measurement_mode") == original_mode |
| 310 |
assert getcfg("measurement_mode.backup", False) is None |
| 311 |
finally: |
| 312 |
setcfg("measurement_mode", original_mode) |
| 313 |
setcfg("measurement_mode.backup", None) |
| 314 |
|
| 315 |
|
| 316 |
def test_get_profile_load_on_login_label() -> None: |
| 317 |
"""Test if load on login label is returned.""" |
| 318 |
assert get_profile_load_on_login_label(True) == "profile.load_on_login" |
| 319 |
|
| 320 |
|
| 321 |
def test_install_scope_handler(mainframe: MainFrame) -> None: |
| 322 |
"""Test if install scope handler calls the correct methods for authentication dialog.""" |
| 323 |
dlg = ConfirmDialog( |
| 324 |
mainframe, |
| 325 |
title="colorimeter_correction.import", |
| 326 |
msg="msg", |
| 327 |
ok="ok", |
| 328 |
cancel="cancel", |
| 329 |
bitmap=get_icon(32, "dialog-information"), |
| 330 |
alt="file.select", |
| 331 |
) |
| 332 |
dlg.install_systemwide = wx.RadioButton(dlg, -1, "install_local_system") |
| 333 |
dlg.install_systemwide.Bind(wx.EVT_RADIOBUTTON, install_scope_handler) |
| 334 |
with check_call(Button, "SetAuthNeeded", call_count=2): |
| 335 |
install_scope_handler(dlg=dlg) |
| 336 |
|
| 337 |
|
| 338 |
def test_webbrowser_open(monkeypatch) -> None: |
| 339 |
"""Test if function calls browser as expected.""" |
| 340 |
opened_urls = [] |
| 341 |
|
| 342 |
class PatchedWebBrowser: |
| 343 |
@staticmethod |
| 344 |
def open(url: str, new: int = 0, autoraise: bool = True) -> bool: |
| 345 |
opened_urls.append(url) |
| 346 |
return True |
| 347 |
|
| 348 |
# patch webbrowser.open |
| 349 |
monkeypatch.setattr("DisplayCAL.display_cal.webbrowser", PatchedWebBrowser) |
| 350 |
assert opened_urls == [] |
| 351 |
url = "https://github.com/eoyilmaz/displaycal-py3" |
| 352 |
assert webbrowser_open(url) |
| 353 |
assert opened_urls == [url] |
| 354 |
|
| 355 |
|
| 356 |
def test_incrementing_int() -> None: |
| 357 |
"""Testing if self incrementing int increments every time it is used.""" |
| 358 |
inc_integer = IncrementingInt() |
| 359 |
assert int(inc_integer) == 0 |
| 360 |
[int(inc_integer) for _ in range(9)] |
| 361 |
assert int(inc_integer) == 10 |
| 362 |
|
| 363 |
|
| 364 |
def test_init_extra_args_frame(mainframe: MainFrame) -> None: |
| 365 |
"""Test if ExtraArgsFrame is initialized properly""" |
| 366 |
with check_call(ExtraArgsFrame, "update_controls"): |
| 367 |
ExtraArgsFrame(mainframe) |
| 368 |
|
| 369 |
|
| 370 |
def test_init_gamap_frame(mainframe: MainFrame) -> None: |
| 371 |
"""Test if GamapFrame is initialized properly.""" |
| 372 |
with check_call(GamapFrame, "update_layout"): |
| 373 |
GamapFrame(mainframe) |
| 374 |
|
| 375 |
|
| 376 |
@pytest.mark.skipif( |
| 377 |
sys.platform == "darwin" and os.getenv("GITHUB_ACTIONS") == "true", |
| 378 |
reason="StartupFrame is failing on CI macOS machines, skipping test.", |
| 379 |
) |
| 380 |
def test_init_startup_frame() -> None: |
| 381 |
"""Test if StartupFrame is initialized properly.""" |
| 382 |
show_func_name = "Show" |
| 383 |
if ( |
| 384 |
sys.platform == "darwin" |
| 385 |
and intlist(platform.mac_ver()[0].split(".")) >= [10, 10] |
| 386 |
) or os.getenv("XDG_SESSION_TYPE") == "wayland": |
| 387 |
show_func_name = "ShowModal" |
| 388 |
|
| 389 |
with check_call(StartupFrame, show_func_name): |
| 390 |
StartupFrame() |
| 391 |
|
| 392 |
|
| 393 |
@pytest.mark.skipif( |
| 394 |
sys.platform == "darwin", |
| 395 |
reason="MeasurementFileCheckSanityDialog hard-crashes the pytest-xdist worker " |
| 396 |
"process on macOS due to wxPython grid widget creation in a subprocess context.", |
| 397 |
) |
| 398 |
def test_init_measurement_file_check_sanity_dialog_frame( |
| 399 |
data_files, mainframe: MainFrame |
| 400 |
) -> None: |
| 401 |
"""Test if MeasurementFileCheckSanityDialog is initialized properly.""" |
| 402 |
path = data_files["0_16.ti3"].absolute() |
| 403 |
cgats = CGATS(cgats=path) |
| 404 |
with check_call(MeasurementFileCheckSanityDialog, "Center"): |
| 405 |
MeasurementFileCheckSanityDialog(mainframe, cgats[0], check_ti3(cgats), False) |
| 406 |
|
| 407 |
|
| 408 |
# --------------------------------------------------------------------------- |
| 409 |
# is_new_update() unit tests |
| 410 |
# --------------------------------------------------------------------------- |
| 411 |
|
| 412 |
def test_is_new_update_returns_version_when_newer(monkeypatch): |
| 413 |
"""is_new_update() returns a version tuple when a newer release exists.""" |
| 414 |
mock_resp = MagicMock() |
| 415 |
mock_resp.json.return_value = {"tag_name": "99.0.0", "assets": []} |
| 416 |
monkeypatch.setattr("DisplayCAL.display_cal.requests.get", lambda *a, **kw: mock_resp) |
| 417 |
result = display_cal.is_new_update() |
| 418 |
assert result == (99, 0, 0) |
| 419 |
|
| 420 |
|
| 421 |
def test_is_new_update_returns_false_when_current(monkeypatch): |
| 422 |
"""is_new_update() returns False when already on the latest version.""" |
| 423 |
from DisplayCAL.meta import VERSION_TUPLE |
| 424 |
tag = ".".join(str(n) for n in VERSION_TUPLE[:3]) |
| 425 |
mock_resp = MagicMock() |
| 426 |
mock_resp.json.return_value = {"tag_name": tag, "assets": []} |
| 427 |
monkeypatch.setattr("DisplayCAL.display_cal.requests.get", lambda *a, **kw: mock_resp) |
| 428 |
assert display_cal.is_new_update() is False |
| 429 |
|
| 430 |
|
| 431 |
def test_is_new_update_returns_false_on_network_error(monkeypatch): |
| 432 |
"""is_new_update() returns False and does not raise on network failures.""" |
| 433 |
def raise_error(*a, **kw): |
| 434 |
raise requests.RequestException("connection refused") |
| 435 |
monkeypatch.setattr("DisplayCAL.display_cal.requests.get", raise_error) |
| 436 |
assert display_cal.is_new_update() is False |
| 437 |
|
| 438 |
|
| 439 |
def test_is_new_update_returns_false_on_bad_json(monkeypatch): |
| 440 |
"""is_new_update() returns False when the response JSON is missing expected keys.""" |
| 441 |
mock_resp = MagicMock() |
| 442 |
mock_resp.json.return_value = {"unexpected_key": "value"} |
| 443 |
monkeypatch.setattr("DisplayCAL.display_cal.requests.get", lambda *a, **kw: mock_resp) |
| 444 |
assert display_cal.is_new_update() is False |
| 445 |
|
| 446 |
|
| 447 |
# --------------------------------------------------------------------------- |
| 448 |
# get_download_url() unit tests |
| 449 |
# --------------------------------------------------------------------------- |
| 450 |
|
| 451 |
@pytest.mark.parametrize("plat,machine,version,expected_filename", [ |
| 452 |
("win32", "AMD64", "3.9.0", "DisplayCAL-3.9.0-Windows-x64.exe"), |
| 453 |
("win32", "ARM64", "3.9.0", "DisplayCAL-3.9.0-Windows-arm64.exe"), |
| 454 |
("darwin", "arm64", "3.9.0", "DisplayCAL-3.9.0-macOS-arm64.dmg"), |
| 455 |
("darwin", "aarch64", "3.9.0", "DisplayCAL-3.9.0-macOS-arm64.dmg"), |
| 456 |
("darwin", "x86_64", "3.9.0", "DisplayCAL-3.9.0-macOS-x86.dmg"), |
| 457 |
("linux", "x86_64", "3.9.0", "displaycal-3.9.0.tar.gz"), |
| 458 |
]) |
| 459 |
def test_get_download_url(monkeypatch, plat, machine, version, expected_filename): |
| 460 |
"""get_download_url() returns the correct asset URL for each platform.""" |
| 461 |
fake_assets = [ |
| 462 |
{"name": expected_filename, |
| 463 |
"browser_download_url": f"https://example.com/{expected_filename}"}, |
| 464 |
] |
| 465 |
monkeypatch.setattr(display_cal, "RELEASE_DATA", {"assets": fake_assets}) |
| 466 |
monkeypatch.setattr(display_cal.sys, "platform", plat) |
| 467 |
monkeypatch.setattr(display_cal.platform, "machine", lambda: machine) |
| 468 |
assert display_cal.get_download_url(version) == f"https://example.com/{expected_filename}" |
| 469 |
|
| 470 |
|
| 471 |
def test_get_download_url_returns_none_when_no_matching_asset(monkeypatch): |
| 472 |
"""get_download_url() returns None when no asset matches the current platform.""" |
| 473 |
monkeypatch.setattr(display_cal, "RELEASE_DATA", {"assets": []}) |
| 474 |
monkeypatch.setattr(display_cal.sys, "platform", "linux") |
| 475 |
monkeypatch.setattr(display_cal.platform, "machine", lambda: "x86_64") |
| 476 |
assert display_cal.get_download_url("3.9.0") is None |
| 477 |
|
| 478 |
|
| 479 |
def test_get_download_url_returns_none_before_release_data_loaded(monkeypatch): |
| 480 |
"""get_download_url() returns None gracefully when called before is_new_update().""" |
| 481 |
monkeypatch.setattr(display_cal, "RELEASE_DATA", None) |
| 482 |
assert display_cal.get_download_url("3.9.0") is None |
| 483 |
|
| 484 |
|
| 485 |
def test_create_profile_name_crc32_with_bytes_edid( |
| 486 |
mainframe: MainFrame, monkeypatch |
| 487 |
) -> None: |
| 488 |
"""create_profile_name() resolves %crc32 when EDID data is bytes (#776).""" |
| 489 |
raw_edid = b"\x00\xff\xff\xff\xff\xff\xff\x00test-edid-payload" |
| 490 |
monkeypatch.setattr( |
| 491 |
mainframe.worker, "get_display_edid", lambda: {"edid": raw_edid} |
| 492 |
) |
| 493 |
mainframe.profile_name_textctrl.SetValue("%crc32") |
| 494 |
expected = "%X" % (crc32(raw_edid) & 0xFFFFFFFF) |
| 495 |
assert mainframe.create_profile_name() == expected |
| 496 |
|
| 497 |
|
| 498 |
def test_create_profile_name_crc32_with_str_edid( |
| 499 |
mainframe: MainFrame, monkeypatch |
| 500 |
) -> None: |
| 501 |
"""create_profile_name() resolves %crc32 when EDID data is a str.""" |
| 502 |
raw_edid = "test-edid-payload" |
| 503 |
monkeypatch.setattr( |
| 504 |
mainframe.worker, "get_display_edid", lambda: {"edid": raw_edid} |
| 505 |
) |
| 506 |
mainframe.profile_name_textctrl.SetValue("%crc32") |
| 507 |
expected = "%X" % (crc32(raw_edid.encode("utf-8")) & 0xFFFFFFFF) |
| 508 |
assert mainframe.create_profile_name() == expected |
| 509 |
|
| 510 |
|
| 511 |
def test_create_profile_name_crc32_without_edid( |
| 512 |
mainframe: MainFrame, monkeypatch |
| 513 |
) -> None: |
| 514 |
"""create_profile_name() strips %crc32 when no EDID data is available.""" |
| 515 |
monkeypatch.setattr(mainframe.worker, "get_display_edid", lambda: {}) |
| 516 |
mainframe.profile_name_textctrl.SetValue("name-%crc32-suffix") |
| 517 |
assert mainframe.create_profile_name() == "name-suffix" |
| 518 |
|
| 519 |
|
| 520 |
def test_create_profile_handler_accepts_valid_embedded_cti3( |
| 521 |
data_files, mainframe: MainFrame |
| 522 |
) -> None: |
| 523 |
"""Regression test for issue #811: bytes-vs-str "CTI3" comparison bug. |
| 524 |
|
| 525 |
``(profile.tags.get("CIED", "") or profile.tags.get("targ", ""))[0:4] != |
| 526 |
"CTI3"`` compared the ``bytes`` slice of an embedded ``Text`` tag against |
| 527 |
the ``str`` literal ``"CTI3"``, which is never equal in Python 3, so the |
| 528 |
"no embedded ti3" error fired for every ICC profile regardless of its |
| 529 |
actual content. Uses a real profile with a valid embedded CTI3 chart and |
| 530 |
asserts the ``profile.no_embedded_ti3`` ``InfoDialog`` is never shown. |
| 531 |
""" |
| 532 |
icc_path = str( |
| 533 |
data_files[ |
| 534 |
"UP2516D #1 2022-03-20 02-08 D6500 2.2 F-S XYZLUT+MTX.icc" |
| 535 |
].absolute() |
| 536 |
) |
| 537 |
with check_call(InfoDialog, "ShowModal", wx.ID_OK, call_count=0): |
| 538 |
with check_call(wx.FileDialog, "ShowModal", wx.ID_CANCEL, call_count=1): |
| 539 |
mainframe.create_profile_handler(None, icc_path, False) |
| 540 |
|
| 541 |
|
| 542 |
def test_measurement_file_check_handler_regenerates_profile_without_typeerror( |
| 543 |
data_files, mainframe: MainFrame, monkeypatch |
| 544 |
) -> None: |
| 545 |
"""Regression test for issue #811. |
| 546 |
|
| 547 |
Covers two bugs in ``measurement_file_check_handler()``'s profile |
| 548 |
regeneration branch: |
| 549 |
|
| 550 |
1. The bytes-vs-str "CTI3" comparison (same bug as |
| 551 |
``test_create_profile_handler_accepts_valid_embedded_cti3`` above, but |
| 552 |
at this method's own call site): asserted via the |
| 553 |
``profile.no_embedded_ti3`` ``InfoDialog`` never being shown. |
| 554 |
2. ``profile.tags.targ = TextType(b"text\\0\\0\\0\\0" + ti3 + b"\\0", ...)`` |
| 555 |
concatenated ``bytes`` with a ``CGATS`` instance (``ti3`` is reassigned |
| 556 |
to ``CGATS(ti3)`` earlier in the method), raising ``TypeError`` on |
| 557 |
every profile regeneration. Fixed by using ``bytes(ti3)``. |
| 558 |
""" |
| 559 |
icc_path = str( |
| 560 |
data_files[ |
| 561 |
"UP2516D #1 2022-03-20 02-08 D6500 2.2 F-S XYZLUT+MTX.icc" |
| 562 |
].absolute() |
| 563 |
) |
| 564 |
|
| 565 |
def _fake_confirm(self, ti3=None, force=False, parent=None): |
| 566 |
# Skip the sanity-check dialog itself (covered elsewhere); pretend |
| 567 |
# the user removed a suspicious patch so the regeneration branch runs. |
| 568 |
ti3.modified = True |
| 569 |
return True |
| 570 |
|
| 571 |
# wx.FileDialog is DisplayCAL.wx_fixes.FileDialog, whose GetPath()/etc. |
| 572 |
# are proxied to an inner ``self.filedialog`` via __getattr__ rather than |
| 573 |
# being real class attributes, so stub GetPath as an instance attribute |
| 574 |
# (which __getattr__ never intercepts) right after construction. |
| 575 |
original_filedialog_init = wx.FileDialog.__init__ |
| 576 |
|
| 577 |
def _fake_filedialog_init(self, *args, **kwargs): |
| 578 |
original_filedialog_init(self, *args, **kwargs) |
| 579 |
self.GetPath = lambda: icc_path |
| 580 |
|
| 581 |
monkeypatch.setattr(wx.FileDialog, "__init__", _fake_filedialog_init) |
| 582 |
monkeypatch.setattr(wx.FileDialog, "ShowModal", lambda self: wx.ID_OK) |
| 583 |
monkeypatch.setattr( |
| 584 |
MainFrame, "measurement_file_check_confirm", _fake_confirm |
| 585 |
) |
| 586 |
monkeypatch.setattr(ConfirmDialog, "ShowModal", lambda self: wx.ID_OK) |
| 587 |
create_profile_calls = [] |
| 588 |
monkeypatch.setattr( |
| 589 |
MainFrame, |
| 590 |
"create_profile_handler", |
| 591 |
lambda self, event, path, skip_ti3_check: create_profile_calls.append(path), |
| 592 |
) |
| 593 |
with check_call(InfoDialog, "ShowModal", wx.ID_OK, call_count=0): |
| 594 |
mainframe.measurement_file_check_handler(None) |
| 595 |
assert len(create_profile_calls) == 1 |
| 596 |
assert create_profile_calls[0].endswith( |
| 597 |
os.path.basename(icc_path) |
| 598 |
) |
| 599 |
|
| 600 |
|
| 601 |
def test_import_session_archive_producer_returns_extracted_file_extension( |
| 602 |
tmp_path, mainframe: MainFrame |
| 603 |
) -> None: |
| 604 |
"""Regression test for issue #817. |
| 605 |
|
| 606 |
``import_session_archive_producer()`` used to return a path built from |
| 607 |
the archive's own extension (``.zip``/``.7z``/``.tgz``) instead of the |
| 608 |
extension of the file actually extracted from it (``.cal``/``.icc``/ |
| 609 |
``.icm``), so ``load_cal_handler()`` was handed a path to a file that |
| 610 |
never existed on disk and silently treated the import as missing. |
| 611 |
""" |
| 612 |
basename = "test" |
| 613 |
archive_path = tmp_path / f"{basename}.zip" |
| 614 |
with zipfile.ZipFile(archive_path, "w") as archive: |
| 615 |
archive.writestr(f"{basename}/{basename}.cal", b"dummy calibration data") |
| 616 |
|
| 617 |
result = mainframe.import_session_archive_producer( |
| 618 |
str(archive_path), basename, ".zip" |
| 619 |
) |
| 620 |
|
| 621 |
assert not isinstance(result, Exception) |
| 622 |
assert result == os.path.join(getcfg("profile.save_path"), basename, f"{basename}.cal") |
| 623 |
|
| 624 |
|
| 625 |
def test_load_cal_handler_proceeds_for_cal_files_with_no_profile( |
| 626 |
data_files, mainframe: MainFrame, monkeypatch |
| 627 |
) -> None: |
| 628 |
"""Regression test for issue #820. |
| 629 |
|
| 630 |
``parse_calibration_file()`` only ever returns a non-``None`` ``profile`` |
| 631 |
for ``.icc``/``.icm`` paths (it stays ``None`` for ``.cal`` files, which |
| 632 |
have no embedded ``ICCProfile`` at all). But ``load_cal_handler()``'s |
| 633 |
early-out checked ``if profile is None or ti3_lines is None: return``, |
| 634 |
so it always bailed before doing anything for every ``.cal`` file, |
| 635 |
regardless of whether it parsed successfully. Only ``ti3_lines`` (the |
| 636 |
actual parse-failure signal) should gate the early return. |
| 637 |
""" |
| 638 |
monkeypatch.setattr( |
| 639 |
display_cal, "check_set_argyll_bin", lambda *args, **kwargs: True |
| 640 |
) |
| 641 |
# load_cal_handler() bails immediately if a previous test left this set; |
| 642 |
# it is unrelated to the bug under test here. |
| 643 |
setcfg("settings.changed", 0) |
| 644 |
path = str( |
| 645 |
data_files[ |
| 646 |
"UP2516D #1 2022-03-20 02-08 D6500 2.2 F-S XYZLUT+MTX.cal" |
| 647 |
].absolute() |
| 648 |
) |
| 649 |
|
| 650 |
mainframe.load_cal_handler(None, path=path) |
| 651 |
|
| 652 |
assert getcfg("last_cal_or_icc_path") == path |
| 653 |
|
| 654 |
|
| 655 |
def test_load_cal_handler_config_mapper_block_bytes_str_bugs( |
| 656 |
data_files, tmp_path, mainframe: MainFrame, monkeypatch |
| 657 |
) -> None: |
| 658 |
"""Regression test for issue #820. |
| 659 |
|
| 660 |
Covers all four bugs in ``load_cal_handler()``'s 3D LUT / profile-B2A |
| 661 |
config-mapper block (the ``BEGIN_DATA_FORMAT``-guarded block that reads |
| 662 |
``PATCH_SEQUENCE``, ``3DLUT_GAMUT_MAPPING_MODE``, etc. from a saved |
| 663 |
``.cal``/profile file): |
| 664 |
|
| 665 |
1. ``"BEGIN_DATA_FORMAT" in ti3_lines`` compared a ``str`` literal |
| 666 |
against ``ti3_lines`` (``list[bytes]``), so the whole block, along |
| 667 |
with the five smaller ``ti3_lines`` checks above it, was unreachable |
| 668 |
dead code. |
| 669 |
2. ``cfgvalue = 0 if cfgvalue == "G" else 1`` compared ``bytes`` against |
| 670 |
a ``str`` literal, always forcing ``3dlut.gamap.use_b2a`` to ``1``. |
| 671 |
3. ``cfgvalue.lower().replace("_rgb_", "_RGB_")`` called ``bytes`` |
| 672 |
methods with ``str`` arguments, raising ``TypeError`` for |
| 673 |
``PATCH_SEQUENCE``. |
| 674 |
4. ``cfgvalue = str(cfgvalue)`` stringified the ``bytes`` repr (e.g. |
| 675 |
``"b'...'"``) instead of decoding it, corrupting every keyword |
| 676 |
``CGATS.queryv1()`` left as ``bytes``. |
| 677 |
|
| 678 |
Builds a ``.cal`` file from a real fixture with ``PATCH_SEQUENCE`` and |
| 679 |
``3DLUT_GAMUT_MAPPING_MODE`` keywords inserted ahead of the first |
| 680 |
``BEGIN_DATA_FORMAT`` marker (mirroring how Argyll writes these), then |
| 681 |
asserts both end up correctly decoded/mapped instead of at their |
| 682 |
(different) config defaults. |
| 683 |
""" |
| 684 |
monkeypatch.setattr( |
| 685 |
display_cal, "check_set_argyll_bin", lambda *args, **kwargs: True |
| 686 |
) |
| 687 |
# load_cal_handler() bails immediately if a previous test left this set; |
| 688 |
# it is unrelated to the bugs under test here. |
| 689 |
setcfg("settings.changed", 0) |
| 690 |
fixture_path = data_files[ |
| 691 |
"UP2516D #1 2022-03-20 02-08 D6500 2.2 F-S XYZLUT+MTX.cal" |
| 692 |
] |
| 693 |
# splitlines() (not split(b"\n")) so this is robust to Windows checkouts |
| 694 |
# where git's core.autocrlf normalizes this text fixture to CRLF, |
| 695 |
# otherwise a trailing "\r" on every line would break the exact-bytes |
| 696 |
# index() lookup below. |
| 697 |
lines = fixture_path.read_bytes().splitlines() |
| 698 |
data_format_index = lines.index(b"BEGIN_DATA_FORMAT") |
| 699 |
lines[data_format_index:data_format_index] = [ |
| 700 |
b'PATCH_SEQUENCE "MAXIMIZE_RGB_DIFFERENCE"', |
| 701 |
b'3DLUT_GAMUT_MAPPING_MODE "G"', |
| 702 |
] |
| 703 |
cal_path = tmp_path / fixture_path.name |
| 704 |
cal_path.write_bytes(b"\n".join(lines)) |
| 705 |
|
| 706 |
mainframe.load_cal_handler(None, path=str(cal_path)) |
| 707 |
|
| 708 |
# Defaults are "optimize_display_response_delay" / 1, so these values |
| 709 |
# only end up here if the block ran and decoded/compared correctly. |
| 710 |
assert getcfg("testchart.patch_sequence") == "maximize_RGB_difference" |
| 711 |
assert getcfg("3dlut.gamap.use_b2a") == 0 |