Debian Codegraph @

tests/test_config.py

raw
1 from enum import IntEnum
2 import configparser
3 import os
4 import sys
5 from unittest.mock import patch, MagicMock
6
7
8 import pytest
9 import sys
10 import builtins
11
12 import DisplayCAL.config as config
13
14
15 def test_default_values_1():
16 """Test default values of module level variables."""
17 from DisplayCAL import config
18
19 config.initcfg()
20
21 assert config.configparser.DEFAULTSECT == "Default"
22 assert config.EXE == sys.executable # venv/bin/python
23 assert config.EXEDIR == os.path.dirname(sys.executable) # venv/bin
24 assert config.EXENAME == os.path.basename(sys.executable) # python
25 assert config.ISEXE is False
26 # $HOME/.local/bin/pycharm-{PYCHARMVERSION}/plugins/python/helpers/pycharm/_jb_pytest_runner.py
27 assert config.PYFILE != ""
28 # $HOME/.local/bin/pycharm-{PYCHARMVERSION}/plugins/python/helpers/pycharm/_jb_pytest_runner.py
29 assert config.PYPATH != ""
30 assert config.ISAPP is False #
31 assert config.PYNAME != "" # _jb_pytest_runner
32 # assert config.pyext != "" # .py This is not valid when pytest runß directly
33 # $HOME/Documents/development/displaycal/DisplayCAL
34 assert config.PYDIR != ""
35
36 if sys.platform == "linux":
37 assert config.XDG_CONFIG_DIR_DEFAULT == "/etc/xdg"
38 assert config.XDG_CONFIG_HOME == os.path.expanduser("~/.config")
39 assert config.XDG_DATA_HOME == os.path.expanduser("~/.local/share")
40 assert config.XDG_DATA_HOME_DEFAULT == os.path.expanduser("~/.local/share")
41
42 # skip the rest of the test for now
43 return
44
45 assert config.XDG_DATA_DIRS == [
46 "/usr/share/pop",
47 os.path.expanduser("~/.local/share/flatpak/exports/share"),
48 "/var/lib/flatpak/exports/share",
49 "/usr/local/share",
50 "/usr/share",
51 "/var/lib",
52 ]
53
54 from DisplayCAL.meta import VERSION_STRING
55
56 expected_data_dirs = [
57 os.path.expanduser("~/.local/share/DisplayCAL"),
58 os.path.expanduser("~/.local/share/doc/DisplayCAL"),
59 os.path.expanduser(f"~/.local/share/doc/DisplayCAL-{VERSION_STRING}"),
60 os.path.expanduser("~/.local/share/doc/displaycal"),
61 os.path.expanduser("~/.local/share/doc/packages/DisplayCAL"),
62 os.path.expanduser("~/.local/share/flatpak/exports/share/DisplayCAL"),
63 os.path.expanduser("~/.local/share/flatpak/exports/share/doc/DisplayCAL"),
64 os.path.expanduser(
65 f"~/.local/share/flatpak/exports/share/doc/DisplayCAL-{VERSION_STRING}"
66 ),
67 os.path.expanduser("~/.local/share/flatpak/exports/share/doc/displaycal"),
68 os.path.expanduser(
69 "~/.local/share/flatpak/exports/share/doc/packages/DisplayCAL"
70 ),
71 os.path.expanduser("~/.local/share/flatpak/exports/share/icons/hicolor"),
72 os.path.expanduser("~/.local/share/icons/hicolor"),
73 config.PYDIR,
74 os.path.expanduser(
75 "~/PycharmProjects/DisplayCAL/venv/lib/python3.9/site-packages/DisplayCAL-3.8.9.3-py3.9-linux-x86_64.egg/DisplayCAL"
76 ),
77 "/usr/local/share/DisplayCAL",
78 "/usr/local/share/doc/DisplayCAL",
79 f"/usr/local/share/doc/DisplayCAL-{VERSION_STRING}",
80 "/usr/local/share/doc/displaycal",
81 "/usr/local/share/doc/packages/DisplayCAL",
82 "/usr/local/share/icons/hicolor",
83 "/usr/share/DisplayCAL",
84 "/usr/share/doc/DisplayCAL",
85 f"/usr/share/doc/DisplayCAL-{VERSION_STRING}",
86 "/usr/share/doc/displaycal",
87 "/usr/share/doc/packages/DisplayCAL",
88 "/usr/share/icons/hicolor",
89 "/usr/share/pop/DisplayCAL",
90 "/usr/share/pop/doc/DisplayCAL",
91 f"/usr/share/pop/doc/DisplayCAL-{VERSION_STRING}",
92 "/usr/share/pop/doc/displaycal",
93 "/usr/share/pop/doc/packages/DisplayCAL",
94 "/usr/share/pop/icons/hicolor",
95 "/var/lib/DisplayCAL",
96 "/var/lib/doc/DisplayCAL",
97 f"/var/lib/doc/DisplayCAL-{VERSION_STRING}",
98 "/var/lib/doc/displaycal",
99 "/var/lib/doc/packages/DisplayCAL",
100 "/var/lib/flatpak/exports/share/DisplayCAL",
101 "/var/lib/flatpak/exports/share/doc/DisplayCAL",
102 f"/var/lib/flatpak/exports/share/doc/DisplayCAL-{VERSION_STRING}",
103 "/var/lib/flatpak/exports/share/doc/displaycal",
104 "/var/lib/flatpak/exports/share/doc/packages/DisplayCAL",
105 "/var/lib/flatpak/exports/share/icons/hicolor",
106 "/var/lib/icons/hicolor",
107 ]
108 assert sorted(config.DATA_DIRS) == sorted(expected_data_dirs)
109
110
111 # get_hidpi_scaling_factor
112 @pytest.mark.parametrize(
113 "platform,expected", [
114 ("darwin", 1.0),
115 ("win32", 1.0),
116 ]
117 )
118 def test_get_hidpi_scaling_factor_mac_win(monkeypatch, platform, expected):
119 monkeypatch.setattr(sys, "platform", platform)
120 assert config.get_hidpi_scaling_factor() == expected
121
122
123 def test_get_hidpi_scaling_factor_xrdb(monkeypatch):
124 # Simulate Linux, xrdb present, Xft.dpi found
125 monkeypatch.setattr(sys, "platform", "linux")
126 # Patch which to return True for "xrdb"
127 monkeypatch.setattr("DisplayCAL.util_os.which", lambda name: name == "xrdb")
128 # Patch get_default_dpi to return 96
129 monkeypatch.setattr(config, "get_default_dpi", lambda: 96)
130 # Patch subprocess.Popen to simulate xrdb output
131 class DummyPopen:
132 def __init__(self, *a, **k): pass
133 def communicate(self):
134 return (b"Xft.dpi: 192\n", b"")
135 monkeypatch.setattr("subprocess.Popen", DummyPopen)
136 assert config.get_hidpi_scaling_factor() == 2.0
137
138
139 def test_get_hidpi_scaling_factor_xrdb_invalid(monkeypatch):
140 # Simulate Linux, xrdb present, Xft.dpi invalid
141 monkeypatch.setattr(sys, "platform", "linux")
142 monkeypatch.setattr("DisplayCAL.util_os.which", lambda name: name == "xrdb")
143 monkeypatch.setattr(config, "get_default_dpi", lambda: 96)
144 class DummyPopen:
145 def __init__(self, *a, **k): pass
146 def communicate(self):
147 return (b"Xft.dpi: notanumber\n", b"")
148 monkeypatch.setattr("subprocess.Popen", DummyPopen)
149 # Should fall through and return None
150 assert config.get_hidpi_scaling_factor() is None
151
152
153 def test_get_hidpi_scaling_factor_kde(monkeypatch):
154 # Simulate Linux, no xrdb, KDE desktop, QT_SCREEN_SCALE_FACTORS set
155 monkeypatch.setattr(sys, "platform", "linux")
156 monkeypatch.setattr("DisplayCAL.util_os.which", lambda name: False)
157 monkeypatch.setenv("XDG_CURRENT_DESKTOP", "KDE")
158 monkeypatch.setenv("QT_SCREEN_SCALE_FACTORS", "1.5;2.0")
159 # Patch wx and real_display_size_mm to avoid wx dependency
160 class DummyWx:
161 @staticmethod
162 def GetApp():
163 return None
164 monkeypatch.setitem(sys.modules, "DisplayCAL.wx_addons", type("mod", (), {"wx": DummyWx}))
165 # Should use first factor
166 assert config.get_hidpi_scaling_factor() == 1.5
167
168
169 def test_get_hidpi_scaling_factor_gnome(monkeypatch):
170 # Simulate Linux, no xrdb, not KDE, gsettings present
171 monkeypatch.setattr(sys, "platform", "linux")
172 monkeypatch.setattr("DisplayCAL.util_os.which", lambda name: name == "gsettings")
173 monkeypatch.setenv("XDG_CURRENT_DESKTOP", "GNOME")
174 # Patch subprocess.Popen to simulate gsettings output
175 class DummyPopen:
176 def __init__(self, *a, **k): pass
177 def communicate(self):
178 return (b"uint32 2", b"")
179 monkeypatch.setattr("subprocess.Popen", DummyPopen)
180 assert config.get_hidpi_scaling_factor() == 2.0
181
182
183 def test_get_hidpi_scaling_factor_none(monkeypatch):
184 # Simulate Linux, no xrdb, not KDE, no gsettings
185 monkeypatch.setattr(sys, "platform", "linux")
186 monkeypatch.setattr("DisplayCAL.util_os.which", lambda name: False)
187 monkeypatch.setenv("XDG_CURRENT_DESKTOP", "XFCE")
188 assert config.get_hidpi_scaling_factor() is None
189
190
191 # getcfg debug_print fix (#698)
192
193 def test_getcfg_no_debug_print_for_none_default(monkeypatch):
194 """debug_print must not fire when the fallback default value is None."""
195 monkeypatch.setattr(config, "DEBUG", True)
196 mock_debug_print = MagicMock()
197 monkeypatch.setattr(config, "debug_print", mock_debug_print)
198
199 fresh_cfg = config.CaseSensitiveConfigParser()
200 # "argyll.dir" has DEFAULTS["argyll.dir"] = None
201 config.getcfg("argyll.dir", fallback=True, cfg=fresh_cfg)
202
203 mock_debug_print.assert_not_called()
204
205
206 def test_getcfg_debug_print_called_for_non_none_default(monkeypatch):
207 """debug_print must fire when the fallback default value is not None."""
208 monkeypatch.setattr(config, "DEBUG", True)
209 mock_debug_print = MagicMock()
210 monkeypatch.setattr(config, "debug_print", mock_debug_print)
211
212 fresh_cfg = config.CaseSensitiveConfigParser()
213 # "calibration.ambient_viewcond_adjust" has DEFAULTS value of 0 (not None)
214 config.getcfg("calibration.ambient_viewcond_adjust", fallback=True, cfg=fresh_cfg)
215
216 mock_debug_print.assert_called_once()
217
218
219 # initcfg combined "if not module" block (#698)
220
221 def _make_ini(tmp_path: os.PathLike) -> None:
222 """Write a minimal DisplayCAL.ini so fetch_config_files finds it."""
223 ini = tmp_path / "DisplayCAL.ini"
224 ini.write_text("[Default]\n")
225
226
227 def test_initcfg_sets_lang_default(monkeypatch, tmp_path):
228 """initcfg() without a module sets lang when absent from config."""
229 _make_ini(tmp_path)
230 monkeypatch.setattr(config, "CONFIG_HOME", str(tmp_path))
231 monkeypatch.setattr(config, "CONFIG_SYS", str(tmp_path))
232
233 fresh_cfg = config.CaseSensitiveConfigParser()
234 config.initcfg(cfg=fresh_cfg)
235
236 assert fresh_cfg.get(configparser.DEFAULTSECT, "lang", fallback=None) is not None
237
238
239 def test_initcfg_sets_calibration_ambient_default(monkeypatch, tmp_path):
240 """initcfg() without a module sets calibration.ambient_viewcond_adjust when absent."""
241 _make_ini(tmp_path)
242 monkeypatch.setattr(config, "CONFIG_HOME", str(tmp_path))
243 monkeypatch.setattr(config, "CONFIG_SYS", str(tmp_path))
244
245 fresh_cfg = config.CaseSensitiveConfigParser()
246 config.initcfg(cfg=fresh_cfg)
247
248 value = fresh_cfg.get(
249 configparser.DEFAULTSECT, "calibration.ambient_viewcond_adjust", fallback=None
250 )
251 assert value == config.DEFAULTS["calibration.ambient_viewcond_adjust"]
252
253
254 def test_initcfg_sets_profile_save_path_default(monkeypatch, tmp_path):
255 """initcfg() without a module sets profile.save_path to STORAGE when absent."""
256 _make_ini(tmp_path)
257 monkeypatch.setattr(config, "CONFIG_HOME", str(tmp_path))
258 monkeypatch.setattr(config, "CONFIG_SYS", str(tmp_path))
259
260 fresh_cfg = config.CaseSensitiveConfigParser()
261 config.initcfg(cfg=fresh_cfg)
262
263 value = fresh_cfg.get(configparser.DEFAULTSECT, "profile.save_path", fallback=None)
264 assert value == config.STORAGE
265
266
267 def test_initcfg_module_skips_defaults(monkeypatch, tmp_path):
268 """initcfg() with a module arg must not touch the module-only defaults."""
269 ini = tmp_path / "DisplayCAL-apply-profiles.ini"
270 ini.write_text("[Default]\n")
271 monkeypatch.setattr(config, "CONFIG_HOME", str(tmp_path))
272
273 fresh_cfg = config.CaseSensitiveConfigParser()
274 mock_setcfg = MagicMock()
275 monkeypatch.setattr(config, "setcfg", mock_setcfg)
276
277 config.initcfg(module="apply-profiles", cfg=fresh_cfg)
278
279 set_keys = {call.args[0] for call in mock_setcfg.call_args_list}
280 assert "lang" not in set_keys
281 assert "calibration.ambient_viewcond_adjust" not in set_keys
282 assert "profile.save_path" not in set_keys
283
284
285 # writecfg atomicity/locking and oversized-config quarantine (#828)
286
287 def test_writecfg_writes_atomically_and_locks(monkeypatch, tmp_path):
288 """writecfg() must write via a locked temp file + atomic replace."""
289 monkeypatch.setattr(config, "CONFIG_HOME", str(tmp_path))
290
291 fresh_cfg = config.CaseSensitiveConfigParser()
292 fresh_cfg.add_section(config.configparser.DEFAULTSECT)
293 config.setcfg("lang", "en", cfg=fresh_cfg)
294
295 assert config.writecfg(cfg=fresh_cfg) is True
296
297 cfgfile = tmp_path / f"{config.APPBASENAME}.ini"
298 assert cfgfile.is_file()
299 assert "lang = en" in cfgfile.read_text()
300
301 # No leftover temp files from the atomic-replace step.
302 assert [p for p in tmp_path.iterdir() if p.suffix == ".tmp"] == []
303 # The lock file used to serialize concurrent writers must exist.
304 assert (tmp_path / f"{config.APPBASENAME}.ini.lock").is_file()
305
306
307 def test_writecfg_blocks_while_lock_held(monkeypatch, tmp_path):
308 """A concurrent writer must wait for the lock instead of interleaving."""
309 import threading
310 import time as time_module
311
312 monkeypatch.setattr(config, "CONFIG_HOME", str(tmp_path))
313 cfgfile = tmp_path / f"{config.APPBASENAME}.ini"
314 lockfilename = tmp_path / f"{config.APPBASENAME}.ini.lock"
315
316 fresh_cfg = config.CaseSensitiveConfigParser()
317 fresh_cfg.add_section(config.configparser.DEFAULTSECT)
318 config.setcfg("lang", "en", cfg=fresh_cfg)
319
320 # Hold the exclusive lock ourselves first, simulating a second process
321 # (e.g. the profile loader) already mid-write.
322 held_lockfile = open(lockfilename, "a+b")
323 lock = config.FileLock(held_lockfile, exclusive=True, blocking=True)
324
325 result = {}
326
327 def writer():
328 result["ok"] = config.writecfg(cfg=fresh_cfg)
329
330 t = threading.Thread(target=writer)
331 t.start()
332 time_module.sleep(0.2)
333 # writecfg() must still be blocked waiting for our lock.
334 assert t.is_alive()
335 assert not cfgfile.exists()
336
337 lock.unlock()
338 held_lockfile.close()
339 t.join(timeout=5)
340
341 assert not t.is_alive()
342 assert result.get("ok") is True
343 assert "lang = en" in cfgfile.read_text()
344
345
346 def test_initcfg_reads_ini_as_utf8(monkeypatch, tmp_path):
347 """initcfg() must decode the ini file as UTF-8 regardless of OS locale.
348
349 writecfg() always encodes as UTF-8 (str.encode() defaults to it
350 regardless of locale). If initcfg()'s cfg.read() ever again omits an
351 explicit encoding, Python falls back to the OS locale's preferred
352 encoding, which on Windows without the "Beta: UTF-8" system-locale
353 option is a legacy codepage (e.g. cp1252). That mismatch mis-decodes
354 non-ASCII option values on every read, and since writecfg() re-encodes
355 the already-garbled string as UTF-8 again, the mojibake compounds on
356 every read/write cycle (issue #828).
357 """
358 monkeypatch.setattr(config, "CONFIG_HOME", str(tmp_path))
359 monkeypatch.setattr(config, "CONFIG_SYS", str(tmp_path))
360
361 value = "C:\\Users\\Foo\\target 110cdm² gamma 2.2.cal"
362 ini = tmp_path / "DisplayCAL.ini"
363 ini.write_bytes(f"[Default]\nlast_cal_path = {value}\n".encode())
364
365 fresh_cfg = config.CaseSensitiveConfigParser()
366 with patch.object(fresh_cfg, "read", wraps=fresh_cfg.read) as mock_read:
367 config.initcfg(cfg=fresh_cfg)
368 assert mock_read.call_args.kwargs.get("encoding") == "utf-8"
369
370 assert (
371 fresh_cfg.get(configparser.DEFAULTSECT, "last_cal_path", fallback=None)
372 == value
373 )
374
375
376 def test_fetch_config_files_quarantines_oversized_file(monkeypatch, tmp_path):
377 """A pathologically large config file must be quarantined, not parsed."""
378 monkeypatch.setattr(config, "MAX_CFG_FILE_SIZE", 64)
379 cfgfile = tmp_path / "DisplayCAL.ini"
380 cfgfile.write_text("[Default]\nlast_icc_path = " + ("x" * 200) + "\n")
381
382 cfgfiles = config.fetch_config_files(["DisplayCAL"], [str(tmp_path)])
383
384 assert cfgfiles == []
385 assert not cfgfile.exists()
386 quarantined = list(tmp_path.glob("DisplayCAL.ini.corrupt-*"))
387 assert len(quarantined) == 1
388
389
390 def test_fetch_config_files_loads_normal_sized_file(monkeypatch, tmp_path):
391 """A normal-sized config file must load as before."""
392 monkeypatch.setattr(config, "MAX_CFG_FILE_SIZE", 10 * 1024 * 1024)
393 cfgfile = tmp_path / "DisplayCAL.ini"
394 cfgfile.write_text("[Default]\nlang = en\n")
395
396 cfgfiles = config.fetch_config_files(["DisplayCAL"], [str(tmp_path)])
397
398 assert cfgfiles == [str(cfgfile)]
399 assert cfgfile.exists()
400