Skip to content

Commit aed428d

Browse files
committed
Add tests that check runtime qt environment selection code
1 parent 5a99f46 commit aed428d

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

tests/test_environment.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
"""
2+
BSD License
3+
"""
4+
5+
import importlib
6+
import sys
7+
import types
8+
9+
import pytest
10+
from pytest import MonkeyPatch
11+
12+
from qasync import QT_ALL, _get_qt_flavor
13+
14+
15+
def _purge_qt(mp: MonkeyPatch):
16+
"""Ensure no Qt modules are loaded."""
17+
for name in QT_ALL:
18+
mp.delitem(sys.modules, name, raising=False)
19+
20+
21+
def _stub_import(mp: MonkeyPatch, available=()):
22+
"""Patch importlib.import_module to only 'exist' for certain modules."""
23+
24+
def fake_import(name):
25+
if name in available:
26+
return types.ModuleType(name)
27+
raise ImportError
28+
29+
mp.setattr(importlib, "import_module", fake_import)
30+
31+
32+
def test_env_exact():
33+
with MonkeyPatch.context() as mp:
34+
_purge_qt(mp)
35+
_stub_import(mp)
36+
mp.setenv("QT_API", "PySide6")
37+
assert _get_qt_flavor() == "PySide6"
38+
39+
40+
def test_env_invalid_raises():
41+
with MonkeyPatch.context() as mp:
42+
_purge_qt(mp)
43+
_stub_import(mp)
44+
mp.setenv("QT_API", "QT")
45+
with pytest.raises(ImportError):
46+
_get_qt_flavor()
47+
48+
49+
def test_already_imported_precedence():
50+
with MonkeyPatch.context() as mp:
51+
_purge_qt(mp)
52+
_stub_import(mp)
53+
mp.delenv("QT_API", raising=False)
54+
mp.setitem(sys.modules, "PySide2", types.ModuleType("PySide2"))
55+
mp.setitem(sys.modules, "PyQt5", types.ModuleType("PyQt5"))
56+
assert _get_qt_flavor() == next(n for n in QT_ALL if n in ("PyQt5", "PySide2"))
57+
58+
59+
def test_first_available_import():
60+
with MonkeyPatch.context() as mp:
61+
_purge_qt(mp)
62+
_stub_import(mp, available=("PySide6",))
63+
mp.delenv("QT_API", raising=False)
64+
assert _get_qt_flavor() == "PySide6"
65+
66+
67+
def test_none_available_raises():
68+
with MonkeyPatch.context() as mp:
69+
_purge_qt(mp)
70+
_stub_import(mp)
71+
mp.delenv("QT_API", raising=False)
72+
with pytest.raises(ImportError):
73+
_get_qt_flavor()
74+
75+
76+
def test_env_overrides_imported():
77+
with MonkeyPatch.context() as mp:
78+
_purge_qt(mp)
79+
_stub_import(mp)
80+
mp.setitem(sys.modules, "PyQt6", types.ModuleType("PyQt6"))
81+
mp.setenv("QT_API", "PySide2")
82+
assert _get_qt_flavor() == "PySide2"

0 commit comments

Comments
 (0)