pylint: Re-enable bad-continuation

And lots and lots of whitespace changes.
This commit is contained in:
Florian Bruhin 2017-12-15 19:08:15 +01:00
parent 93cd200bb7
commit e65c0dd8a7
44 changed files with 235 additions and 235 deletions

View File

@ -16,7 +16,6 @@ enable=all
disable=fixme,
no-self-use,
cyclic-import,
bad-continuation,
blacklisted-name,
logging-format-interpolation,
broad-except,

View File

@ -564,8 +564,8 @@ class Quitter:
cwd = os.path.abspath(os.path.dirname(sys.executable))
else:
args = [sys.executable, '-m', 'qutebrowser']
cwd = os.path.join(os.path.abspath(os.path.dirname(
qutebrowser.__file__)), '..')
cwd = os.path.join(
os.path.abspath(os.path.dirname(qutebrowser.__file__)), '..')
if not os.path.isdir(cwd):
# Probably running from a python egg. Let's fallback to
# cwd=None and see if that works out.

View File

@ -673,7 +673,7 @@ class CommandDispatcher:
self._open(new_url, tab, bg, window, related=True)
else: # pragma: no cover
raise ValueError("Got called with invalid value {} for "
"`where'.".format(where))
"`where'.".format(where))
except navigate.Error as e:
raise cmdexc.CommandError(e)
@ -1738,7 +1738,7 @@ class CommandDispatcher:
message.info("Search hit TOP, continuing at BOTTOM")
else:
message.warning("Text '{}' not found on page!".format(text),
replace=True)
replace=True)
@cmdutils.register(instance='command-dispatcher', scope='window',
maxsplit=0)

View File

@ -992,7 +992,7 @@ class DownloadModel(QAbstractListModel):
if not count:
count = len(self)
raise cmdexc.CommandError("Download {} is already done!"
.format(count))
.format(count))
download.cancel()
@cmdutils.register(instance='download-model', scope='window')

View File

@ -82,7 +82,7 @@ def fix_urls(asset):
('viewer.css', 'qute://pdfjs/web/viewer.css'),
('compatibility.js', 'qute://pdfjs/web/compatibility.js'),
('locale/locale.properties',
'qute://pdfjs/web/locale/locale.properties'),
'qute://pdfjs/web/locale/locale.properties'),
('l10n.js', 'qute://pdfjs/web/l10n.js'),
('../build/pdf.js', 'qute://pdfjs/build/pdf.js'),
('debugger.js', 'qute://pdfjs/web/debugger.js'),

View File

@ -139,7 +139,7 @@ def data_for_url(url):
A (mimetype, data) tuple.
"""
norm_url = url.adjusted(QUrl.NormalizePathSegments |
QUrl.StripTrailingSlash)
QUrl.StripTrailingSlash)
if norm_url != url:
raise Redirect(norm_url)
@ -455,7 +455,7 @@ def qute_configdiff(url):
return 'text/html', configdiff.get_diff()
except OSError as e:
error = (b'Failed to read old config: ' +
str(e.strerror).encode('utf-8'))
str(e.strerror).encode('utf-8'))
return 'text/plain', error
else:
data = config.instance.dump_userconfig().encode('utf-8')

View File

@ -206,7 +206,7 @@ class Completer(QObject):
log.completion.debug("Ignoring update because the length of "
"the text is less than completion.min_chars.")
elif (self._cmd.cursorPosition() == self._last_cursor_pos and
self._cmd.text() == self._last_text):
self._cmd.text() == self._last_text):
log.completion.debug("Ignoring update because there were no "
"changes.")
else:
@ -247,8 +247,8 @@ class Completer(QObject):
if func != self._last_completion_func:
self._last_completion_func = func
args = (x for x in before_cursor[1:] if not x.startswith('-'))
with debug.log_time(log.completion,
'Starting {} completion'.format(func.__name__)):
with debug.log_time(log.completion, 'Starting {} completion'
.format(func.__name__)):
info = CompletionInfo(config=config.instance,
keyconf=config.key_instance,
win_id=self._win_id)

View File

@ -60,7 +60,8 @@ def value(optname, *_values, info):
opt = info.config.get_opt(optname)
default = opt.typ.to_str(opt.default)
cur_cat = listcategory.ListCategory("Current/Default",
cur_cat = listcategory.ListCategory(
"Current/Default",
[(current, "Current value"), (default, "Default value")])
model.add_category(cur_cat)

View File

@ -123,7 +123,7 @@ def _buffer(skip_win_id=None):
tab.url().toDisplayString(),
tabbed_browser.page_title(idx)))
cat = listcategory.ListCategory("{}".format(win_id), tabs,
delete_func=delete_buffer)
delete_func=delete_buffer)
model.add_category(cat)
return model

View File

@ -71,7 +71,7 @@ class NormalKeyParser(keyparser.CommandKeyParser):
txt = e.text().strip()
if self._inhibited:
self._debug_log("Ignoring key '{}', because the normal mode is "
"currently inhibited.".format(txt))
"currently inhibited.".format(txt))
return self.Match.none
match = super()._handle_single_key(e)
if match == self.Match.partial:

View File

@ -202,14 +202,14 @@ def _check_modules(modules):
messages = ['invalid escape sequence',
'Flags not at the start of the expression']
with log.ignore_py_warnings(
category=DeprecationWarning,
message=r'({})'.format('|'.join(messages))
category=DeprecationWarning,
message=r'({})'.format('|'.join(messages))
), log.ignore_py_warnings(
category=PendingDeprecationWarning,
module='imp'
category=PendingDeprecationWarning,
module='imp'
), log.ignore_py_warnings(
category=ImportWarning,
message=r'Not importing directory .*: missing __init__'
category=ImportWarning,
message=r'Not importing directory .*: missing __init__'
):
importlib.import_module(name)
except ImportError as e:

View File

@ -111,9 +111,11 @@ class ExternalEditor(QObject):
# the file from the external editor, see
# https://github.com/qutebrowser/qutebrowser/issues/1767
with tempfile.NamedTemporaryFile(
# pylint: disable=bad-continuation
mode='w', prefix='qutebrowser-editor-',
encoding=config.val.editor.encoding,
delete=False) as fobj:
# pylint: enable=bad-continuation
if text:
fobj.write(text)
self._filename = fobj.name

View File

@ -74,7 +74,8 @@ def get_argparser():
"session even if one would be restored.",
action='store_true')
parser.add_argument('--target', choices=['auto', 'tab', 'tab-bg',
'tab-silent', 'tab-bg-silent', 'window'],
'tab-silent', 'tab-bg-silent',
'window'],
help="How URLs should be opened if there is already a "
"qutebrowser instance running.")
parser.add_argument('--backend', choices=['webkit', 'webengine'],

View File

@ -361,29 +361,29 @@ def qt_message_handler(msg_type, context, msg):
suppressed_msgs = [
# PNGs in Qt with broken color profile
# https://bugreports.qt.io/browse/QTBUG-39788
'libpng warning: iCCP: Not recognizing known sRGB profile that has '
'been edited', # noqa: E131
('libpng warning: iCCP: Not recognizing known sRGB profile that has '
'been edited'),
'libpng warning: iCCP: known incorrect sRGB profile',
# Hopefully harmless warning
'OpenType support missing for script ',
# Error if a QNetworkReply gets two different errors set. Harmless Qt
# bug on some pages.
# https://bugreports.qt.io/browse/QTBUG-30298
'QNetworkReplyImplPrivate::error: Internal problem, this method must '
'only be called once.',
('QNetworkReplyImplPrivate::error: Internal problem, this method must '
'only be called once.'),
# Sometimes indicates missing text, but most of the time harmless
'load glyph failed ',
# Harmless, see https://bugreports.qt.io/browse/QTBUG-42479
'content-type missing in HTTP POST, defaulting to '
'application/x-www-form-urlencoded. '
'Use QNetworkRequest::setHeader() to fix this problem.',
('content-type missing in HTTP POST, defaulting to '
'application/x-www-form-urlencoded. '
'Use QNetworkRequest::setHeader() to fix this problem.'),
# https://bugreports.qt.io/browse/QTBUG-43118
'Using blocking call!',
# Hopefully harmless
'"Method "GetAll" with signature "s" on interface '
'"org.freedesktop.DBus.Properties" doesn\'t exist',
'"Method \\"GetAll\\" with signature \\"s\\" on interface '
'\\"org.freedesktop.DBus.Properties\\" doesn\'t exist\\n"',
('"Method "GetAll" with signature "s" on interface '
'"org.freedesktop.DBus.Properties" doesn\'t exist'),
('"Method \\"GetAll\\" with signature \\"s\\" on interface '
'\\"org.freedesktop.DBus.Properties\\" doesn\'t exist\\n"'),
'WOFF support requires QtWebKit to be built with zlib support.',
# Weird Enlightment/GTK X extensions
'QXcbWindow: Unhandled client message: "_E_',
@ -392,21 +392,21 @@ def qt_message_handler(msg_type, context, msg):
# Happens on AppVeyor CI
'SetProcessDpiAwareness failed:',
# https://bugreports.qt.io/browse/QTBUG-49174
'QObject::connect: Cannot connect (null)::stateChanged('
'QNetworkSession::State) to '
'QNetworkReplyHttpImpl::_q_networkSessionStateChanged('
'QNetworkSession::State)',
('QObject::connect: Cannot connect (null)::stateChanged('
'QNetworkSession::State) to '
'QNetworkReplyHttpImpl::_q_networkSessionStateChanged('
'QNetworkSession::State)'),
# https://bugreports.qt.io/browse/QTBUG-53989
"Image of format '' blocked because it is not considered safe. If you "
"are sure it is safe to do so, you can white-list the format by "
"setting the environment variable QTWEBKIT_IMAGEFORMAT_WHITELIST=",
("Image of format '' blocked because it is not considered safe. If "
"you are sure it is safe to do so, you can white-list the format by "
"setting the environment variable QTWEBKIT_IMAGEFORMAT_WHITELIST="),
# Installing Qt from the installer may cause it looking for SSL3 or
# OpenSSL 1.0 which may not be available on the system
"QSslSocket: cannot resolve ",
"QSslSocket: cannot call unresolved function ",
# When enabling debugging with QtWebEngine
"Remote debugging server started successfully. Try pointing a "
"Chromium-based browser to ",
("Remote debugging server started successfully. Try pointing a "
"Chromium-based browser to "),
# https://github.com/qutebrowser/qutebrowser/issues/1287
"QXcbClipboard: SelectionRequest too old",
# https://github.com/qutebrowser/qutebrowser/issues/2071
@ -420,8 +420,8 @@ def qt_message_handler(msg_type, context, msg):
suppressed_msgs += [
'libpng warning: iCCP: known incorrect sRGB profile',
# https://bugreports.qt.io/browse/QTBUG-47154
'virtual void QSslSocketBackendPrivate::transmit() SSLRead failed '
'with: -9805', # noqa: E131
('virtual void QSslSocketBackendPrivate::transmit() SSLRead '
'failed with: -9805'),
]
if not msg:

View File

@ -254,7 +254,7 @@ def register(name, obj, update=False, scope=None, registry=None, window=None,
reg = _get_registry(scope, window, tab)
if not update and name in reg:
raise KeyError("Object '{}' is already registered ({})!".format(
name, repr(reg[name])))
name, repr(reg[name])))
reg[name] = obj

View File

@ -192,7 +192,7 @@ def fuzzy_url(urlstr, cwd=None, relative=False, do_search=True,
log.url.debug("URL is a fuzzy address")
url = qurl_from_user_input(urlstr)
log.url.debug("Converting fuzzy term {!r} to URL -> {}".format(
urlstr, url.toDisplayString()))
urlstr, url.toDisplayString()))
if do_search and config.val.url.auto_search != 'never' and urlstr:
qtutils.ensure_valid(url)
else:
@ -241,7 +241,7 @@ def is_url(urlstr):
autosearch = config.val.url.auto_search
log.url.debug("Checking if {!r} is a URL (autosearch={}).".format(
urlstr, autosearch))
urlstr, autosearch))
urlstr = urlstr.strip()
qurl = QUrl(urlstr)

View File

@ -86,9 +86,9 @@ class AsciiDoc:
# patch image links to use local copy
replacements = [
("https://qutebrowser.org/img/cheatsheet-big.png",
"qute://help/img/cheatsheet-big.png"),
"qute://help/img/cheatsheet-big.png"),
("https://qutebrowser.org/img/cheatsheet-small.png",
"qute://help/img/cheatsheet-small.png")
"qute://help/img/cheatsheet-small.png")
]
asciidoc_args = ['-a', 'source-highlighter=pygments']
@ -211,9 +211,8 @@ class AsciiDoc:
shutil.copytree(src, full_dest)
for dst, link_name in [
('README.html', 'index.html'),
(os.path.join('doc', 'quickstart.html'), 'quickstart.html'),
]:
('README.html', 'index.html'),
(os.path.join('doc', 'quickstart.html'), 'quickstart.html')]:
try:
os.symlink(dst, os.path.join(outdir, link_name))
except FileExistsError:

View File

@ -52,132 +52,132 @@ MsgType = enum.Enum('MsgType', 'insufficent_coverage, perfect_file')
# A list of (test_file, tested_file) tuples. test_file can be None.
PERFECT_FILES = [
(None,
'commands/cmdexc.py'),
'commands/cmdexc.py'),
('tests/unit/commands/test_cmdutils.py',
'commands/cmdutils.py'),
'commands/cmdutils.py'),
('tests/unit/commands/test_argparser.py',
'commands/argparser.py'),
'commands/argparser.py'),
('tests/unit/browser/webkit/test_cache.py',
'browser/webkit/cache.py'),
'browser/webkit/cache.py'),
('tests/unit/browser/webkit/test_cookies.py',
'browser/webkit/cookies.py'),
'browser/webkit/cookies.py'),
('tests/unit/browser/test_history.py',
'browser/history.py'),
'browser/history.py'),
('tests/unit/browser/webkit/http/test_http.py',
'browser/webkit/http.py'),
'browser/webkit/http.py'),
('tests/unit/browser/webkit/http/test_content_disposition.py',
'browser/webkit/rfc6266.py'),
'browser/webkit/rfc6266.py'),
# ('tests/unit/browser/webkit/test_webkitelem.py',
# 'browser/webkit/webkitelem.py'),
# 'browser/webkit/webkitelem.py'),
# ('tests/unit/browser/webkit/test_webkitelem.py',
# 'browser/webelem.py'),
# 'browser/webelem.py'),
('tests/unit/browser/webkit/network/test_schemehandler.py',
'browser/webkit/network/schemehandler.py'),
'browser/webkit/network/schemehandler.py'),
('tests/unit/browser/webkit/network/test_filescheme.py',
'browser/webkit/network/filescheme.py'),
'browser/webkit/network/filescheme.py'),
('tests/unit/browser/webkit/network/test_networkreply.py',
'browser/webkit/network/networkreply.py'),
'browser/webkit/network/networkreply.py'),
('tests/unit/browser/test_signalfilter.py',
'browser/signalfilter.py'),
'browser/signalfilter.py'),
(None,
'browser/webengine/certificateerror.py'),
'browser/webengine/certificateerror.py'),
# ('tests/unit/browser/test_tab.py',
# 'browser/tab.py'),
# 'browser/tab.py'),
('tests/unit/keyinput/test_basekeyparser.py',
'keyinput/basekeyparser.py'),
'keyinput/basekeyparser.py'),
('tests/unit/misc/test_autoupdate.py',
'misc/autoupdate.py'),
'misc/autoupdate.py'),
('tests/unit/misc/test_readline.py',
'misc/readline.py'),
'misc/readline.py'),
('tests/unit/misc/test_split.py',
'misc/split.py'),
'misc/split.py'),
('tests/unit/misc/test_msgbox.py',
'misc/msgbox.py'),
'misc/msgbox.py'),
('tests/unit/misc/test_checkpyver.py',
'misc/checkpyver.py'),
'misc/checkpyver.py'),
('tests/unit/misc/test_guiprocess.py',
'misc/guiprocess.py'),
'misc/guiprocess.py'),
('tests/unit/misc/test_editor.py',
'misc/editor.py'),
'misc/editor.py'),
('tests/unit/misc/test_cmdhistory.py',
'misc/cmdhistory.py'),
'misc/cmdhistory.py'),
('tests/unit/misc/test_ipc.py',
'misc/ipc.py'),
'misc/ipc.py'),
('tests/unit/misc/test_keyhints.py',
'misc/keyhintwidget.py'),
'misc/keyhintwidget.py'),
('tests/unit/misc/test_pastebin.py',
'misc/pastebin.py'),
'misc/pastebin.py'),
(None,
'misc/objects.py'),
'misc/objects.py'),
(None,
'mainwindow/statusbar/keystring.py'),
'mainwindow/statusbar/keystring.py'),
('tests/unit/mainwindow/statusbar/test_percentage.py',
'mainwindow/statusbar/percentage.py'),
'mainwindow/statusbar/percentage.py'),
('tests/unit/mainwindow/statusbar/test_progress.py',
'mainwindow/statusbar/progress.py'),
'mainwindow/statusbar/progress.py'),
('tests/unit/mainwindow/statusbar/test_tabindex.py',
'mainwindow/statusbar/tabindex.py'),
'mainwindow/statusbar/tabindex.py'),
('tests/unit/mainwindow/statusbar/test_textbase.py',
'mainwindow/statusbar/textbase.py'),
'mainwindow/statusbar/textbase.py'),
('tests/unit/mainwindow/statusbar/test_url.py',
'mainwindow/statusbar/url.py'),
'mainwindow/statusbar/url.py'),
('tests/unit/mainwindow/statusbar/test_backforward.py',
'mainwindow/statusbar/backforward.py'),
'mainwindow/statusbar/backforward.py'),
('tests/unit/mainwindow/test_messageview.py',
'mainwindow/messageview.py'),
'mainwindow/messageview.py'),
('tests/unit/config/test_config.py',
'config/config.py'),
'config/config.py'),
('tests/unit/config/test_configdata.py',
'config/configdata.py'),
'config/configdata.py'),
('tests/unit/config/test_configexc.py',
'config/configexc.py'),
'config/configexc.py'),
('tests/unit/config/test_configfiles.py',
'config/configfiles.py'),
'config/configfiles.py'),
('tests/unit/config/test_configtypes.py',
'config/configtypes.py'),
'config/configtypes.py'),
('tests/unit/config/test_configinit.py',
'config/configinit.py'),
'config/configinit.py'),
('tests/unit/config/test_configcommands.py',
'config/configcommands.py'),
'config/configcommands.py'),
('tests/unit/utils/test_qtutils.py',
'utils/qtutils.py'),
'utils/qtutils.py'),
('tests/unit/utils/test_standarddir.py',
'utils/standarddir.py'),
'utils/standarddir.py'),
('tests/unit/utils/test_urlutils.py',
'utils/urlutils.py'),
'utils/urlutils.py'),
('tests/unit/utils/usertypes',
'utils/usertypes.py'),
'utils/usertypes.py'),
('tests/unit/utils/test_utils.py',
'utils/utils.py'),
'utils/utils.py'),
('tests/unit/utils/test_version.py',
'utils/version.py'),
'utils/version.py'),
('tests/unit/utils/test_debug.py',
'utils/debug.py'),
'utils/debug.py'),
('tests/unit/utils/test_jinja.py',
'utils/jinja.py'),
'utils/jinja.py'),
('tests/unit/utils/test_error.py',
'utils/error.py'),
'utils/error.py'),
('tests/unit/utils/test_javascript.py',
'utils/javascript.py'),
'utils/javascript.py'),
(None,
'completion/models/util.py'),
'completion/models/util.py'),
('tests/unit/completion/test_models.py',
'completion/models/urlmodel.py'),
'completion/models/urlmodel.py'),
('tests/unit/completion/test_histcategory.py',
'completion/models/histcategory.py'),
'completion/models/histcategory.py'),
('tests/unit/completion/test_listcategory.py',
'completion/models/listcategory.py'),
'completion/models/listcategory.py'),
('tests/unit/browser/webengine/test_spell.py',
'browser/webengine/spell.py'),
'browser/webengine/spell.py'),
]

View File

@ -33,7 +33,7 @@ sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir,
from scripts import utils
REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'..', '..') # /scripts/dev -> /scripts -> /
'..', '..') # /scripts/dev -> /scripts -> /
REQ_DIR = os.path.join(REPO_DIR, 'misc', 'requirements')
@ -118,9 +118,9 @@ def main():
pip_bin = os.path.join(tmpdir, 'bin', 'pip')
subprocess.run(['virtualenv', tmpdir], check=True)
subprocess.run([pip_bin, 'install', '-r', filename], check=True)
reqs = subprocess.run([pip_bin, 'freeze'], check=True,
stdout=subprocess.PIPE
).stdout.decode('utf-8')
proc = subprocess.run([pip_bin, 'freeze'], check=True,
stdout=subprocess.PIPE)
reqs = proc.stdout.decode('utf-8')
with open(filename, 'r', encoding='utf-8') as f:
comments = read_comments(f)

View File

@ -257,7 +257,7 @@ def _get_command_doc_count(cmd, parser):
yield parser.arg_descs[param.name]
except KeyError as e:
raise KeyError("No description for count arg {!r} of command "
"{!r}!".format(param.name, cmd.name)) from e
"{!r}!".format(param.name, cmd.name)) from e
def _get_command_doc_notes(cmd):

View File

@ -99,16 +99,17 @@ def get_argparser():
subparsers = parser.add_subparsers(help='Command', dest='cmd')
subparsers.required = True
subparsers.add_parser('list',
help='Display the list of available languages.')
help='Display the list of available languages.')
subparsers.add_parser('update',
help='Update dictionaries')
help='Update dictionaries')
subparsers.add_parser('remove-old',
help='Remove old versions of dictionaries.')
help='Remove old versions of dictionaries.')
install_parser = subparsers.add_parser('install',
help='Install dictionaries')
help='Install dictionaries')
install_parser.add_argument('language',
nargs='*', help="A list of languages to install.")
nargs='*',
help="A list of languages to install.")
return parser

View File

@ -246,29 +246,29 @@ def import_netscape_bookmarks(bookmarks_file, bookmark_types, output_format):
def import_moz_places(profile, bookmark_types, output_format):
"""Import bookmarks from a Mozilla profile's places.sqlite database."""
place_query = {
'bookmark':
("SELECT DISTINCT moz_bookmarks.title,moz_places.url "
"FROM moz_bookmarks,moz_places "
"WHERE moz_places.id=moz_bookmarks.fk "
"AND moz_places.id NOT IN (SELECT place_id FROM moz_keywords) "
"AND moz_places.url NOT LIKE 'place:%';"
), # Bookmarks with no keywords assigned
'keyword':
("SELECT moz_keywords.keyword,moz_places.url "
"FROM moz_keywords,moz_places,moz_bookmarks "
"WHERE moz_places.id=moz_bookmarks.fk "
"AND moz_places.id=moz_keywords.place_id "
"AND moz_places.url NOT LIKE '%!%s%' ESCAPE '!';"
), # Bookmarks with keywords assigned but no %s substitution
'search':
("SELECT moz_keywords.keyword, "
" moz_bookmarks.title, "
" search_conv(moz_places.url) AS url "
"FROM moz_keywords,moz_places,moz_bookmarks "
"WHERE moz_places.id=moz_bookmarks.fk "
"AND moz_places.id=moz_keywords.place_id "
"AND moz_places.url LIKE '%!%s%' ESCAPE '!';"
) # bookmarks with keyword and %s substitution
'bookmark': (
"SELECT DISTINCT moz_bookmarks.title,moz_places.url "
"FROM moz_bookmarks,moz_places "
"WHERE moz_places.id=moz_bookmarks.fk "
"AND moz_places.id NOT IN (SELECT place_id FROM moz_keywords) "
"AND moz_places.url NOT LIKE 'place:%';"
), # Bookmarks with no keywords assigned
'keyword': (
"SELECT moz_keywords.keyword,moz_places.url "
"FROM moz_keywords,moz_places,moz_bookmarks "
"WHERE moz_places.id=moz_bookmarks.fk "
"AND moz_places.id=moz_keywords.place_id "
"AND moz_places.url NOT LIKE '%!%s%' ESCAPE '!';"
), # Bookmarks with keywords assigned but no %s substitution
'search': (
"SELECT moz_keywords.keyword, "
" moz_bookmarks.title, "
" search_conv(moz_places.url) AS url "
"FROM moz_keywords,moz_places,moz_bookmarks "
"WHERE moz_places.id=moz_bookmarks.fk "
"AND moz_places.id=moz_keywords.place_id "
"AND moz_places.url LIKE '%!%s%' ESCAPE '!';"
) # bookmarks with keyword and %s substitution
}
out_template = {
'bookmark': {

View File

@ -57,9 +57,9 @@ def _apply_platform_markers(config, item):
('mac', not utils.is_mac, "Requires macOS"),
('not_mac', utils.is_mac, "Skipped on macOS"),
('not_frozen', getattr(sys, 'frozen', False),
"Can't be run when frozen"),
"Can't be run when frozen"),
('frozen', not getattr(sys, 'frozen', False),
"Can only run when frozen"),
"Can only run when frozen"),
('ci', 'CI' not in os.environ, "Only runs on CI."),
('no_ci', 'CI' in os.environ, "Skipped on CI."),
('issue2478', utils.is_windows and config.webengine,

View File

@ -65,4 +65,4 @@ def create_greasemonkey_file(quteproc, stage, frameset):
"not {}".format(frameset))
with open(file_path, 'w', encoding='utf-8') as f:
f.write(test_gm_script.format(stage=stage,
frames=frames))
frames=frames))

View File

@ -154,7 +154,7 @@ def is_ignored_chromium_message(line):
'Invalid node channel message *',
# Makes tests fail on Quantumcross' machine
('CreatePlatformSocket() returned an error, errno=97: Address family'
'not supported by protocol'),
'not supported by protocol'),
# Qt 5.9 with debug Chromium
@ -169,7 +169,7 @@ def is_ignored_chromium_message(line):
# /tmp/pytest-of-florian/pytest-32/test_webengine_download_suffix0/
# downloads/download.bin: Operation not supported
('Could not set extended attribute user.xdg.* on file *: '
'Operation not supported'),
'Operation not supported'),
# [5947:5947:0605/192837.856931:ERROR:render_process_impl.cc(112)]
# WebFrame LEAKED 1 TIMES
'WebFrame LEAKED 1 TIMES',
@ -357,9 +357,10 @@ class QuteProc(testprocess.Process):
if not self._load_ready:
log_line.waited_for = True
self._is_ready('load')
elif log_line.category == 'misc' and any(testutils.pattern_match(
pattern=pattern, value=log_line.message) for pattern in
start_okay_messages_focus):
elif (log_line.category == 'misc' and any(
testutils.pattern_match(pattern=pattern,
value=log_line.message)
for pattern in start_okay_messages_focus)):
self._is_ready('focus')
elif (log_line.category == 'init' and
log_line.module == 'standarddir' and

View File

@ -241,8 +241,8 @@ def test_log_line_parse(data, attrs):
pytest.param(
{'created': 86400, 'msecs': 0, 'levelname': 'DEBUG', 'name': 'foo',
'module': 'bar', 'funcName': 'qux', 'lineno': 10, 'levelno': 10,
'message': 'quux', 'traceback': 'Traceback (most recent call '
'last):\n here be dragons'},
'message': 'quux', 'traceback': ('Traceback (most recent call '
'last):\n here be dragons')},
False, False,
'{timestamp} DEBUG foo bar:qux:10 quux\n'
'Traceback (most recent call last):\n'

View File

@ -71,8 +71,8 @@ def _parse_file(test_name):
allowed_keys = {'target', 'qtwebengine_todo'}
if not set(data.keys()).issubset(allowed_keys):
raise InvalidFile(test_name, "expected keys {} but found {}".format(
', '.join(allowed_keys),
', '.join(set(data.keys()))))
', '.join(allowed_keys),
', '.join(set(data.keys()))))
if 'target' not in data:
raise InvalidFile(test_name, "'target' key not found")

View File

@ -153,13 +153,13 @@ def test_delete_url(hist, raw, escaped):
'url, atime, title, redirect, history_url, completion_url', [
('http://www.example.com', 12346, 'the title', False,
'http://www.example.com', 'http://www.example.com'),
'http://www.example.com', 'http://www.example.com'),
('http://www.example.com', 12346, 'the title', True,
'http://www.example.com', None),
'http://www.example.com', None),
('http://www.example.com/sp ce', 12346, 'the title', False,
'http://www.example.com/sp%20ce', 'http://www.example.com/sp ce'),
'http://www.example.com/sp%20ce', 'http://www.example.com/sp ce'),
('https://user:pass@example.com', 12346, 'the title', False,
'https://user@example.com', 'https://user@example.com'),
'https://user@example.com', 'https://user@example.com'),
]
)
def test_add_url(qtbot, hist, url, atime, title, redirect, history_url,

View File

@ -118,7 +118,7 @@ class TestHistoryHandler:
(72*60*60, 0)
])
def test_qutehistory_data(self, start_time_offset, expected_item_count,
now):
now):
"""Ensure qute://history/data returns correct items."""
start_time = now - start_time_offset
url = QUrl("qute://history/data?start_time=" + str(start_time))

View File

@ -160,7 +160,7 @@ def _set_cmd_prompt(cmd, txt):
(':set general editor |', 'value', '', ['general', 'editor']),
(':set general editor gv|', 'value', 'gv', ['general', 'editor']),
(':set general editor "gvim -f"|', 'value', 'gvim -f',
['general', 'editor']),
['general', 'editor']),
(':set general editor "gvim |', 'value', 'gvim', ['general', 'editor']),
(':set general huh |', 'value', '', ['general', 'huh']),
(':help |', 'helptopic', '', []),

View File

@ -31,7 +31,8 @@ from qutebrowser.utils import qtutils
from qutebrowser.commands import cmdexc
@hypothesis.given(strategies.lists(min_size=0, max_size=3,
@hypothesis.given(strategies.lists(
min_size=0, max_size=3,
elements=strategies.integers(min_value=0, max_value=2**31)))
def test_first_last_item(counts):
"""Test that first() and last() index to the first and last items."""

View File

@ -82,9 +82,9 @@ def test_maybe_update_geometry(completionview, config_stub, qtbot):
('next', [['Aa'], ['Ba']], ['Aa', 'Ba', 'Aa']),
('prev', [['Aa'], ['Ba']], ['Ba', 'Aa', 'Ba']),
('next', [['Aa', 'Ab', 'Ac'], ['Ba', 'Bb'], ['Ca']],
['Aa', 'Ab', 'Ac', 'Ba', 'Bb', 'Ca', 'Aa']),
['Aa', 'Ab', 'Ac', 'Ba', 'Bb', 'Ca', 'Aa']),
('prev', [['Aa', 'Ab', 'Ac'], ['Ba', 'Bb'], ['Ca']],
['Ca', 'Bb', 'Ba', 'Ac', 'Ab', 'Aa', 'Ca']),
['Ca', 'Bb', 'Ba', 'Ac', 'Ab', 'Aa', 'Ca']),
('next', [[], ['Ba', 'Bb']], ['Ba', 'Bb', 'Ba']),
('prev', [[], ['Ba', 'Bb']], ['Bb', 'Ba', 'Bb']),
('next', [[], [], ['Ca', 'Cb']], ['Ca', 'Cb', 'Ca']),
@ -102,9 +102,9 @@ def test_maybe_update_geometry(completionview, config_stub, qtbot):
('next-category', [['Aa'], ['Ba']], ['Aa', 'Ba', 'Aa']),
('prev-category', [['Aa'], ['Ba']], ['Ba', 'Aa', 'Ba']),
('next-category', [['Aa', 'Ab', 'Ac'], ['Ba', 'Bb'], ['Ca']],
['Aa', 'Ba', 'Ca', 'Aa']),
['Aa', 'Ba', 'Ca', 'Aa']),
('prev-category', [['Aa', 'Ab', 'Ac'], ['Ba', 'Bb'], ['Ca']],
['Ca', 'Ba', 'Aa', 'Ca']),
['Ca', 'Ba', 'Aa', 'Ca']),
('next-category', [[], ['Ba', 'Bb']], ['Ba', None, None]),
('prev-category', [[], ['Ba', 'Bb']], ['Ba', None, None]),
('next-category', [[], [], ['Ca', 'Cb']], ['Ca', None, None]),
@ -170,8 +170,9 @@ def test_completion_item_focus_fetch(completionview, qtbot):
emitted.
"""
model = completionmodel.CompletionModel()
cat = mock.Mock(spec=['layoutChanged', 'layoutAboutToBeChanged',
'canFetchMore', 'fetchMore', 'rowCount', 'index', 'data'])
cat = mock.Mock(spec=[
'layoutChanged', 'layoutAboutToBeChanged', 'canFetchMore',
'fetchMore', 'rowCount', 'index', 'data'])
cat.canFetchMore = lambda *_: True
cat.rowCount = lambda *_: 2
cat.fetchMore = mock.Mock()

View File

@ -627,7 +627,7 @@ def test_window_completion(qtmodeltester, fake_web_tab, tabbed_browser_stubs,
_check_completions(model, {
'Windows': [
('0', 'window title - qutebrowser',
'GitHub, Wikipedia, DuckDuckGo'),
'GitHub, Wikipedia, DuckDuckGo'),
]
})
@ -642,11 +642,11 @@ def test_setting_option_completion(qtmodeltester, config_stub,
_check_completions(model, {
"Options": [
('aliases', 'Aliases for commands.', '{"q": "quit"}'),
('bindings.commands', 'Default keybindings',
('bindings.commands', 'Default keybindings', (
'{"normal": {"<ctrl+q>": "quit", "ZQ": "quit", '
'"I": "invalid", "d": "scroll down"}}'),
'"I": "invalid", "d": "scroll down"}}')),
('bindings.default', 'Default keybindings',
'{"normal": {"<ctrl+q>": "quit", "d": "tab-close"}}'),
'{"normal": {"<ctrl+q>": "quit", "d": "tab-close"}}'),
]
})

View File

@ -213,7 +213,7 @@ class TestYaml:
('%', 'While parsing', 'while scanning a directive'),
('global: 42', 'While loading data', "'global' object is not a dict"),
('foo: 42', 'While loading data',
"Toplevel object does not contain 'global' key"),
"Toplevel object does not contain 'global' key"),
('42', 'While loading data', "Toplevel object is not a dict"),
])
def test_invalid(self, yaml, config_tmpdir, line, text, exception):
@ -318,8 +318,9 @@ class TestConfigPyModules:
sys.path = old_path
def test_bind_in_module(self, confpy, qbmodulepy, tmpdir):
qbmodulepy.write('def run(config):',
' config.bind(",a", "message-info foo", mode="normal")')
qbmodulepy.write(
'def run(config):',
' config.bind(",a", "message-info foo", mode="normal")')
confpy.write_qbmodule()
confpy.read()
expected = {'normal': {',a': 'message-info foo'}}

View File

@ -143,11 +143,11 @@ class TestEarlyInit:
suffix = ' (autoconfig.yml)' if config_py else ''
if invalid_yaml == '42':
error = ("While loading data{}: Toplevel object is not a dict"
.format(suffix))
.format(suffix))
expected_errors.append(error)
elif invalid_yaml == 'wrong-type':
error = ("Error{}: Invalid value 'True' - expected a value of "
"type str but got bool.".format(suffix))
"type str but got bool.".format(suffix))
expected_errors.append(error)
elif invalid_yaml == 'unknown':
error = ("While loading options{}: Unknown option "

View File

@ -340,13 +340,13 @@ class TestBaseType:
@pytest.mark.parametrize('valid_values, completions', [
# Without description
(['foo', 'bar'],
[('foo', ''), ('bar', '')]),
[('foo', ''), ('bar', '')]),
# With description
([('foo', "foo desc"), ('bar', "bar desc")],
[('foo', "foo desc"), ('bar', "bar desc")]),
[('foo', "foo desc"), ('bar', "bar desc")]),
# With mixed description
([('foo', "foo desc"), 'bar'],
[('foo', "foo desc"), ('bar', "")]),
[('foo', "foo desc"), ('bar', "")]),
])
def test_complete_without_desc(self, klass, valid_values, completions):
"""Test complete with valid_values set without description."""
@ -489,9 +489,9 @@ class TestString:
@pytest.mark.parametrize('valid_values, expected', [
(configtypes.ValidValues('one', 'two'),
[('one', ''), ('two', '')]),
[('one', ''), ('two', '')]),
(configtypes.ValidValues(('1', 'one'), ('2', 'two')),
[('1', 'one'), ('2', 'two')]),
[('1', 'one'), ('2', 'two')]),
])
def test_complete_valid_values(self, klass, valid_values, expected):
assert klass(valid_values=valid_values).complete() == expected
@ -1853,14 +1853,14 @@ class TestProxy:
('system', configtypes.SYSTEM_PROXY),
('none', QNetworkProxy(QNetworkProxy.NoProxy)),
('socks://example.com/',
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')),
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')),
('socks5://foo:bar@example.com:2323',
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323,
'foo', 'bar')),
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323,
'foo', 'bar')),
('pac+http://example.com/proxy.pac',
pac.PACFetcher(QUrl('pac+http://example.com/proxy.pac'))),
pac.PACFetcher(QUrl('pac+http://example.com/proxy.pac'))),
('pac+file:///tmp/proxy.pac',
pac.PACFetcher(QUrl('pac+file:///tmp/proxy.pac'))),
pac.PACFetcher(QUrl('pac+file:///tmp/proxy.pac'))),
])
def test_to_py_valid(self, klass, val, expected):
actual = klass().to_py(val)

View File

@ -461,11 +461,11 @@ NEW_VERSION = str(ipc.PROTOCOL_VERSION + 1).encode('utf-8')
(b'{"valid json without args": true}\n', 'Missing args'),
(b'{"args": []}\n', 'Missing target_arg'),
(b'{"args": [], "target_arg": null, "protocol_version": ' + OLD_VERSION +
b'}\n', 'incompatible version'),
b'}\n', 'incompatible version'),
(b'{"args": [], "target_arg": null, "protocol_version": ' + NEW_VERSION +
b'}\n', 'incompatible version'),
b'}\n', 'incompatible version'),
(b'{"args": [], "target_arg": null, "protocol_version": "foo"}\n',
'invalid version'),
'invalid version'),
(b'{"args": [], "target_arg": null}\n', 'invalid version'),
])
def test_invalid_data(qtbot, ipc_server, connected_socket, caplog, data, msg):
@ -672,9 +672,9 @@ class TestSendOrListen:
@pytest.mark.parametrize('has_error, exc_name, exc_msg', [
(True, 'SocketError',
'Error while writing to running instance: Error string (error 0)'),
'Error while writing to running instance: Error string (error 0)'),
(False, 'AddressInUseError',
'Error while listening to IPC server: Error string (error 8)'),
'Error while listening to IPC server: Error string (error 8)'),
])
def test_address_in_use_error(self, qlocalserver_mock, qlocalsocket_mock,
stubs, caplog, args, has_error, exc_name,
@ -737,7 +737,7 @@ class TestSendOrListen:
'pre_text: ',
'post_text: Maybe another instance is running but frozen?',
('exception text: Error while listening to IPC server: Error '
'string (error 4)'),
'string (error 4)'),
]
assert caplog.records[-1].msg == '\n'.join(error_msgs)

View File

@ -106,7 +106,7 @@ class TestFullscreenNotification:
@pytest.mark.parametrize('bindings, text', [
({'<escape>': 'fullscreen --leave'},
"Press Escape to exit fullscreen."),
"Press Escape to exit fullscreen."),
({'<escape>': 'fullscreen'}, "Page is now fullscreen."),
({'a': 'fullscreen --leave'}, "Press a to exit fullscreen."),
({}, "Page is now fullscreen."),

View File

@ -157,13 +157,13 @@ def test_iter():
@pytest.mark.parametrize('rows, sort_by, sort_order, limit, result', [
([{"a": 2, "b": 5}, {"a": 1, "b": 6}, {"a": 3, "b": 4}], 'a', 'asc', 5,
[(1, 6), (2, 5), (3, 4)]),
[(1, 6), (2, 5), (3, 4)]),
([{"a": 2, "b": 5}, {"a": 1, "b": 6}, {"a": 3, "b": 4}], 'a', 'desc', 3,
[(3, 4), (2, 5), (1, 6)]),
[(3, 4), (2, 5), (1, 6)]),
([{"a": 2, "b": 5}, {"a": 1, "b": 6}, {"a": 3, "b": 4}], 'b', 'desc', 2,
[(1, 6), (2, 5)]),
[(1, 6), (2, 5)]),
([{"a": 2, "b": 5}, {"a": 1, "b": 6}, {"a": 3, "b": 4}], 'a', 'asc', -1,
[(1, 6), (2, 5), (3, 4)]),
[(1, 6), (2, 5), (3, 4)]),
])
def test_select(rows, sort_by, sort_order, limit, result):
table = sql.SqlTable('Foo', ['a', 'b'])

View File

@ -27,28 +27,22 @@ _samples = 'tests/unit/scripts/importer_sample'
def qm_expected(input_format):
"""Read expected quickmark-formatted output."""
with open(
os.path.join(_samples, input_format, 'quickmarks'),
'r',
encoding='utf-8') as f:
with open(os.path.join(_samples, input_format, 'quickmarks'),
'r', encoding='utf-8') as f:
return f.read()
def bm_expected(input_format):
"""Read expected bookmark-formatted output."""
with open(
os.path.join(_samples, input_format, 'bookmarks'),
'r',
encoding='utf-8') as f:
with open(os.path.join(_samples, input_format, 'bookmarks'),
'r', encoding='utf-8') as f:
return f.read()
def search_expected(input_format):
"""Read expected search-formatted (config.py) output."""
with open(
os.path.join(_samples, input_format, 'config_py'),
'r',
encoding='utf-8') as f:
with open(os.path.join(_samples, input_format, 'config_py'),
'r', encoding='utf-8') as f:
return f.read()

View File

@ -17,6 +17,7 @@
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Tests for qutebrowser.utils.qtutils."""
import io
@ -40,6 +41,7 @@ from qutebrowser.utils import qtutils, utils
import overflow_test_cases
# pylint: disable=bad-continuation
@pytest.mark.parametrize(['qversion', 'compiled', 'pyqt', 'version', 'exact',
'expected'], [
# equal versions
@ -61,6 +63,7 @@ import overflow_test_cases
# all up-to-date
('5.4.0', '5.4.0', '5.4.0', '5.4.0', False, True),
])
# pylint: enable=bad-continuation
def test_version_check(monkeypatch, qversion, compiled, pyqt, version, exact,
expected):
"""Test for version_check().

View File

@ -492,18 +492,14 @@ def test_filename_from_url(qurl, output):
(QUrl('qute://'), None),
(QUrl('qute://foobar'), None),
(QUrl('mailto:nobody'), None),
(QUrl('ftp://example.com/'),
('ftp', 'example.com', 21)),
(QUrl('ftp://example.com:2121/'),
('ftp', 'example.com', 2121)),
(QUrl('ftp://example.com/'), ('ftp', 'example.com', 21)),
(QUrl('ftp://example.com:2121/'), ('ftp', 'example.com', 2121)),
(QUrl('http://qutebrowser.org:8010/waterfall'),
('http', 'qutebrowser.org', 8010)),
(QUrl('https://example.com/'),
('https', 'example.com', 443)),
(QUrl('https://example.com:4343/'),
('https', 'example.com', 4343)),
('http', 'qutebrowser.org', 8010)),
(QUrl('https://example.com/'), ('https', 'example.com', 443)),
(QUrl('https://example.com:4343/'), ('https', 'example.com', 4343)),
(QUrl('http://user:password@qutebrowser.org/foo?bar=baz#fish'),
('http', 'qutebrowser.org', 80)),
('http', 'qutebrowser.org', 80)),
])
def test_host_tuple(qurl, tpl):
"""Test host_tuple().
@ -752,7 +748,7 @@ def test_data_url():
(QUrl('http://www.example.com/ä'), 'http://www.example.com/ä'),
# Unicode only in TLD (looks like Qt shows Punycode with рф...)
(QUrl('http://www.example.xn--p1ai'),
'(www.example.xn--p1ai) http://www.example.рф'),
'(www.example.xn--p1ai) http://www.example.рф'),
# https://bugreports.qt.io/browse/QTBUG-60364
pytest.param(QUrl('http://www.xn--80ak6aa92e.com'),
'(unparseable URL!) http://www.аррӏе.com',
@ -779,19 +775,19 @@ class TestProxyFromUrl:
@pytest.mark.parametrize('url, expected', [
('socks://example.com/',
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')),
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')),
('socks5://example.com',
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')),
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')),
('socks5://example.com:2342',
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2342)),
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2342)),
('socks5://foo@example.com',
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo')),
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo')),
('socks5://foo:bar@example.com',
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo',
'bar')),
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo',
'bar')),
('socks5://foo:bar@example.com:2323',
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323,
'foo', 'bar')),
QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323,
'foo', 'bar')),
('direct://', QNetworkProxy(QNetworkProxy.NoProxy)),
])
def test_proxy_from_url_valid(self, url, expected):

View File

@ -376,7 +376,7 @@ class TestKeyEventToString:
('<Control-x>', utils.KeyInfo(Qt.Key_X, Qt.ControlModifier, '')),
('<Meta-x>', utils.KeyInfo(Qt.Key_X, Qt.MetaModifier, '')),
('<Ctrl-Alt-y>',
utils.KeyInfo(Qt.Key_Y, Qt.ControlModifier | Qt.AltModifier, '')),
utils.KeyInfo(Qt.Key_Y, Qt.ControlModifier | Qt.AltModifier, '')),
('x', utils.KeyInfo(Qt.Key_X, Qt.NoModifier, 'x')),
('X', utils.KeyInfo(Qt.Key_X, Qt.ShiftModifier, 'X')),
('<Escape>', utils.KeyInfo(Qt.Key_Escape, Qt.NoModifier, '')),

View File

@ -467,12 +467,12 @@ def test_path_info(monkeypatch, equal):
equal: Whether system data / data and system config / config are equal.
"""
patches = {
'config': lambda auto=False:
'config': lambda auto=False: (
'AUTO CONFIG PATH' if auto and not equal
else 'CONFIG PATH',
'data': lambda system=False:
else 'CONFIG PATH'),
'data': lambda system=False: (
'SYSTEM DATA PATH' if system and not equal
else 'DATA PATH',
else 'DATA PATH'),
'cache': lambda: 'CACHE PATH',
'runtime': lambda: 'RUNTIME PATH',
}