Move cmdutils.cmd_dict to objects.commands

This commit is contained in:
Florian Bruhin 2018-11-29 11:21:07 +01:00
parent 168bc3dc49
commit 19628d0ae9
17 changed files with 69 additions and 71 deletions

View File

@ -37,7 +37,7 @@ from qutebrowser.keyinput import modeman, keyutils
from qutebrowser.utils import (message, usertypes, log, qtutils, urlutils, from qutebrowser.utils import (message, usertypes, log, qtutils, urlutils,
objreg, utils, standarddir) objreg, utils, standarddir)
from qutebrowser.utils.usertypes import KeyMode from qutebrowser.utils.usertypes import KeyMode
from qutebrowser.misc import editor, guiprocess from qutebrowser.misc import editor, guiprocess, objects
from qutebrowser.completion.models import urlmodel, miscmodels from qutebrowser.completion.models import urlmodel, miscmodels
from qutebrowser.mainwindow import mainwindow from qutebrowser.mainwindow import mainwindow
@ -1612,7 +1612,7 @@ class CommandDispatcher:
path = 'index.html' path = 'index.html'
elif topic.startswith(':'): elif topic.startswith(':'):
command = topic[1:] command = topic[1:]
if command not in cmdutils.cmd_dict: if command not in objects.commands:
raise cmdexc.CommandError("Invalid command {}!".format( raise cmdexc.CommandError("Invalid command {}!".format(
command)) command))
path = 'commands.html#{}'.format(command) path = 'commands.html#{}'.format(command)

View File

@ -22,11 +22,10 @@
import inspect import inspect
import typing # pylint: disable=unused-import import typing # pylint: disable=unused-import
from qutebrowser.misc import objects
from qutebrowser.utils import qtutils, log from qutebrowser.utils import qtutils, log
from qutebrowser.commands import command, cmdexc from qutebrowser.commands import command, cmdexc
cmd_dict = {} # type: typing.Dict[str, command.Command]
def check_overflow(arg, ctype): def check_overflow(arg, ctype):
"""Check if the given argument is in bounds for the given type. """Check if the given argument is in bounds for the given type.
@ -89,7 +88,7 @@ class register: # noqa: N801,N806 pylint: disable=invalid-name
Gets called when a function should be decorated. Gets called when a function should be decorated.
Doesn't actually decorate anything, but creates a Command object and Doesn't actually decorate anything, but creates a Command object and
registers it in the cmd_dict. registers it in the global commands dict.
Args: Args:
func: The function to be decorated. func: The function to be decorated.
@ -104,11 +103,11 @@ class register: # noqa: N801,N806 pylint: disable=invalid-name
name = self._name name = self._name
log.commands.vdebug("Registering command {} (from {}:{})".format( log.commands.vdebug("Registering command {} (from {}:{})".format(
name, func.__module__, func.__qualname__)) name, func.__module__, func.__qualname__))
if name in cmd_dict: if name in objects.commands:
raise ValueError("{} is already registered!".format(name)) raise ValueError("{} is already registered!".format(name))
cmd = command.Command(name=name, instance=self._instance, cmd = command.Command(name=name, instance=self._instance,
handler=func, **self._kwargs) handler=func, **self._kwargs)
cmd_dict[name] = cmd objects.commands[name] = cmd
return func return func

View File

@ -26,9 +26,9 @@ import attr
from PyQt5.QtCore import pyqtSlot, QUrl, QObject from PyQt5.QtCore import pyqtSlot, QUrl, QObject
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.commands import cmdexc
from qutebrowser.utils import message, objreg, qtutils, usertypes, utils from qutebrowser.utils import message, objreg, qtutils, usertypes, utils
from qutebrowser.misc import split from qutebrowser.misc import split, objects
last_command = {} last_command = {}
@ -193,7 +193,7 @@ class CommandParser:
cmdstr = self._completion_match(cmdstr) cmdstr = self._completion_match(cmdstr)
try: try:
cmd = cmdutils.cmd_dict[cmdstr] cmd = objects.commands[cmdstr]
except KeyError: except KeyError:
if not fallback: if not fallback:
raise cmdexc.NoSuchCommandError( raise cmdexc.NoSuchCommandError(
@ -220,7 +220,7 @@ class CommandParser:
Return: Return:
cmdstr modified to the matching completion or unmodified cmdstr modified to the matching completion or unmodified
""" """
matches = [cmd for cmd in sorted(cmdutils.cmd_dict, key=len) matches = [cmd for cmd in sorted(objects.commands, key=len)
if cmdstr in cmd] if cmdstr in cmd]
if len(matches) == 1: if len(matches) == 1:
cmdstr = matches[0] cmdstr = matches[0]

View File

@ -23,7 +23,8 @@ import attr
from PyQt5.QtCore import pyqtSlot, QObject, QTimer from PyQt5.QtCore import pyqtSlot, QObject, QTimer
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.commands import cmdutils, runners from qutebrowser.commands import runners
from qutebrowser.misc import objects
from qutebrowser.utils import log, utils, debug from qutebrowser.utils import log, utils, debug
from qutebrowser.completion.models import miscmodels from qutebrowser.completion.models import miscmodels
@ -92,7 +93,7 @@ class Completer(QObject):
log.completion.debug('Starting command completion') log.completion.debug('Starting command completion')
return miscmodels.command return miscmodels.command
try: try:
cmd = cmdutils.cmd_dict[before_cursor[0]] cmd = objects.commands[before_cursor[0]]
except KeyError: except KeyError:
log.completion.debug("No completion for unknown command: {}" log.completion.debug("No completion for unknown command: {}"
.format(before_cursor[0])) .format(before_cursor[0]))
@ -170,7 +171,7 @@ class Completer(QObject):
before, center, after = self._partition() before, center, after = self._partition()
log.completion.debug("Changing {} to '{}'".format(center, text)) log.completion.debug("Changing {} to '{}'".format(center, text))
try: try:
maxsplit = cmdutils.cmd_dict[before[0]].maxsplit maxsplit = objects.commands[before[0]].maxsplit
except (KeyError, IndexError): except (KeyError, IndexError):
maxsplit = None maxsplit = None
if maxsplit is None: if maxsplit is None:

View File

@ -20,7 +20,7 @@
"""Utility functions for completion models.""" """Utility functions for completion models."""
from qutebrowser.utils import objreg, usertypes from qutebrowser.utils import objreg, usertypes
from qutebrowser.commands import cmdutils from qutebrowser.misc import objects
def get_cmd_completions(info, include_hidden, include_aliases, prefix=''): def get_cmd_completions(info, include_hidden, include_aliases, prefix=''):
@ -34,10 +34,10 @@ def get_cmd_completions(info, include_hidden, include_aliases, prefix=''):
Return: A list of tuples of form (name, description, bindings). Return: A list of tuples of form (name, description, bindings).
""" """
assert cmdutils.cmd_dict assert objects.commands
cmdlist = [] cmdlist = []
cmd_to_keys = info.keyconf.get_reverse_bindings_for('normal') cmd_to_keys = info.keyconf.get_reverse_bindings_for('normal')
for obj in set(cmdutils.cmd_dict.values()): for obj in set(objects.commands.values()):
hide_debug = obj.debug and not objreg.get('args').debug hide_debug = obj.debug and not objreg.get('args').debug
hide_mode = (usertypes.KeyMode.normal not in obj.modes and hide_mode = (usertypes.KeyMode.normal not in obj.modes and
not include_hidden) not include_hidden)

View File

@ -60,7 +60,7 @@ from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtGui import QColor, QFont from PyQt5.QtGui import QColor, QFont
from PyQt5.QtWidgets import QTabWidget, QTabBar from PyQt5.QtWidgets import QTabWidget, QTabBar
from qutebrowser.commands import cmdutils from qutebrowser.misc import objects
from qutebrowser.config import configexc, configutils from qutebrowser.config import configexc, configutils
from qutebrowser.utils import standarddir, utils, qtutils, urlutils, urlmatch from qutebrowser.utils import standarddir, utils, qtutils, urlutils, urlmatch
from qutebrowser.keyinput import keyutils from qutebrowser.keyinput import keyutils
@ -881,7 +881,7 @@ class Command(BaseType):
def complete(self): def complete(self):
out = [] out = []
for cmdname, obj in cmdutils.cmd_dict.items(): for cmdname, obj in objects.commands.items():
out.append((cmdname, obj.desc)) out.append((cmdname, obj.desc))
return out return out

View File

@ -33,7 +33,7 @@ from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.utils import utils, usertypes from qutebrowser.utils import utils, usertypes
from qutebrowser.commands import cmdutils from qutebrowser.misc import objects
from qutebrowser.keyinput import keyutils from qutebrowser.keyinput import keyutils
@ -101,7 +101,7 @@ class KeyHintView(QLabel):
def takes_count(cmdstr): def takes_count(cmdstr):
"""Return true iff this command can take a count argument.""" """Return true iff this command can take a count argument."""
cmdname = cmdstr.split(' ')[0] cmdname = cmdstr.split(' ')[0]
cmd = cmdutils.cmd_dict.get(cmdname) cmd = objects.commands.get(cmdname)
return cmd and cmd.takes_count() return cmd and cmd.takes_count()
bindings_dict = config.key_instance.get_bindings_for(modename) bindings_dict = config.key_instance.get_bindings_for(modename)

View File

@ -28,6 +28,7 @@ MYPY = False
if MYPY: if MYPY:
# pylint: disable=unused-import,useless-suppression # pylint: disable=unused-import,useless-suppression
from qutebrowser.utils import usertypes from qutebrowser.utils import usertypes
from qutebrowser.commands import command
class NoBackend: class NoBackend:
@ -39,3 +40,4 @@ class NoBackend:
backend = NoBackend() # type: typing.Union[usertypes.Backend, NoBackend] backend = NoBackend() # type: typing.Union[usertypes.Backend, NoBackend]
commands = {} # type: typing.Dict[str, command.Command]

View File

@ -30,7 +30,7 @@ import argparse
import vulture import vulture
import qutebrowser.app # pylint: disable=unused-import import qutebrowser.app # pylint: disable=unused-import
from qutebrowser.commands import cmdutils from qutebrowser.misc import objects
from qutebrowser.utils import utils from qutebrowser.utils import utils
from qutebrowser.browser.webkit import rfc6266 from qutebrowser.browser.webkit import rfc6266
# To run the decorators from there # To run the decorators from there
@ -44,7 +44,7 @@ from qutebrowser.config import configtypes
def whitelist_generator(): # noqa def whitelist_generator(): # noqa
"""Generator which yields lines to add to a vulture whitelist.""" """Generator which yields lines to add to a vulture whitelist."""
# qutebrowser commands # qutebrowser commands
for cmd in cmdutils.cmd_dict.values(): for cmd in objects.commands.values():
yield utils.qualname(cmd.handler) yield utils.qualname(cmd.handler)
# pyPEG2 classes # pyPEG2 classes

View File

@ -35,9 +35,10 @@ sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir,
# We import qutebrowser.app so all @cmdutils-register decorators are run. # We import qutebrowser.app so all @cmdutils-register decorators are run.
import qutebrowser.app import qutebrowser.app
from qutebrowser import qutebrowser, commands from qutebrowser import qutebrowser, commands
from qutebrowser.commands import cmdutils, argparser from qutebrowser.commands import argparser
from qutebrowser.config import configdata, configtypes from qutebrowser.config import configdata, configtypes
from qutebrowser.utils import docutils, usertypes from qutebrowser.utils import docutils, usertypes
from qutebrowser.misc import objects
from scripts import asciidoc2html, utils from scripts import asciidoc2html, utils
FILE_HEADER = """ FILE_HEADER = """
@ -350,7 +351,7 @@ def generate_commands(filename):
normal_cmds = [] normal_cmds = []
other_cmds = [] other_cmds = []
debug_cmds = [] debug_cmds = []
for name, cmd in cmdutils.cmd_dict.items(): for name, cmd in objects.commands.items():
if cmd.deprecated: if cmd.deprecated:
continue continue
if usertypes.KeyMode.normal not in cmd.modes: if usertypes.KeyMode.normal not in cmd.modes:

View File

@ -326,14 +326,6 @@ class FakeSignal:
""" """
@attr.s
class FakeCmdUtils:
"""Stub for cmdutils which provides a cmd_dict."""
cmd_dict = attr.ib()
@attr.s(frozen=True) @attr.s(frozen=True)
class FakeCommand: class FakeCommand:

View File

@ -29,14 +29,14 @@ import enum
import pytest import pytest
from qutebrowser.commands import cmdutils, cmdexc, argparser, command from qutebrowser.misc import objects
from qutebrowser.commands import cmdexc, argparser, command, cmdutils
from qutebrowser.utils import usertypes from qutebrowser.utils import usertypes
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def clear_globals(monkeypatch): def clear_globals(monkeypatch):
"""Clear the cmdutils globals between each test.""" monkeypatch.setattr(objects, 'commands', {})
monkeypatch.setattr(cmdutils, 'cmd_dict', {})
def _get_cmd(*args, **kwargs): def _get_cmd(*args, **kwargs):
@ -48,7 +48,7 @@ def _get_cmd(*args, **kwargs):
@cmdutils.register(*args, **kwargs) @cmdutils.register(*args, **kwargs)
def fun(): def fun():
"""Blah.""" """Blah."""
return cmdutils.cmd_dict['fun'] return objects.commands['fun']
class TestCheckOverflow: class TestCheckOverflow:
@ -83,10 +83,10 @@ class TestRegister:
def fun(): def fun():
"""Blah.""" """Blah."""
cmd = cmdutils.cmd_dict['fun'] cmd = objects.commands['fun']
assert cmd.handler is fun assert cmd.handler is fun
assert cmd.name == 'fun' assert cmd.name == 'fun'
assert len(cmdutils.cmd_dict) == 1 assert len(objects.commands) == 1
def test_underlines(self): def test_underlines(self):
"""Make sure the function name is normalized correctly (_ -> -).""" """Make sure the function name is normalized correctly (_ -> -)."""
@ -94,8 +94,8 @@ class TestRegister:
def eggs_bacon(): def eggs_bacon():
"""Blah.""" """Blah."""
assert cmdutils.cmd_dict['eggs-bacon'].name == 'eggs-bacon' assert objects.commands['eggs-bacon'].name == 'eggs-bacon'
assert 'eggs_bacon' not in cmdutils.cmd_dict assert 'eggs_bacon' not in objects.commands
def test_lowercasing(self): def test_lowercasing(self):
"""Make sure the function name is normalized correctly (uppercase).""" """Make sure the function name is normalized correctly (uppercase)."""
@ -103,8 +103,8 @@ class TestRegister:
def Test(): # noqa: N801,N806 pylint: disable=invalid-name def Test(): # noqa: N801,N806 pylint: disable=invalid-name
"""Blah.""" """Blah."""
assert cmdutils.cmd_dict['test'].name == 'test' assert objects.commands['test'].name == 'test'
assert 'Test' not in cmdutils.cmd_dict assert 'Test' not in objects.commands
def test_explicit_name(self): def test_explicit_name(self):
"""Test register with explicit name.""" """Test register with explicit name."""
@ -112,9 +112,9 @@ class TestRegister:
def fun(): def fun():
"""Blah.""" """Blah."""
assert cmdutils.cmd_dict['foobar'].name == 'foobar' assert objects.commands['foobar'].name == 'foobar'
assert 'fun' not in cmdutils.cmd_dict assert 'fun' not in objects.commands
assert len(cmdutils.cmd_dict) == 1 assert len(objects.commands) == 1
def test_multiple_registrations(self): def test_multiple_registrations(self):
"""Make sure registering the same name twice raises ValueError.""" """Make sure registering the same name twice raises ValueError."""
@ -132,7 +132,7 @@ class TestRegister:
@cmdutils.register(instance='foobar') @cmdutils.register(instance='foobar')
def fun(self): def fun(self):
"""Blah.""" """Blah."""
assert cmdutils.cmd_dict['fun']._instance == 'foobar' assert objects.commands['fun']._instance == 'foobar'
def test_star_args(self): def test_star_args(self):
"""Check handling of *args.""" """Check handling of *args."""
@ -140,7 +140,7 @@ class TestRegister:
def fun(*args): def fun(*args):
"""Blah.""" """Blah."""
with pytest.raises(argparser.ArgumentParserError): with pytest.raises(argparser.ArgumentParserError):
cmdutils.cmd_dict['fun'].parser.parse_args([]) objects.commands['fun'].parser.parse_args([])
def test_star_args_optional(self): def test_star_args_optional(self):
"""Check handling of *args withstar_args_optional.""" """Check handling of *args withstar_args_optional."""
@ -148,7 +148,7 @@ class TestRegister:
def fun(*args): def fun(*args):
"""Blah.""" """Blah."""
assert not args assert not args
cmd = cmdutils.cmd_dict['fun'] cmd = objects.commands['fun']
cmd.namespace = cmd.parser.parse_args([]) cmd.namespace = cmd.parser.parse_args([])
args, kwargs = cmd._get_call_args(win_id=0) args, kwargs = cmd._get_call_args(win_id=0)
fun(*args, **kwargs) fun(*args, **kwargs)
@ -160,7 +160,7 @@ class TestRegister:
def fun(arg=False): def fun(arg=False):
"""Blah.""" """Blah."""
assert arg == expected assert arg == expected
cmd = cmdutils.cmd_dict['fun'] cmd = objects.commands['fun']
cmd.namespace = cmd.parser.parse_args(inp) cmd.namespace = cmd.parser.parse_args(inp)
assert cmd.namespace.arg == expected assert cmd.namespace.arg == expected
@ -170,7 +170,7 @@ class TestRegister:
def fun(arg=False): def fun(arg=False):
"""Blah.""" """Blah."""
assert arg assert arg
cmd = cmdutils.cmd_dict['fun'] cmd = objects.commands['fun']
with pytest.raises(argparser.ArgumentParserError): with pytest.raises(argparser.ArgumentParserError):
cmd.parser.parse_args(['-a']) cmd.parser.parse_args(['-a'])
@ -192,14 +192,14 @@ class TestRegister:
@cmdutils.argument('win_id', win_id=True) @cmdutils.argument('win_id', win_id=True)
def fun(win_id): def fun(win_id):
"""Blah.""" """Blah."""
assert cmdutils.cmd_dict['fun']._get_call_args(42) == ([42], {}) assert objects.commands['fun']._get_call_args(42) == ([42], {})
def test_count(self): def test_count(self):
@cmdutils.register() @cmdutils.register()
@cmdutils.argument('count', count=True) @cmdutils.argument('count', count=True)
def fun(count=0): def fun(count=0):
"""Blah.""" """Blah."""
assert cmdutils.cmd_dict['fun']._get_call_args(42) == ([0], {}) assert objects.commands['fun']._get_call_args(42) == ([0], {})
def test_count_without_default(self): def test_count_without_default(self):
with pytest.raises(TypeError, match="fun: handler has count parameter " with pytest.raises(TypeError, match="fun: handler has count parameter "
@ -216,7 +216,7 @@ class TestRegister:
def fun(arg): def fun(arg):
"""Blah.""" """Blah."""
pos_args = cmdutils.cmd_dict['fun'].pos_args pos_args = objects.commands['fun'].pos_args
if hide: if hide:
assert pos_args == [] assert pos_args == []
else: else:
@ -251,7 +251,7 @@ class TestRegister:
"""Blah.""" """Blah."""
assert arg == expected assert arg == expected
cmd = cmdutils.cmd_dict['fun'] cmd = objects.commands['fun']
cmd.namespace = cmd.parser.parse_args([inp]) cmd.namespace = cmd.parser.parse_args([inp])
if expected is cmdexc.ArgumentTypeError: if expected is cmdexc.ArgumentTypeError:
@ -270,7 +270,7 @@ class TestRegister:
def fun(arg): def fun(arg):
"""Blah.""" """Blah."""
cmd = cmdutils.cmd_dict['fun'] cmd = objects.commands['fun']
cmd.namespace = cmd.parser.parse_args(['fish']) cmd.namespace = cmd.parser.parse_args(['fish'])
with pytest.raises(cmdexc.ArgumentTypeError): with pytest.raises(cmdexc.ArgumentTypeError):
@ -283,7 +283,7 @@ class TestRegister:
def fun(*, arg='foo'): def fun(*, arg='foo'):
"""Blah.""" """Blah."""
cmd = cmdutils.cmd_dict['fun'] cmd = objects.commands['fun']
cmd.namespace = cmd.parser.parse_args(['--arg=fish']) cmd.namespace = cmd.parser.parse_args(['--arg=fish'])
with pytest.raises(cmdexc.ArgumentTypeError): with pytest.raises(cmdexc.ArgumentTypeError):
@ -297,7 +297,7 @@ class TestRegister:
def fun(foo, bar, opt=False): def fun(foo, bar, opt=False):
"""Blah.""" """Blah."""
cmd = cmdutils.cmd_dict['fun'] cmd = objects.commands['fun']
assert cmd.get_pos_arg_info(0) == command.ArgInfo(choices=('a', 'b')) assert cmd.get_pos_arg_info(0) == command.ArgInfo(choices=('a', 'b'))
assert cmd.get_pos_arg_info(1) == command.ArgInfo(choices=('x', 'y')) assert cmd.get_pos_arg_info(1) == command.ArgInfo(choices=('x', 'y'))
with pytest.raises(IndexError): with pytest.raises(IndexError):
@ -422,6 +422,6 @@ class TestRun:
monkeypatch.setattr(command.objects, 'backend', monkeypatch.setattr(command.objects, 'backend',
usertypes.Backend.QtWebKit) usertypes.Backend.QtWebKit)
cmd = cmdutils.cmd_dict['fun'] cmd = objects.commands['fun']
with pytest.raises(cmdexc.PrerequisitesError, match=r'.* backend\.'): with pytest.raises(cmdexc.PrerequisitesError, match=r'.* backend\.'):
cmd.run(win_id=0) cmd.run(win_id=0)

View File

@ -21,7 +21,8 @@
import pytest import pytest
from qutebrowser.commands import runners, cmdexc, cmdutils from qutebrowser.misc import objects
from qutebrowser.commands import runners, cmdexc
class TestCommandParser: class TestCommandParser:
@ -74,7 +75,7 @@ class TestCompletions:
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def cmdutils_stub(self, monkeypatch, stubs): def cmdutils_stub(self, monkeypatch, stubs):
"""Patch the cmdutils module to provide fake commands.""" """Patch the cmdutils module to provide fake commands."""
monkeypatch.setattr(cmdutils, 'cmd_dict', { monkeypatch.setattr(objects, 'commands', {
'one': stubs.FakeCommand(name='one'), 'one': stubs.FakeCommand(name='one'),
'two': stubs.FakeCommand(name='two'), 'two': stubs.FakeCommand(name='two'),
'two-foo': stubs.FakeCommand(name='two-foo'), 'two-foo': stubs.FakeCommand(name='two-foo'),

View File

@ -129,7 +129,7 @@ def cmdutils_patch(monkeypatch, stubs, miscmodels_patch):
def config_cycle(option, *values): def config_cycle(option, *values):
"""For testing varargs.""" """For testing varargs."""
cmd_utils = stubs.FakeCmdUtils({ commands = {
'set': command.Command(name='set', handler=set_command), 'set': command.Command(name='set', handler=set_command),
'help': command.Command(name='help', handler=show_help), 'help': command.Command(name='help', handler=show_help),
'open': command.Command(name='open', handler=openurl, maxsplit=0), 'open': command.Command(name='open', handler=openurl, maxsplit=0),
@ -137,8 +137,8 @@ def cmdutils_patch(monkeypatch, stubs, miscmodels_patch):
'tab-give': command.Command(name='tab-give', handler=tab_give), 'tab-give': command.Command(name='tab-give', handler=tab_give),
'config-cycle': command.Command(name='config-cycle', 'config-cycle': command.Command(name='config-cycle',
handler=config_cycle), handler=config_cycle),
}) }
monkeypatch.setattr(completer, 'cmdutils', cmd_utils) monkeypatch.setattr(completer.objects, 'commands', commands)
def _set_cmd_prompt(cmd, txt): def _set_cmd_prompt(cmd, txt):

View File

@ -27,11 +27,11 @@ from datetime import datetime
import pytest import pytest
from PyQt5.QtCore import QUrl from PyQt5.QtCore import QUrl
from qutebrowser.misc import objects
from qutebrowser.completion import completer from qutebrowser.completion import completer
from qutebrowser.completion.models import miscmodels, urlmodel, configmodel from qutebrowser.completion.models import miscmodels, urlmodel, configmodel
from qutebrowser.config import configdata, configtypes from qutebrowser.config import configdata, configtypes
from qutebrowser.utils import usertypes from qutebrowser.utils import usertypes
from qutebrowser.commands import cmdutils
def _check_completions(model, expected): def _check_completions(model, expected):
@ -66,7 +66,7 @@ def _check_completions(model, expected):
@pytest.fixture() @pytest.fixture()
def cmdutils_stub(monkeypatch, stubs): def cmdutils_stub(monkeypatch, stubs):
"""Patch the cmdutils module to provide fake commands.""" """Patch the cmdutils module to provide fake commands."""
return monkeypatch.setattr(cmdutils, 'cmd_dict', { return monkeypatch.setattr(objects, 'commands', {
'quit': stubs.FakeCommand(name='quit', desc='quit qutebrowser'), 'quit': stubs.FakeCommand(name='quit', desc='quit qutebrowser'),
'open': stubs.FakeCommand(name='open', desc='open a url'), 'open': stubs.FakeCommand(name='open', desc='open a url'),
'prompt-yes': stubs.FakeCommand(name='prompt-yes', deprecated=True), 'prompt-yes': stubs.FakeCommand(name='prompt-yes', deprecated=True),

View File

@ -33,6 +33,7 @@ from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QColor, QFont from PyQt5.QtGui import QColor, QFont
from PyQt5.QtNetwork import QNetworkProxy from PyQt5.QtNetwork import QNetworkProxy
from qutebrowser.misc import objects
from qutebrowser.config import configtypes, configexc, configutils from qutebrowser.config import configtypes, configexc, configutils
from qutebrowser.utils import debug, utils, qtutils, urlmatch from qutebrowser.utils import debug, utils, qtutils, urlmatch
from qutebrowser.browser.network import pac from qutebrowser.browser.network import pac
@ -1208,11 +1209,11 @@ class TestCommand:
@pytest.fixture @pytest.fixture
def patch_cmdutils(self, monkeypatch, stubs): def patch_cmdutils(self, monkeypatch, stubs):
"""Patch the cmdutils module to provide fake commands.""" """Patch the cmdutils module to provide fake commands."""
cmd_utils = stubs.FakeCmdUtils({ commands = {
'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(configtypes, 'cmdutils', cmd_utils) }
monkeypatch.setattr('qutebrowser.commands.runners.cmdutils', cmd_utils) monkeypatch.setattr(objects, 'commands', commands)
@pytest.fixture @pytest.fixture
def klass(self): def klass(self):

View File

@ -21,6 +21,7 @@
import pytest import pytest
from qutebrowser.misc import objects
from qutebrowser.misc.keyhintwidget import KeyHintView from qutebrowser.misc.keyhintwidget import KeyHintView
@ -120,7 +121,7 @@ def test_suggestions_special(keyhint, config_stub):
def test_suggestions_with_count(keyhint, config_stub, monkeypatch, stubs): def test_suggestions_with_count(keyhint, config_stub, monkeypatch, stubs):
"""Test that a count prefix filters out commands that take no count.""" """Test that a count prefix filters out commands that take no count."""
monkeypatch.setattr('qutebrowser.commands.cmdutils.cmd_dict', { monkeypatch.setattr(objects, 'commands', {
'foo': stubs.FakeCommand(name='foo', takes_count=lambda: False), 'foo': stubs.FakeCommand(name='foo', takes_count=lambda: False),
'bar': stubs.FakeCommand(name='bar', takes_count=lambda: True), 'bar': stubs.FakeCommand(name='bar', takes_count=lambda: True),
}) })