Use a pytest marker to fake an OS

This commit is contained in:
Florian Bruhin 2017-09-20 11:28:19 +02:00
parent ef1c83862b
commit 46cfd5353d
7 changed files with 47 additions and 19 deletions

View File

@ -25,6 +25,7 @@ markers =
this: Used to mark tests during development this: Used to mark tests during development
no_invalid_lines: Don't fail on unparseable lines in end2end tests no_invalid_lines: Don't fail on unparseable lines in end2end tests
issue2478: Tests which are broken on Windows with QtWebEngine, https://github.com/qutebrowser/qutebrowser/issues/2478 issue2478: Tests which are broken on Windows with QtWebEngine, https://github.com/qutebrowser/qutebrowser/issues/2478
fake_os: Fake utils.is_* to a fake operating system
qt_log_level_fail = WARNING qt_log_level_fail = WARNING
qt_log_ignore = qt_log_ignore =
^SpellCheck: .* ^SpellCheck: .*

View File

@ -193,6 +193,37 @@ def set_backend(monkeypatch, request):
monkeypatch.setattr(objects, 'backend', backend) monkeypatch.setattr(objects, 'backend', backend)
@pytest.fixture(autouse=True)
def apply_fake_os(monkeypatch, request):
fake_os = request.node.get_marker('fake_os')
if not fake_os:
return
name = fake_os.args[0]
mac = False
windows = False
linux = False
posix = False
if name == 'unknown':
pass
elif name == 'mac':
mac = True
posix = True
elif name == 'windows':
windows = True
elif name == 'linux':
linux = True
posix = True
else:
raise ValueError("Invalid fake_os {}".format(name))
monkeypatch.setattr('qutebrowser.utils.utils.is_mac', mac)
monkeypatch.setattr('qutebrowser.utils.utils.is_linux', linux)
monkeypatch.setattr('qutebrowser.utils.utils.is_windows', windows)
monkeypatch.setattr('qutebrowser.utils.utils.is_posix', posix)
@pytest.hookimpl(tryfirst=True, hookwrapper=True) @pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call): def pytest_runtest_makereport(item, call):
"""Make test information available in fixtures. """Make test information available in fixtures.

View File

@ -246,9 +246,8 @@ def test_unicode_error(caplog, qtbot, py_proc, runner):
assert caplog.records[0].message == expected assert caplog.records[0].message == expected
def test_unsupported(monkeypatch, tabbed_browser_stubs): @pytest.mark.fake_os('unknown')
monkeypatch.setattr(userscripts.utils, 'is_posix', False) def test_unsupported(tabbed_browser_stubs):
monkeypatch.setattr(userscripts.utils, 'is_windows', False)
with pytest.raises(userscripts.UnsupportedError, match="Userscripts are " with pytest.raises(userscripts.UnsupportedError, match="Userscripts are "
"not supported on this platform!"): "not supported on this platform!"):
userscripts.run_async(tab=None, cmd=None, win_id=0, env=None) userscripts.run_async(tab=None, cmd=None, win_id=0, env=None)

View File

@ -207,8 +207,8 @@ def test_skipped_args(covtest, args, reason):
covtest.check_skipped(args, reason) covtest.check_skipped(args, reason)
def test_skipped_non_linux(covtest, monkeypatch): @pytest.mark.fake_os('windows')
monkeypatch.setattr(check_coverage.utils, 'is_linux', False) def test_skipped_non_linux(covtest):
covtest.check_skipped([], "on non-Linux system.") covtest.check_skipped([], "on non-Linux system.")

View File

@ -78,9 +78,9 @@ def test_unset_organization_no_qapp(monkeypatch):
pass pass
@pytest.mark.fake_os('mac')
def test_fake_mac_config(tmpdir, monkeypatch): def test_fake_mac_config(tmpdir, monkeypatch):
"""Test standardir.config on a fake Mac.""" """Test standardir.config on a fake Mac."""
monkeypatch.setattr(utils, 'is_mac', True)
monkeypatch.setenv('HOME', str(tmpdir)) monkeypatch.setenv('HOME', str(tmpdir))
expected = str(tmpdir) + '/.qute_test' # always with / expected = str(tmpdir) + '/.qute_test' # always with /
standarddir._init_config(args=None) standarddir._init_config(args=None)
@ -89,9 +89,9 @@ def test_fake_mac_config(tmpdir, monkeypatch):
@pytest.mark.parametrize('what', ['data', 'config', 'cache']) @pytest.mark.parametrize('what', ['data', 'config', 'cache'])
@pytest.mark.not_mac @pytest.mark.not_mac
@pytest.mark.fake_os('windows')
def test_fake_windows(tmpdir, monkeypatch, what): def test_fake_windows(tmpdir, monkeypatch, what):
"""Make sure the config/data/cache dirs are correct on a fake Windows.""" """Make sure the config/data/cache dirs are correct on a fake Windows."""
monkeypatch.setattr(standarddir.utils, 'is_windows', True)
monkeypatch.setattr(standarddir.QStandardPaths, 'writableLocation', monkeypatch.setattr(standarddir.QStandardPaths, 'writableLocation',
lambda typ: str(tmpdir / APPNAME)) lambda typ: str(tmpdir / APPNAME))
@ -173,9 +173,9 @@ class TestStandardDir:
standarddir._init_dirs() standarddir._init_dirs()
assert standarddir.runtime() == str(tmpdir / 'temp' / APPNAME) assert standarddir.runtime() == str(tmpdir / 'temp' / APPNAME)
@pytest.mark.fake_os('windows')
def test_runtimedir_empty_tempdir(self, monkeypatch, tmpdir): def test_runtimedir_empty_tempdir(self, monkeypatch, tmpdir):
"""With an empty tempdir on non-Linux, we should raise.""" """With an empty tempdir on non-Linux, we should raise."""
monkeypatch.setattr(standarddir.utils, 'is_linux', False)
monkeypatch.setattr(standarddir.QStandardPaths, 'writableLocation', monkeypatch.setattr(standarddir.QStandardPaths, 'writableLocation',
lambda typ: '') lambda typ: '')
with pytest.raises(standarddir.EmptyValueError): with pytest.raises(standarddir.EmptyValueError):
@ -324,9 +324,9 @@ class TestSystemData:
"""Test system data path.""" """Test system data path."""
@pytest.mark.fake_os('linux')
def test_system_datadir_exist_linux(self, monkeypatch): def test_system_datadir_exist_linux(self, monkeypatch):
"""Test that /usr/share/qute_test is used if path exists.""" """Test that /usr/share/qute_test is used if path exists."""
monkeypatch.setattr(standarddir.utils, 'is_linux', True)
monkeypatch.setattr(os.path, 'exists', lambda path: True) monkeypatch.setattr(os.path, 'exists', lambda path: True)
standarddir._init_dirs() standarddir._init_dirs()
assert standarddir.data(system=True) == "/usr/share/qute_test" assert standarddir.data(system=True) == "/usr/share/qute_test"

View File

@ -365,9 +365,9 @@ class TestKeyEventToString:
Qt.MetaModifier | Qt.ShiftModifier)) Qt.MetaModifier | Qt.ShiftModifier))
assert utils.keyevent_to_string(evt) == 'ctrl+alt+meta+shift+a' assert utils.keyevent_to_string(evt) == 'ctrl+alt+meta+shift+a'
def test_mac(self, monkeypatch, fake_keyevent_factory): @pytest.mark.fake_os('mac')
def test_mac(self, fake_keyevent_factory):
"""Test with a simulated mac.""" """Test with a simulated mac."""
monkeypatch.setattr(utils, 'is_mac', True)
evt = fake_keyevent_factory(key=Qt.Key_A, modifiers=Qt.ControlModifier) evt = fake_keyevent_factory(key=Qt.Key_A, modifiers=Qt.ControlModifier)
assert utils.keyevent_to_string(evt) == 'meta+a' assert utils.keyevent_to_string(evt) == 'meta+a'

View File

@ -662,12 +662,12 @@ class TestOsInfo:
"""Tests for _os_info.""" """Tests for _os_info."""
@pytest.mark.fake_os('linux')
def test_linux_fake(self, monkeypatch): def test_linux_fake(self, monkeypatch):
"""Test with a fake Linux. """Test with a fake Linux.
No args because osver is set to '' if the OS is linux. No args because osver is set to '' if the OS is linux.
""" """
monkeypatch.setattr(version.sys, 'platform', 'linux')
monkeypatch.setattr(version, '_release_info', monkeypatch.setattr(version, '_release_info',
lambda: [('releaseinfo', 'Hello World')]) lambda: [('releaseinfo', 'Hello World')])
ret = version._os_info() ret = version._os_info()
@ -675,15 +675,16 @@ class TestOsInfo:
'--- releaseinfo ---', 'Hello World'] '--- releaseinfo ---', 'Hello World']
assert ret == expected assert ret == expected
@pytest.mark.fake_os('windows')
def test_windows_fake(self, monkeypatch): def test_windows_fake(self, monkeypatch):
"""Test with a fake Windows.""" """Test with a fake Windows."""
monkeypatch.setattr(version.sys, 'platform', 'win32')
monkeypatch.setattr(version.platform, 'win32_ver', monkeypatch.setattr(version.platform, 'win32_ver',
lambda: ('eggs', 'bacon', 'ham', 'spam')) lambda: ('eggs', 'bacon', 'ham', 'spam'))
ret = version._os_info() ret = version._os_info()
expected = ['OS Version: eggs, bacon, ham, spam'] expected = ['OS Version: eggs, bacon, ham, spam']
assert ret == expected assert ret == expected
@pytest.mark.fake_os('mac')
@pytest.mark.parametrize('mac_ver, mac_ver_str', [ @pytest.mark.parametrize('mac_ver, mac_ver_str', [
(('x', ('', '', ''), 'y'), 'x, y'), (('x', ('', '', ''), 'y'), 'x, y'),
(('', ('', '', ''), ''), ''), (('', ('', '', ''), ''), ''),
@ -696,18 +697,14 @@ class TestOsInfo:
mac_ver: The tuple to set platform.mac_ver() to. mac_ver: The tuple to set platform.mac_ver() to.
mac_ver_str: The expected Mac version string in version._os_info(). mac_ver_str: The expected Mac version string in version._os_info().
""" """
monkeypatch.setattr(version.utils, 'is_linux', False)
monkeypatch.setattr(version.utils, 'is_windows', False)
monkeypatch.setattr(version.utils, 'is_mac', True)
monkeypatch.setattr(version.platform, 'mac_ver', lambda: mac_ver) monkeypatch.setattr(version.platform, 'mac_ver', lambda: mac_ver)
ret = version._os_info() ret = version._os_info()
expected = ['OS Version: {}'.format(mac_ver_str)] expected = ['OS Version: {}'.format(mac_ver_str)]
assert ret == expected assert ret == expected
def test_unknown_fake(self, monkeypatch): @pytest.mark.fake_os('unknown')
def test_unknown_fake(self):
"""Test with a fake unknown platform.""" """Test with a fake unknown platform."""
for name in ['is_mac', 'is_windows', 'is_linux']:
monkeypatch.setattr(version.utils, name, False)
ret = version._os_info() ret = version._os_info()
expected = ['OS Version: ?'] expected = ['OS Version: ?']
assert ret == expected assert ret == expected