Use three-argument form of monkeypatch.*attr

This commit is contained in:
Florian Bruhin 2017-03-01 11:33:41 +01:00
parent 1e42fd1319
commit ca4f249c30
18 changed files with 67 additions and 96 deletions

View File

@ -39,7 +39,7 @@ import py.path # pylint: disable=no-name-in-module
import helpers.stubs as stubsmod import helpers.stubs as stubsmod
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.utils import objreg from qutebrowser.utils import objreg, standarddir
from qutebrowser.browser.webkit import cookies from qutebrowser.browser.webkit import cookies
from qutebrowser.misc import savemanager from qutebrowser.misc import savemanager
from qutebrowser.keyinput import modeman from qutebrowser.keyinput import modeman
@ -446,7 +446,7 @@ def config_tmpdir(monkeypatch, tmpdir):
confdir = tmpdir / 'config' confdir = tmpdir / 'config'
path = str(confdir) path = str(confdir)
os.mkdir(path) os.mkdir(path)
monkeypatch.setattr('qutebrowser.utils.standarddir.config', lambda: path) monkeypatch.setattr(standarddir, 'config', lambda: path)
return confdir return confdir
@ -459,7 +459,7 @@ def data_tmpdir(monkeypatch, tmpdir):
datadir = tmpdir / 'data' datadir = tmpdir / 'data'
path = str(datadir) path = str(datadir)
os.mkdir(path) os.mkdir(path)
monkeypatch.setattr('qutebrowser.utils.standarddir.data', lambda: path) monkeypatch.setattr(standarddir, 'data', lambda: path)
return datadir return datadir

View File

@ -154,7 +154,7 @@ class TestDirbrowserHtml:
def test_icons(self, monkeypatch): def test_icons(self, monkeypatch):
"""Make sure icon paths are correct file:// URLs.""" """Make sure icon paths are correct file:// URLs."""
monkeypatch.setattr('qutebrowser.utils.jinja.utils.resource_filename', monkeypatch.setattr(filescheme.jinja.utils, 'resource_filename',
lambda name: '/test path/foo.svg') lambda name: '/test path/foo.svg')
html = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8') html = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8')

View File

@ -39,8 +39,7 @@ class TestPDFJSHandler:
return b'foobar' return b'foobar'
raise pdfjs.PDFJSNotFound(path) raise pdfjs.PDFJSNotFound(path)
monkeypatch.setattr('qutebrowser.browser.pdfjs.get_pdfjs_res', monkeypatch.setattr(pdfjs, 'get_pdfjs_res', get_pdfjs_res)
get_pdfjs_res)
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def patch_backend(self, monkeypatch): def patch_backend(self, monkeypatch):

View File

@ -672,8 +672,7 @@ class TestRectOnView:
This is needed for all the tests calling rect_on_view or is_visible. This is needed for all the tests calling rect_on_view or is_visible.
""" """
config_stub.data = {'ui': {'zoom-text-only': 'true'}} config_stub.data = {'ui': {'zoom-text-only': 'true'}}
monkeypatch.setattr('qutebrowser.browser.webkit.webkitelem.config', monkeypatch.setattr(webkitelem, 'config', config_stub)
config_stub)
return config_stub return config_stub
@pytest.mark.parametrize('js_rect', [ @pytest.mark.parametrize('js_rect', [
@ -800,8 +799,7 @@ class TestIsEditable:
def stubbed_config(self, config_stub, monkeypatch): def stubbed_config(self, config_stub, monkeypatch):
"""Fixture to create a config stub with an input section.""" """Fixture to create a config stub with an input section."""
config_stub.data = {'input': {}} config_stub.data = {'input': {}}
monkeypatch.setattr('qutebrowser.browser.webkit.webkitelem.config', monkeypatch.setattr(webkitelem, 'config', config_stub)
config_stub)
return config_stub return config_stub
@pytest.mark.parametrize('tagname, attributes, editable', [ @pytest.mark.parametrize('tagname, attributes, editable', [

View File

@ -64,8 +64,7 @@ def completion_widget_stub():
def completer_obj(qtbot, status_command_stub, config_stub, monkeypatch, stubs, def completer_obj(qtbot, status_command_stub, config_stub, monkeypatch, stubs,
completion_widget_stub): completion_widget_stub):
"""Create the completer used for testing.""" """Create the completer used for testing."""
monkeypatch.setattr('qutebrowser.completion.completer.QTimer', monkeypatch.setattr(completer, 'QTimer', stubs.InstaTimer)
stubs.InstaTimer)
config_stub.data = {'completion': {'show': 'auto'}} config_stub.data = {'completion': {'show': 'auto'}}
return completer.Completer(status_command_stub, 0, completion_widget_stub) return completer.Completer(status_command_stub, 0, completion_widget_stub)
@ -85,8 +84,7 @@ def instances(monkeypatch):
'editor': FakeCompletionModel(usertypes.Completion.value), 'editor': FakeCompletionModel(usertypes.Completion.value),
} }
} }
monkeypatch.setattr('qutebrowser.completion.completer.instances', monkeypatch.setattr(completer, 'instances', instances)
instances)
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@ -129,7 +127,7 @@ def cmdutils_patch(monkeypatch, stubs):
'bind': command.Command(name='bind', handler=bind), 'bind': command.Command(name='bind', handler=bind),
'tab-detach': command.Command(name='tab-detach', handler=tab_detach), 'tab-detach': command.Command(name='tab-detach', handler=tab_detach),
}) })
monkeypatch.setattr('qutebrowser.completion.completer.cmdutils', cmd_utils) monkeypatch.setattr(completer, 'cmdutils', cmd_utils)
def _set_cmd_prompt(cmd, txt): def _set_cmd_prompt(cmd, txt):

View File

@ -796,8 +796,7 @@ class TestCommand:
cmd_utils = stubs.FakeCmdUtils({ cmd_utils = stubs.FakeCmdUtils({
'cmd1': stubs.FakeCommand(desc="desc 1"), 'cmd1': stubs.FakeCommand(desc="desc 1"),
'cmd2': stubs.FakeCommand(desc="desc 2")}) 'cmd2': stubs.FakeCommand(desc="desc 2")})
monkeypatch.setattr('qutebrowser.config.configtypes.cmdutils', monkeypatch.setattr(configtypes, 'cmdutils', cmd_utils)
cmd_utils)
@pytest.fixture @pytest.fixture
def klass(self): def klass(self):

View File

@ -46,8 +46,7 @@ class TestsNormalKeyParser:
'qutebrowser.keyinput.basekeyparser.usertypes.Timer', 'qutebrowser.keyinput.basekeyparser.usertypes.Timer',
stubs.FakeTimer) stubs.FakeTimer)
config_stub.data = CONFIG config_stub.data = CONFIG
monkeypatch.setattr('qutebrowser.keyinput.modeparsers.config', monkeypatch.setattr(modeparsers, 'config', config_stub)
config_stub)
@pytest.fixture @pytest.fixture
def keyparser(self): def keyparser(self):

View File

@ -58,12 +58,10 @@ def test_normal(capfd):
def test_patched_no_errwindow(capfd, monkeypatch): def test_patched_no_errwindow(capfd, monkeypatch):
"""Test with a patched sys.hexversion and --no-err-windows.""" """Test with a patched sys.hexversion and --no-err-windows."""
monkeypatch.setattr('qutebrowser.misc.checkpyver.sys.argv', monkeypatch.setattr(checkpyver.sys, 'argv',
[sys.argv[0], '--no-err-windows']) [sys.argv[0], '--no-err-windows'])
monkeypatch.setattr('qutebrowser.misc.checkpyver.sys.hexversion', monkeypatch.setattr(checkpyver.sys, 'hexversion', 0x03000000)
0x03000000) monkeypatch.setattr(checkpyver.sys, 'exit', lambda status: None)
monkeypatch.setattr('qutebrowser.misc.checkpyver.sys.exit',
lambda status: None)
checkpyver.check_python_version() checkpyver.check_python_version()
stdout, stderr = capfd.readouterr() stdout, stderr = capfd.readouterr()
assert not stdout assert not stdout
@ -72,10 +70,8 @@ def test_patched_no_errwindow(capfd, monkeypatch):
def test_patched_errwindow(capfd, mocker, monkeypatch): def test_patched_errwindow(capfd, mocker, monkeypatch):
"""Test with a patched sys.hexversion and a fake Tk.""" """Test with a patched sys.hexversion and a fake Tk."""
monkeypatch.setattr('qutebrowser.misc.checkpyver.sys.hexversion', monkeypatch.setattr(checkpyver.sys, 'hexversion', 0x03000000)
0x03000000) monkeypatch.setattr(checkpyver.sys, 'exit', lambda status: None)
monkeypatch.setattr('qutebrowser.misc.checkpyver.sys.exit',
lambda status: None)
try: try:
import tkinter # pylint: disable=unused-variable import tkinter # pylint: disable=unused-variable

View File

@ -33,13 +33,13 @@ from qutebrowser.utils import usertypes
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def patch_things(config_stub, monkeypatch, stubs): def patch_things(config_stub, monkeypatch, stubs):
monkeypatch.setattr('qutebrowser.misc.editor.guiprocess.QProcess', monkeypatch.setattr(editormod.guiprocess, 'QProcess',
stubs.fake_qprocess()) stubs.fake_qprocess())
config_stub.data = { config_stub.data = {
'general': {'editor': [''], 'editor-encoding': 'utf-8'}, 'general': {'editor': [''], 'editor-encoding': 'utf-8'},
'input': {}, 'input': {},
} }
monkeypatch.setattr('qutebrowser.misc.editor.config', config_stub) monkeypatch.setattr(editormod, 'config', config_stub)
@pytest.fixture @pytest.fixture
@ -141,8 +141,7 @@ class TestFileHandling:
caplog): caplog):
"""Test file handling when the initial file is not writable.""" """Test file handling when the initial file is not writable."""
tmpdir.chmod(0) tmpdir.chmod(0)
monkeypatch.setattr('qutebrowser.misc.editor.tempfile.tempdir', monkeypatch.setattr(editormod.tempfile, 'tempdir', str(tmpdir))
str(tmpdir))
with caplog.at_level(logging.ERROR): with caplog.at_level(logging.ERROR):
editor.edit("") editor.edit("")

View File

@ -199,8 +199,7 @@ class TestSocketName:
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def patch_user(self, monkeypatch): def patch_user(self, monkeypatch):
monkeypatch.setattr('qutebrowser.misc.ipc.getpass.getuser', monkeypatch.setattr(ipc.getpass, 'getuser', lambda: 'testusername')
lambda: 'testusername')
@pytest.mark.parametrize('basedir, expected', LEGACY_TESTS) @pytest.mark.parametrize('basedir, expected', LEGACY_TESTS)
def test_legacy(self, basedir, expected): def test_legacy(self, basedir, expected):
@ -281,7 +280,7 @@ class TestListen:
def test_error(self, ipc_server, monkeypatch): def test_error(self, ipc_server, monkeypatch):
"""Simulate an error while listening.""" """Simulate an error while listening."""
monkeypatch.setattr('qutebrowser.misc.ipc.QLocalServer.removeServer', monkeypatch.setattr(ipc.QLocalServer, 'removeServer',
lambda self: True) lambda self: True)
monkeypatch.setattr(ipc_server, '_socketname', None) monkeypatch.setattr(ipc_server, '_socketname', None)
with pytest.raises(ipc.ListenError): with pytest.raises(ipc.ListenError):
@ -289,7 +288,7 @@ class TestListen:
@pytest.mark.posix @pytest.mark.posix
def test_in_use(self, qlocalserver, ipc_server, monkeypatch): def test_in_use(self, qlocalserver, ipc_server, monkeypatch):
monkeypatch.setattr('qutebrowser.misc.ipc.QLocalServer.removeServer', monkeypatch.setattr(ipc.QLocalServer, 'removeServer',
lambda self: True) lambda self: True)
qlocalserver.listen('qute-test') qlocalserver.listen('qute-test')
with pytest.raises(ipc.AddressInUseError): with pytest.raises(ipc.AddressInUseError):
@ -834,8 +833,7 @@ def test_long_username(monkeypatch):
"""See https://github.com/qutebrowser/qutebrowser/issues/888.""" """See https://github.com/qutebrowser/qutebrowser/issues/888."""
username = 'alexandercogneau' username = 'alexandercogneau'
basedir = '/this_is_a_long_basedir' basedir = '/this_is_a_long_basedir'
monkeypatch.setattr('qutebrowser.misc.ipc.standarddir.getpass.getuser', monkeypatch.setattr(ipc.standarddir.getpass, 'getuser', lambda: username)
lambda: username)
name = ipc._get_socketname(basedir=basedir) name = ipc._get_socketname(basedir=basedir)
server = ipc.IPCServer(name) server = ipc.IPCServer(name)
expected_md5 = md5('{}-{}'.format(username, basedir)) expected_md5 = md5('{}-{}'.format(username, basedir))

View File

@ -54,8 +54,7 @@ class TestInit:
@pytest.mark.parametrize('create_dir', [True, False]) @pytest.mark.parametrize('create_dir', [True, False])
def test_with_standarddir(self, tmpdir, monkeypatch, create_dir): def test_with_standarddir(self, tmpdir, monkeypatch, create_dir):
monkeypatch.setattr('qutebrowser.misc.sessions.standarddir.data', monkeypatch.setattr(sessions.standarddir, 'data', lambda: str(tmpdir))
lambda: str(tmpdir))
session_dir = tmpdir / 'sessions' session_dir = tmpdir / 'sessions'
if create_dir: if create_dir:
session_dir.ensure(dir=True) session_dir.ensure(dir=True)
@ -181,7 +180,7 @@ class TestSaveAll:
def test_no_active_window(self, sess_man, fake_window, stubs, def test_no_active_window(self, sess_man, fake_window, stubs,
monkeypatch): monkeypatch):
qapp = stubs.FakeQApplication(active_window=None) qapp = stubs.FakeQApplication(active_window=None)
monkeypatch.setattr('qutebrowser.misc.sessions.QApplication', qapp) monkeypatch.setattr(sessions, 'QApplication', qapp)
sess_man._save_all() sess_man._save_all()
@ -216,7 +215,7 @@ class TestSave:
objreg.register('tabbed-browser', browser, scope='window', window=0) objreg.register('tabbed-browser', browser, scope='window', window=0)
qapp = stubs.FakeQApplication(active_window=win) qapp = stubs.FakeQApplication(active_window=win)
monkeypatch.setattr('qutebrowser.misc.sessions.QApplication', qapp) monkeypatch.setattr(sessions, 'QApplication', qapp)
def set_data(items): def set_data(items):
history = browser.widgets()[0].page().history() history = browser.widgets()[0].page().history()

View File

@ -63,7 +63,7 @@ class CovtestHelper:
perfect_files = [(None, 'module.py')] perfect_files = [(None, 'module.py')]
argv = [sys.argv[0]] argv = [sys.argv[0]]
self._monkeypatch.setattr('scripts.dev.check_coverage.sys.argv', argv) self._monkeypatch.setattr(check_coverage.sys, 'argv', argv)
with self._testdir.tmpdir.as_cwd(): with self._testdir.tmpdir.as_cwd():
with coverage_file.open(encoding='utf-8') as f: with coverage_file.open(encoding='utf-8') as f:
@ -72,7 +72,7 @@ class CovtestHelper:
def check_skipped(self, args, reason): def check_skipped(self, args, reason):
"""Run check_coverage.py and make sure it's skipped.""" """Run check_coverage.py and make sure it's skipped."""
argv = [sys.argv[0]] + list(args) argv = [sys.argv[0]] + list(args)
self._monkeypatch.setattr('scripts.dev.check_coverage.sys.argv', argv) self._monkeypatch.setattr(check_coverage.sys, 'argv', argv)
with pytest.raises(check_coverage.Skipped) as excinfo: with pytest.raises(check_coverage.Skipped) as excinfo:
return check_coverage.check(None, perfect_files=[]) return check_coverage.check(None, perfect_files=[])
assert excinfo.value.reason == reason assert excinfo.value.reason == reason
@ -179,7 +179,7 @@ def test_skipped_args(covtest, args, reason):
def test_skipped_windows(covtest, monkeypatch): def test_skipped_windows(covtest, monkeypatch):
monkeypatch.setattr('scripts.dev.check_coverage.sys.platform', 'toaster') monkeypatch.setattr(check_coverage.sys, 'platform', 'toaster')
covtest.check_skipped([], "on non-Linux system.") covtest.check_skipped([], "on non-Linux system.")

View File

@ -66,9 +66,8 @@ def patch_read_file(monkeypatch):
else: else:
raise IOError("Invalid path {}!".format(path)) raise IOError("Invalid path {}!".format(path))
monkeypatch.setattr('qutebrowser.utils.jinja.utils.read_file', _read_file) monkeypatch.setattr(jinja.utils, 'read_file', _read_file)
monkeypatch.setattr('qutebrowser.utils.jinja.utils.resource_filename', monkeypatch.setattr(jinja.utils, 'resource_filename', _resource_filename)
_resource_filename)
def test_simple_template(): def test_simple_template():

View File

@ -64,7 +64,7 @@ def test_version_check(monkeypatch, qversion, compiled, version, op, expected):
op: The operator to use when comparing. op: The operator to use when comparing.
expected: The expected result. expected: The expected result.
""" """
monkeypatch.setattr('qutebrowser.utils.qtutils.qVersion', lambda: qversion) monkeypatch.setattr(qtutils, 'qVersion', lambda: qversion)
if compiled is not None: if compiled is not None:
monkeypatch.setattr(qtutils, 'QT_VERSION_STR', compiled) monkeypatch.setattr(qtutils, 'QT_VERSION_STR', compiled)
strict = True strict = True
@ -169,8 +169,8 @@ def test_check_print_compat(os_name, qversion, expected, monkeypatch):
qversion: The fake qVersion() to set. qversion: The fake qVersion() to set.
expected: The expected return value. expected: The expected return value.
""" """
monkeypatch.setattr('qutebrowser.utils.qtutils.os.name', os_name) monkeypatch.setattr(qtutils.os, 'name', os_name)
monkeypatch.setattr('qutebrowser.utils.qtutils.qVersion', lambda: qversion) monkeypatch.setattr(qtutils, 'qVersion', lambda: qversion)
assert qtutils.check_print_compat() == expected assert qtutils.check_print_compat() == expected

View File

@ -48,8 +48,7 @@ def change_qapp_name(qapp):
@pytest.fixture @pytest.fixture
def no_cachedir_tag(monkeypatch): def no_cachedir_tag(monkeypatch):
"""Fixture to prevent writing a CACHEDIR.TAG.""" """Fixture to prevent writing a CACHEDIR.TAG."""
monkeypatch.setattr('qutebrowser.utils.standarddir._init_cachedir_tag', monkeypatch.setattr(standarddir, '_init_cachedir_tag', lambda: None)
lambda: None)
@pytest.fixture @pytest.fixture
@ -72,10 +71,9 @@ def test_get_fake_windows_equal_dir(data_subdir, config_subdir, expected,
QStandardPaths.DataLocation: str(tmpdir / data_subdir), QStandardPaths.DataLocation: str(tmpdir / data_subdir),
QStandardPaths.ConfigLocation: str(tmpdir / config_subdir), QStandardPaths.ConfigLocation: str(tmpdir / config_subdir),
} }
monkeypatch.setattr('qutebrowser.utils.standarddir.os.name', 'nt') monkeypatch.setattr(standarddir.os, 'name', 'nt')
monkeypatch.setattr( monkeypatch.setattr(standarddir.QStandardPaths, 'writableLocation',
'qutebrowser.utils.standarddir.QStandardPaths.writableLocation', locations.get)
locations.get)
expected = str(tmpdir / expected) expected = str(tmpdir / expected)
assert standarddir.data() == expected assert standarddir.data() == expected
@ -95,7 +93,7 @@ class TestWritableLocation:
def test_sep(self, monkeypatch): def test_sep(self, monkeypatch):
"""Make sure the right kind of separator is used.""" """Make sure the right kind of separator is used."""
monkeypatch.setattr('qutebrowser.utils.standarddir.os.sep', '\\') monkeypatch.setattr(standarddir.os, 'sep', '\\')
loc = standarddir._writable_location(QStandardPaths.DataLocation) loc = standarddir._writable_location(QStandardPaths.DataLocation)
assert '/' not in loc assert '/' not in loc
assert '\\' in loc assert '\\' in loc
@ -208,8 +206,7 @@ class TestInitCacheDirTag:
def test_existent_cache_dir_tag(self, tmpdir, mocker, monkeypatch): def test_existent_cache_dir_tag(self, tmpdir, mocker, monkeypatch):
"""Test with an existent CACHEDIR.TAG.""" """Test with an existent CACHEDIR.TAG."""
monkeypatch.setattr('qutebrowser.utils.standarddir.cache', monkeypatch.setattr(standarddir, 'cache', lambda: str(tmpdir))
lambda: str(tmpdir))
mocker.patch('builtins.open', side_effect=AssertionError) mocker.patch('builtins.open', side_effect=AssertionError)
m = mocker.patch('qutebrowser.utils.standarddir.os') m = mocker.patch('qutebrowser.utils.standarddir.os')
m.path.join.side_effect = os.path.join m.path.join.side_effect = os.path.join
@ -220,8 +217,7 @@ class TestInitCacheDirTag:
def test_new_cache_dir_tag(self, tmpdir, mocker, monkeypatch): def test_new_cache_dir_tag(self, tmpdir, mocker, monkeypatch):
"""Test creating a new CACHEDIR.TAG.""" """Test creating a new CACHEDIR.TAG."""
monkeypatch.setattr('qutebrowser.utils.standarddir.cache', monkeypatch.setattr(standarddir, 'cache', lambda: str(tmpdir))
lambda: str(tmpdir))
standarddir._init_cachedir_tag() standarddir._init_cachedir_tag()
assert tmpdir.listdir() == [(tmpdir / 'CACHEDIR.TAG')] assert tmpdir.listdir() == [(tmpdir / 'CACHEDIR.TAG')]
data = (tmpdir / 'CACHEDIR.TAG').read_text('utf-8') data = (tmpdir / 'CACHEDIR.TAG').read_text('utf-8')
@ -234,8 +230,7 @@ class TestInitCacheDirTag:
def test_open_oserror(self, caplog, tmpdir, mocker, monkeypatch): def test_open_oserror(self, caplog, tmpdir, mocker, monkeypatch):
"""Test creating a new CACHEDIR.TAG.""" """Test creating a new CACHEDIR.TAG."""
monkeypatch.setattr('qutebrowser.utils.standarddir.cache', monkeypatch.setattr(standarddir, 'cache', lambda: str(tmpdir))
lambda: str(tmpdir))
mocker.patch('builtins.open', side_effect=OSError) mocker.patch('builtins.open', side_effect=OSError)
with caplog.at_level(logging.ERROR, 'init'): with caplog.at_level(logging.ERROR, 'init'):
standarddir._init_cachedir_tag() standarddir._init_cachedir_tag()

View File

@ -84,8 +84,7 @@ def fake_dns(monkeypatch):
fromname_mock will be called without answer being set. fromname_mock will be called without answer being set.
""" """
dns = FakeDNS() dns = FakeDNS()
monkeypatch.setattr('qutebrowser.utils.urlutils.QHostInfo.fromName', monkeypatch.setattr(urlutils.QHostInfo, 'fromName', dns.fromname_mock)
dns.fromname_mock)
return dns return dns
@ -105,7 +104,7 @@ def urlutils_config_stub(config_stub, monkeypatch):
'DEFAULT': 'http://www.example.com/?q={}', 'DEFAULT': 'http://www.example.com/?q={}',
}, },
} }
monkeypatch.setattr('qutebrowser.utils.urlutils.config', config_stub) monkeypatch.setattr(urlutils, 'config', config_stub)
return config_stub return config_stub
@ -225,7 +224,7 @@ class TestFuzzyUrl:
caplog): caplog):
"""Test with an invalid URL.""" """Test with an invalid URL."""
is_url_mock.return_value = True is_url_mock.return_value = True
monkeypatch.setattr('qutebrowser.utils.urlutils.qurl_from_user_input', monkeypatch.setattr(urlutils, 'qurl_from_user_input',
lambda url: QUrl()) lambda url: QUrl())
with pytest.raises(exception): with pytest.raises(exception):
with caplog.at_level(logging.ERROR): with caplog.at_level(logging.ERROR):

View File

@ -117,7 +117,7 @@ class TestElidingFilenames:
def freezer(request, monkeypatch): def freezer(request, monkeypatch):
if request.param and not getattr(sys, 'frozen', False): if request.param and not getattr(sys, 'frozen', False):
monkeypatch.setattr(sys, 'frozen', True, raising=False) monkeypatch.setattr(sys, 'frozen', True, raising=False)
monkeypatch.setattr('sys.executable', qutebrowser.__file__) monkeypatch.setattr(sys, 'executable', qutebrowser.__file__)
elif not request.param and getattr(sys, 'frozen', False): elif not request.param and getattr(sys, 'frozen', False):
# Want to test unfrozen tests, but we are frozen # Want to test unfrozen tests, but we are frozen
pytest.skip("Can't run with sys.frozen = True!") pytest.skip("Can't run with sys.frozen = True!")
@ -161,17 +161,15 @@ class Patcher:
def patch_platform(self, platform='linux'): def patch_platform(self, platform='linux'):
"""Patch sys.platform.""" """Patch sys.platform."""
self.monkeypatch.setattr('sys.platform', platform) self.monkeypatch.setattr(sys, 'platform', platform)
def patch_exists(self, exists=True): def patch_exists(self, exists=True):
"""Patch os.path.exists.""" """Patch os.path.exists."""
self.monkeypatch.setattr('qutebrowser.utils.utils.os.path.exists', self.monkeypatch.setattr(utils.os.path, 'exists', lambda path: exists)
lambda path: exists)
def patch_version(self, version='5.2.0'): def patch_version(self, version='5.2.0'):
"""Patch Qt version.""" """Patch Qt version."""
self.monkeypatch.setattr('qutebrowser.utils.utils.qtutils.qVersion', self.monkeypatch.setattr(utils.qtutils, 'qVersion', lambda: version)
lambda: version)
def patch_file(self, data): def patch_file(self, data):
"""Patch open() to return the given data.""" """Patch open() to return the given data."""
@ -251,7 +249,7 @@ class TestActuteWarning:
def test_match_stdout_none(self, monkeypatch, patcher, capsys): def test_match_stdout_none(self, monkeypatch, patcher, capsys):
"""Test with a match and stdout being None.""" """Test with a match and stdout being None."""
patcher.patch_all('foobar\n<dead_actute>\nbaz') patcher.patch_all('foobar\n<dead_actute>\nbaz')
monkeypatch.setattr('sys.stdout', None) monkeypatch.setattr(sys, 'stdout', None)
utils.actute_warning() utils.actute_warning()
def test_unreadable(self, mocker, patcher, capsys, caplog): def test_unreadable(self, mocker, patcher, capsys, caplog):
@ -434,7 +432,7 @@ class TestKeyToString:
def test_missing(self, monkeypatch): def test_missing(self, monkeypatch):
"""Test with a missing key.""" """Test with a missing key."""
monkeypatch.delattr('qutebrowser.utils.utils.Qt.Key_Blue') monkeypatch.delattr(utils.Qt, 'Key_Blue')
# We don't want to test the key which is actually missing - we only # We don't want to test the key which is actually missing - we only
# want to know if the mapping still behaves properly. # want to know if the mapping still behaves properly.
assert utils.key_to_string(Qt.Key_A) == 'A' assert utils.key_to_string(Qt.Key_A) == 'A'
@ -486,7 +484,7 @@ class TestKeyEventToString:
def test_mac(self, monkeypatch, fake_keyevent_factory): def test_mac(self, monkeypatch, fake_keyevent_factory):
"""Test with a simulated mac.""" """Test with a simulated mac."""
monkeypatch.setattr('sys.platform', 'darwin') monkeypatch.setattr(sys, 'platform', 'darwin')
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

@ -93,21 +93,18 @@ class TestGitStr:
mocker.patch('qutebrowser.utils.version.subprocess', mocker.patch('qutebrowser.utils.version.subprocess',
side_effect=AssertionError) side_effect=AssertionError)
fake = GitStrSubprocessFake() fake = GitStrSubprocessFake()
monkeypatch.setattr('qutebrowser.utils.version._git_str_subprocess', monkeypatch.setattr(version, '_git_str_subprocess', fake.func)
fake.func)
return fake return fake
def test_frozen_ok(self, commit_file_mock, monkeypatch): def test_frozen_ok(self, commit_file_mock, monkeypatch):
"""Test with sys.frozen=True and a successful git-commit-id read.""" """Test with sys.frozen=True and a successful git-commit-id read."""
monkeypatch.setattr(qutebrowser.utils.version.sys, 'frozen', True, monkeypatch.setattr(version.sys, 'frozen', True, raising=False)
raising=False)
commit_file_mock.return_value = 'deadbeef' commit_file_mock.return_value = 'deadbeef'
assert version._git_str() == 'deadbeef' assert version._git_str() == 'deadbeef'
def test_frozen_oserror(self, caplog, commit_file_mock, monkeypatch): def test_frozen_oserror(self, caplog, commit_file_mock, monkeypatch):
"""Test with sys.frozen=True and OSError when reading git-commit-id.""" """Test with sys.frozen=True and OSError when reading git-commit-id."""
monkeypatch.setattr(qutebrowser.utils.version.sys, 'frozen', True, monkeypatch.setattr(version.sys, 'frozen', True, raising=False)
raising=False)
commit_file_mock.side_effect = OSError commit_file_mock.side_effect = OSError
with caplog.at_level(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
assert version._git_str() is None assert version._git_str() is None
@ -144,7 +141,7 @@ class TestGitStr:
def test_normal_path_nofile(self, monkeypatch, caplog, def test_normal_path_nofile(self, monkeypatch, caplog,
git_str_subprocess_fake, commit_file_mock): git_str_subprocess_fake, commit_file_mock):
"""Test with undefined __file__ but available git-commit-id.""" """Test with undefined __file__ but available git-commit-id."""
monkeypatch.delattr('qutebrowser.utils.version.__file__') monkeypatch.delattr(version, '__file__')
commit_file_mock.return_value = '0deadcode' commit_file_mock.return_value = '0deadcode'
with caplog.at_level(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
assert version._git_str() == '0deadcode' assert version._git_str() == '0deadcode'
@ -304,7 +301,7 @@ def test_release_info(files, expected, caplog, monkeypatch):
expected: The expected _release_info output. expected: The expected _release_info output.
""" """
fake = ReleaseInfoFake(files) fake = ReleaseInfoFake(files)
monkeypatch.setattr('qutebrowser.utils.version.glob.glob', fake.glob_fake) monkeypatch.setattr(version.glob, 'glob', fake.glob_fake)
monkeypatch.setattr(version, 'open', fake.open_fake, raising=False) monkeypatch.setattr(version, 'open', fake.open_fake, raising=False)
with caplog.at_level(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
assert version._release_info() == expected assert version._release_info() == expected
@ -325,7 +322,7 @@ def test_path_info(monkeypatch):
} }
for attr, val in patches.items(): for attr, val in patches.items():
monkeypatch.setattr('qutebrowser.utils.standarddir.' + attr, val) monkeypatch.setattr(version.standarddir, attr, val)
pathinfo = version._path_info() pathinfo = version._path_info()
@ -407,7 +404,7 @@ def import_fake(monkeypatch):
"""Fixture to patch imports using ImportFake.""" """Fixture to patch imports using ImportFake."""
fake = ImportFake() fake = ImportFake()
monkeypatch.setattr('builtins.__import__', fake.fake_import) monkeypatch.setattr('builtins.__import__', fake.fake_import)
monkeypatch.setattr('qutebrowser.utils.version.importlib.import_module', monkeypatch.setattr(version.importlib, 'import_module',
fake.fake_importlib_import) fake.fake_importlib_import)
return fake return fake
@ -508,8 +505,8 @@ class TestOsInfo:
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('qutebrowser.utils.version.sys.platform', 'linux') monkeypatch.setattr(version.sys, 'platform', 'linux')
monkeypatch.setattr('qutebrowser.utils.version._release_info', monkeypatch.setattr(version, '_release_info',
lambda: [('releaseinfo', 'Hello World')]) lambda: [('releaseinfo', 'Hello World')])
ret = version._os_info() ret = version._os_info()
expected = ['OS Version: ', '', expected = ['OS Version: ', '',
@ -518,8 +515,8 @@ class TestOsInfo:
def test_windows_fake(self, monkeypatch): def test_windows_fake(self, monkeypatch):
"""Test with a fake Windows.""" """Test with a fake Windows."""
monkeypatch.setattr('qutebrowser.utils.version.sys.platform', 'win32') monkeypatch.setattr(version.sys, 'platform', 'win32')
monkeypatch.setattr('qutebrowser.utils.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']
@ -537,17 +534,15 @@ 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('qutebrowser.utils.version.sys.platform', 'darwin') monkeypatch.setattr(version.sys, 'platform', 'darwin')
monkeypatch.setattr('qutebrowser.utils.version.platform.mac_ver', monkeypatch.setattr(version.platform, 'mac_ver', lambda: 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): def test_unknown_fake(self, monkeypatch):
"""Test with a fake unknown sys.platform.""" """Test with a fake unknown sys.platform."""
monkeypatch.setattr('qutebrowser.utils.version.sys.platform', monkeypatch.setattr(version.sys, 'platform', 'toaster')
'toaster')
ret = version._os_info() ret = version._os_info()
expected = ['OS Version: ?'] expected = ['OS Version: ?']
assert ret == expected assert ret == expected