Various code style improvements

This commit is contained in:
Florian Bruhin 2016-04-27 18:30:54 +02:00
parent fd20b46b33
commit 2a343cb3a1
50 changed files with 143 additions and 189 deletions

View File

@ -842,8 +842,8 @@ class CommandDispatcher:
log.misc.debug("{} contained: {!r}".format(target, text)) log.misc.debug("{} contained: {!r}".format(target, text))
text_urls = [u for u in text.split('\n') if u.strip()] text_urls = [u for u in text.split('\n') if u.strip()]
if (len(text_urls) > 1 and not urlutils.is_url(text_urls[0]) and if (len(text_urls) > 1 and not urlutils.is_url(text_urls[0]) and
urlutils.get_path_if_valid( urlutils.get_path_if_valid(text_urls[0],
text_urls[0], check_exists=True) is None): check_exists=True) is None):
text_urls = [text] text_urls = [text]
for i, text_url in enumerate(text_urls): for i, text_url in enumerate(text_urls):
if not window and i > 0: if not window and i > 0:
@ -1202,8 +1202,8 @@ class CommandDispatcher:
mhtml_: Download the current page and all assets as mhtml file. mhtml_: Download the current page and all assets as mhtml file.
""" """
if dest_old is not None: if dest_old is not None:
message.warning( message.warning(self._win_id,
self._win_id, ":download [url] [dest] is deprecated - use" ":download [url] [dest] is deprecated - use"
" download --dest [dest] [url]") " download --dest [dest] [url]")
if dest is not None: if dest is not None:
raise cmdexc.CommandError("Can't give two destinations for the" raise cmdexc.CommandError("Can't give two destinations for the"
@ -1260,8 +1260,8 @@ class CommandDispatcher:
frame = widget.page().currentFrame() frame = widget.page().currentFrame()
html = frame.toHtml() html = frame.toHtml()
lexer = pygments.lexers.HtmlLexer() lexer = pygments.lexers.HtmlLexer()
formatter = pygments.formatters.HtmlFormatter( formatter = pygments.formatters.HtmlFormatter(full=True,
full=True, linenos='table') linenos='table')
highlighted = pygments.highlight(html, lexer, formatter) highlighted = pygments.highlight(html, lexer, formatter)
current_url = self._current_url() current_url = self._current_url()
tab = self._tabbed_browser.tabopen(explicit=True) tab = self._tabbed_browser.tabopen(explicit=True)

View File

@ -49,10 +49,7 @@ ModelRole = usertypes.enum('ModelRole', ['item'], start=Qt.UserRole,
RetryInfo = collections.namedtuple('RetryInfo', ['request', 'manager']) RetryInfo = collections.namedtuple('RetryInfo', ['request', 'manager'])
DownloadPath = collections.namedtuple('DownloadPath', ['filename', 'question'])
DownloadPath = collections.namedtuple('DownloadPath', ['filename',
'question'])
# Remember the last used directory # Remember the last used directory
last_used_directory = None last_used_directory = None
@ -148,8 +145,7 @@ def ask_for_filename(suggested_filename, win_id, *, parent=None,
return DownloadPath(filename=download_dir(), question=None) return DownloadPath(filename=download_dir(), question=None)
encoding = sys.getfilesystemencoding() encoding = sys.getfilesystemencoding()
suggested_filename = utils.force_encoding(suggested_filename, suggested_filename = utils.force_encoding(suggested_filename, encoding)
encoding)
q = usertypes.Question(parent) q = usertypes.Question(parent)
q.text = "Save file to:" q.text = "Save file to:"
@ -461,8 +457,8 @@ class DownloadItem(QObject):
elif self.stats.percentage() is None: elif self.stats.percentage() is None:
return start return start
else: else:
return utils.interpolate_color( return utils.interpolate_color(start, stop,
start, stop, self.stats.percentage(), system) self.stats.percentage(), system)
@pyqtSlot() @pyqtSlot()
def cancel(self, remove_data=True): def cancel(self, remove_data=True):
@ -562,8 +558,8 @@ class DownloadItem(QObject):
txt = self._filename + " already exists. Overwrite?" txt = self._filename + " already exists. Overwrite?"
self._ask_confirm_question(txt) self._ask_confirm_question(txt)
# FIFO, device node, etc. Make sure we want to do this # FIFO, device node, etc. Make sure we want to do this
elif (os.path.exists(self._filename) and not elif (os.path.exists(self._filename) and
os.path.isdir(self._filename)): not os.path.isdir(self._filename)):
txt = (self._filename + " already exists and is a special file. " txt = (self._filename + " already exists and is a special file. "
"Write to this?") "Write to this?")
self._ask_confirm_question(txt) self._ask_confirm_question(txt)

View File

@ -611,8 +611,7 @@ class HintManager(QObject):
def _find_prevnext(self, frame, prev=False): def _find_prevnext(self, frame, prev=False):
"""Find a prev/next element in frame.""" """Find a prev/next element in frame."""
# First check for <link rel="prev(ious)|next"> # First check for <link rel="prev(ious)|next">
elems = frame.findAllElements( elems = frame.findAllElements(webelem.SELECTORS[webelem.Group.links])
webelem.SELECTORS[webelem.Group.links])
rel_values = ('prev', 'previous') if prev else ('next') rel_values = ('prev', 'previous') if prev else ('next')
for e in elems: for e in elems:
e = webelem.WebElementWrapper(e) e = webelem.WebElementWrapper(e)
@ -924,19 +923,20 @@ class HintManager(QObject):
} }
elem = self._context.elems[keystr].elem elem = self._context.elems[keystr].elem
if elem.webFrame() is None: if elem.webFrame() is None:
message.error(self._win_id, "This element has no webframe.", message.error(self._win_id,
"This element has no webframe.",
immediately=True) immediately=True)
return return
if self._context.target in elem_handlers: if self._context.target in elem_handlers:
handler = functools.partial( handler = functools.partial(elem_handlers[self._context.target],
elem_handlers[self._context.target], elem, self._context) elem, self._context)
elif self._context.target in url_handlers: elif self._context.target in url_handlers:
url = self._resolve_url(elem, self._context.baseurl) url = self._resolve_url(elem, self._context.baseurl)
if url is None: if url is None:
self._show_url_error() self._show_url_error()
return return
handler = functools.partial( handler = functools.partial(url_handlers[self._context.target],
url_handlers[self._context.target], url, self._context) url, self._context)
else: else:
raise ValueError("No suitable handler found!") raise ValueError("No suitable handler found!")
if not self._context.rapid: if not self._context.rapid:
@ -1041,13 +1041,11 @@ class WordHinter:
"text": str, "text": str,
} }
extractable_attrs = collections.defaultdict( extractable_attrs = collections.defaultdict(list, {
list, {
"IMG": ["alt", "title", "src"], "IMG": ["alt", "title", "src"],
"A": ["title", "href", "text"], "A": ["title", "href", "text"],
"INPUT": ["name"] "INPUT": ["name"]
} })
)
return (attr_extractors[attr](elem) return (attr_extractors[attr](elem)
for attr in extractable_attrs[elem.tagName()] for attr in extractable_attrs[elem.tagName()]
@ -1065,8 +1063,7 @@ class WordHinter:
yield candidate[match.start():match.end()].lower() yield candidate[match.start():match.end()].lower()
def any_prefix(self, hint, existing): def any_prefix(self, hint, existing):
return any(hint.startswith(e) or e.startswith(hint) return any(hint.startswith(e) or e.startswith(hint) for e in existing)
for e in existing)
def new_hint_for(self, elem, existing): def new_hint_for(self, elem, existing):
"""Return a hint for elem, not conflicting with the existing.""" """Return a hint for elem, not conflicting with the existing."""

View File

@ -343,12 +343,9 @@ class _Downloader:
item = download_manager.get(url, fileobj=_NoCloseBytesIO(), item = download_manager.get(url, fileobj=_NoCloseBytesIO(),
auto_remove=True) auto_remove=True)
self.pending_downloads.add((url, item)) self.pending_downloads.add((url, item))
item.finished.connect( item.finished.connect(functools.partial(self._finished, url, item))
functools.partial(self._finished, url, item)) item.error.connect(functools.partial(self._error, url, item))
item.error.connect( item.cancelled.connect(functools.partial(self._error, url, item))
functools.partial(self._error, url, item))
item.cancelled.connect(
functools.partial(self._error, url, item))
def _finished(self, url, item): def _finished(self, url, item):
"""Callback when a single asset is downloaded. """Callback when a single asset is downloaded.

View File

@ -276,8 +276,7 @@ class NetworkManager(QNetworkAccessManager):
if user is None: if user is None:
# netrc check failed # netrc check failed
answer = self._ask( answer = self._ask("Username ({}):".format(authenticator.realm()),
"Username ({}):".format(authenticator.realm()),
mode=usertypes.PromptMode.user_pwd, mode=usertypes.PromptMode.user_pwd,
owner=reply) owner=reply)
if answer is not None: if answer is not None:
@ -295,8 +294,9 @@ class NetworkManager(QNetworkAccessManager):
authenticator.setUser(user) authenticator.setUser(user)
authenticator.setPassword(password) authenticator.setPassword(password)
else: else:
answer = self._ask("Proxy username ({}):".format( answer = self._ask(
authenticator.realm()), mode=usertypes.PromptMode.user_pwd) "Proxy username ({}):".format(authenticator.realm()),
mode=usertypes.PromptMode.user_pwd)
if answer is not None: if answer is not None:
authenticator.setUser(answer.user) authenticator.setUser(answer.user)
authenticator.setPassword(answer.password) authenticator.setPassword(answer.password)

View File

@ -109,13 +109,13 @@ class QuteSchemeHandler(schemehandler.SchemeHandler):
request, str(e), QNetworkReply.ContentNotFoundError, request, str(e), QNetworkReply.ContentNotFoundError,
self.parent()) self.parent())
except QuteSchemeError as e: except QuteSchemeError as e:
return networkreply.ErrorNetworkReply( return networkreply.ErrorNetworkReply(request, e.errorstring,
request, e.errorstring, e.error, self.parent()) e.error, self.parent())
mimetype, _encoding = mimetypes.guess_type(request.url().fileName()) mimetype, _encoding = mimetypes.guess_type(request.url().fileName())
if mimetype is None: if mimetype is None:
mimetype = 'text/html' mimetype = 'text/html'
return networkreply.FixedDataNetworkReply( return networkreply.FixedDataNetworkReply(request, data, mimetype,
request, data, mimetype, self.parent()) self.parent())
class JSBridge(QObject): class JSBridge(QObject):

View File

@ -51,9 +51,8 @@ def generate_pdfjs_page(url):
""" """
viewer = get_pdfjs_res('web/viewer.html').decode('utf-8') viewer = get_pdfjs_res('web/viewer.html').decode('utf-8')
script = _generate_pdfjs_script(url) script = _generate_pdfjs_script(url)
html_page = viewer.replace( html_page = viewer.replace('</body>',
'</body>', '</body><script>{}</script>'.format(script) '</body><script>{}</script>'.format(script))
)
return html_page return html_page

View File

@ -154,8 +154,7 @@ class QuickmarkManager(UrlMarkManager):
try: try:
key, url = line.rsplit(maxsplit=1) key, url = line.rsplit(maxsplit=1)
except ValueError: except ValueError:
message.error('current', "Invalid quickmark '{}'".format( message.error('current', "Invalid quickmark '{}'".format(line))
line))
else: else:
self.marks[key] = url self.marks[key] = url

View File

@ -157,8 +157,7 @@ class WebElementWrapper(collections.abc.MutableMapping):
def _check_vanished(self): def _check_vanished(self):
"""Raise an exception if the element vanished (is null).""" """Raise an exception if the element vanished (is null)."""
if self._elem.isNull(): if self._elem.isNull():
raise IsNullError('Element {} vanished!'.format( raise IsNullError('Element {} vanished!'.format(self._elem))
self._elem))
def is_visible(self, mainframe): def is_visible(self, mainframe):
"""Check whether the element is currently visible on the screen. """Check whether the element is currently visible on the screen.
@ -421,8 +420,7 @@ def is_visible(elem, mainframe):
else: else:
# We got an invalid rectangle (width/height 0/0 probably), but this # We got an invalid rectangle (width/height 0/0 probably), but this
# can still be a valid link. # can still be a valid link.
visible_on_screen = mainframe_geometry.contains( visible_on_screen = mainframe_geometry.contains(elem_rect.topLeft())
elem_rect.topLeft())
# Then check if it's visible in its frame if it's not in the main # Then check if it's visible in its frame if it's not in the main
# frame. # frame.
elem_frame = elem.webFrame() elem_frame = elem.webFrame()

View File

@ -184,8 +184,8 @@ class _POSIXUserscriptRunner(_BaseUserscriptRunner):
# pylint: disable=no-member,useless-suppression # pylint: disable=no-member,useless-suppression
os.mkfifo(self._filepath) os.mkfifo(self._filepath)
except OSError as e: except OSError as e:
message.error(self._win_id, "Error while creating FIFO: {}".format( message.error(self._win_id,
e)) "Error while creating FIFO: {}".format(e))
return return
self._reader = _QtFIFOReader(self._filepath) self._reader = _QtFIFOReader(self._filepath)
@ -338,8 +338,8 @@ def run(cmd, *args, win_id, env, verbose=False):
commandrunner = runners.CommandRunner(win_id, tabbed_browser) commandrunner = runners.CommandRunner(win_id, tabbed_browser)
runner = UserscriptRunner(win_id, tabbed_browser) runner = UserscriptRunner(win_id, tabbed_browser)
runner.got_cmd.connect( runner.got_cmd.connect(
lambda cmd: log.commands.debug("Got userscript command: {}".format( lambda cmd:
cmd))) log.commands.debug("Got userscript command: {}".format(cmd)))
runner.got_cmd.connect(commandrunner.run_safely) runner.got_cmd.connect(commandrunner.run_safely)
user_agent = config.get('network', 'user-agent') user_agent = config.get('network', 'user-agent')
if user_agent is not None: if user_agent is not None:

View File

@ -201,8 +201,7 @@ class CompletionView(QTreeView):
idx = self._next_idx(prev) idx = self._next_idx(prev)
qtutils.ensure_valid(idx) qtutils.ensure_valid(idx)
self.selectionModel().setCurrentIndex( self.selectionModel().setCurrentIndex(
idx, QItemSelectionModel.ClearAndSelect | idx, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)
QItemSelectionModel.Rows)
def set_model(self, model): def set_model(self, model):
"""Switch completion to a new model. """Switch completion to a new model.

View File

@ -75,8 +75,7 @@ class UrlCompletionModel(base.BaseCompletionModel):
history = utils.newest_slice(self._history, self._max_history) history = utils.newest_slice(self._history, self._max_history)
for entry in history: for entry in history:
self._add_history_entry(entry) self._add_history_entry(entry)
self._history.add_completion_item.connect( self._history.add_completion_item.connect(self.on_history_item_added)
self.on_history_item_added)
objreg.get('config').changed.connect(self.reformat_timestamps) objreg.get('config').changed.connect(self.reformat_timestamps)

View File

@ -173,8 +173,8 @@ class BaseType:
if self.valid_values is not None: if self.valid_values is not None:
if value not in self.valid_values: if value not in self.valid_values:
raise configexc.ValidationError( raise configexc.ValidationError(
value, "valid values: {}".format(', '.join( value,
self.valid_values))) "valid values: {}".format(', '.join(self.valid_values)))
else: else:
raise NotImplementedError("{} does not implement validate.".format( raise NotImplementedError("{} does not implement validate.".format(
self.__class__.__name__)) self.__class__.__name__))
@ -263,8 +263,8 @@ class String(BaseType):
if self.valid_values is not None: if self.valid_values is not None:
if value not in self.valid_values: if value not in self.valid_values:
raise configexc.ValidationError( raise configexc.ValidationError(
value, "valid values: {}".format(', '.join( value,
self.valid_values))) "valid values: {}".format(', '.join(self.valid_values)))
if self.forbidden is not None and any(c in value if self.forbidden is not None and any(c in value
for c in self.forbidden): for c in self.forbidden):
@ -1147,8 +1147,8 @@ class Proxy(BaseType):
return return
url = QUrl(value) url = QUrl(value)
if not url.isValid(): if not url.isValid():
raise configexc.ValidationError(value, "invalid url, {}".format( raise configexc.ValidationError(
url.errorString())) value, "invalid url, {}".format(url.errorString()))
elif url.scheme() not in self.PROXY_TYPES: elif url.scheme() not in self.PROXY_TYPES:
raise configexc.ValidationError(value, "must be a proxy URL " raise configexc.ValidationError(value, "must be a proxy URL "
"(http://... or socks://...) or " "(http://... or socks://...) or "
@ -1211,8 +1211,8 @@ class SearchEngineUrl(BaseType):
url = QUrl(value.replace('{}', 'foobar')) url = QUrl(value.replace('{}', 'foobar'))
if not url.isValid(): if not url.isValid():
raise configexc.ValidationError(value, "invalid url, {}".format( raise configexc.ValidationError(
url.errorString())) value, "invalid url, {}".format(url.errorString()))
class FuzzyUrl(BaseType): class FuzzyUrl(BaseType):

View File

@ -208,8 +208,8 @@ class ValueList(Section):
def dump_userconfig(self): def dump_userconfig(self):
changed = [] changed = []
mapping = collections.ChainMap( mapping = collections.ChainMap(self.layers['temp'],
self.layers['temp'], self.layers['conf']) self.layers['conf'])
for k, v in mapping.items(): for k, v in mapping.items():
try: try:
if v.value() != self.layers['default'][k].value(): if v.value() != self.layers['default'][k].value():

View File

@ -341,8 +341,7 @@ class BaseKeyParser(QObject):
elif self._supports_chains: elif self._supports_chains:
self.bindings[key] = cmd self.bindings[key] = cmd
elif self._warn_on_keychains: elif self._warn_on_keychains:
log.keyboard.warning( log.keyboard.warning("Ignoring keychain '{}' in mode '{}' because "
"Ignoring keychain '{}' in mode '{}' because "
"keychains are not supported there." "keychains are not supported there."
.format(key, modename)) .format(key, modename))

View File

@ -175,8 +175,7 @@ class ModeManager(QObject):
if handled: if handled:
filter_this = True filter_this = True
elif (parser.passthrough or elif (parser.passthrough or self._forward_unbound_keys == 'all' or
self._forward_unbound_keys == 'all' or
(self._forward_unbound_keys == 'auto' and is_non_alnum)): (self._forward_unbound_keys == 'auto' and is_non_alnum)):
filter_this = False filter_this = False
else: else:
@ -191,8 +190,8 @@ class ModeManager(QObject):
"passthrough: {}, is_non_alnum: {} --> " "passthrough: {}, is_non_alnum: {} --> "
"filter: {} (focused: {!r})".format( "filter: {} (focused: {!r})".format(
handled, self._forward_unbound_keys, handled, self._forward_unbound_keys,
parser.passthrough, is_non_alnum, parser.passthrough, is_non_alnum, filter_this,
filter_this, focus_widget)) focus_widget))
return filter_this return filter_this
def _eventFilter_keyrelease(self, event): def _eventFilter_keyrelease(self, event):

View File

@ -183,10 +183,6 @@ class MainWindow(QWidget):
if config.get('ui', 'hide-mouse-cursor'): if config.get('ui', 'hide-mouse-cursor'):
self.setCursor(Qt.BlankCursor) self.setCursor(Qt.BlankCursor)
#self.retranslateUi(MainWindow)
#self.tabWidget.setCurrentIndex(0)
#QtCore.QMetaObject.connectSlotsByName(MainWindow)
objreg.get("app").new_window.emit(self) objreg.get("app").new_window.emit(self)
def __repr__(self): def __repr__(self):

View File

@ -515,9 +515,9 @@ class TabBarStyle(QCommonStyle):
self._style = style self._style = style
for method in ('drawComplexControl', 'drawItemPixmap', for method in ('drawComplexControl', 'drawItemPixmap',
'generatedIconPixmap', 'hitTestComplexControl', 'generatedIconPixmap', 'hitTestComplexControl',
'itemPixmapRect', 'itemTextRect', 'itemPixmapRect', 'itemTextRect', 'polish', 'styleHint',
'polish', 'styleHint', 'subControlRect', 'unpolish', 'subControlRect', 'unpolish', 'drawItemText',
'drawItemText', 'sizeFromContents', 'drawPrimitive'): 'sizeFromContents', 'drawPrimitive'):
target = getattr(self._style, method) target = getattr(self._style, method)
setattr(self, method, functools.partial(target)) setattr(self, method, functools.partial(target))
super().__init__() super().__init__()

View File

@ -255,8 +255,7 @@ class _CrashDialog(QDialog):
except Exception: except Exception:
self._crash_info.append(("Config", traceback.format_exc())) self._crash_info.append(("Config", traceback.format_exc()))
try: try:
self._crash_info.append( self._crash_info.append(("Environment", _get_environment_vars()))
("Environment", _get_environment_vars()))
except Exception: except Exception:
self._crash_info.append(("Environment", traceback.format_exc())) self._crash_info.append(("Environment", traceback.format_exc()))
@ -283,8 +282,8 @@ class _CrashDialog(QDialog):
def _get_paste_title(self): def _get_paste_title(self):
"""Get a title for the paste.""" """Get a title for the paste."""
desc = self._get_paste_title_desc() desc = self._get_paste_title_desc()
title = "qute {} {}".format( title = "qute {} {}".format(qutebrowser.__version__,
qutebrowser.__version__, self._get_error_type()) self._get_error_type())
if desc: if desc:
title += ' {}'.format(desc) title += ' {}'.format(desc)
return title return title
@ -466,8 +465,7 @@ class ExceptionCrashDialog(_CrashDialog):
self._crash_info.append( self._crash_info.append(
("Debug log", log.ram_handler.dump_log())) ("Debug log", log.ram_handler.dump_log()))
except Exception: except Exception:
self._crash_info.append( self._crash_info.append(("Debug log", traceback.format_exc()))
("Debug log", traceback.format_exc()))
@pyqtSlot() @pyqtSlot()
def finish(self): def finish(self):

View File

@ -314,8 +314,8 @@ class SignalHandler(QObject):
for fd in (read_fd, write_fd): for fd in (read_fd, write_fd):
flags = fcntl.fcntl(fd, fcntl.F_GETFL) flags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
self._notifier = QSocketNotifier( self._notifier = QSocketNotifier(read_fd, QSocketNotifier.Read,
read_fd, QSocketNotifier.Read, self) self)
self._notifier.activated.connect(self.handle_signal_wakeup) self._notifier.activated.connect(self.handle_signal_wakeup)
self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd) self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd)
else: else:
@ -369,8 +369,7 @@ class SignalHandler(QObject):
signal.signal(signal.SIGINT, self.interrupt_forcefully) signal.signal(signal.SIGINT, self.interrupt_forcefully)
signal.signal(signal.SIGTERM, self.interrupt_forcefully) signal.signal(signal.SIGTERM, self.interrupt_forcefully)
# Signals can arrive anywhere, so we do this in the main thread # Signals can arrive anywhere, so we do this in the main thread
self._log_later( self._log_later("SIGINT/SIGTERM received, shutting down!",
"SIGINT/SIGTERM received, shutting down!",
"Do the same again to forcefully quit.") "Do the same again to forcefully quit.")
QTimer.singleShot(0, functools.partial( QTimer.singleShot(0, functools.partial(
self._quitter.shutdown, 128 + signum)) self._quitter.shutdown, 128 + signum))
@ -385,8 +384,7 @@ class SignalHandler(QObject):
signal.signal(signal.SIGINT, self.interrupt_really_forcefully) signal.signal(signal.SIGINT, self.interrupt_really_forcefully)
signal.signal(signal.SIGTERM, self.interrupt_really_forcefully) signal.signal(signal.SIGTERM, self.interrupt_really_forcefully)
# Signals can arrive anywhere, so we do this in the main thread # Signals can arrive anywhere, so we do this in the main thread
self._log_later( self._log_later("Forceful quit requested, goodbye cruel world!",
"Forceful quit requested, goodbye cruel world!",
"Do the same again to quit with even more force.") "Do the same again to quit with even more force.")
QTimer.singleShot(0, functools.partial(self._app.exit, 128 + signum)) QTimer.singleShot(0, functools.partial(self._app.exit, 128 + signum))

View File

@ -293,8 +293,7 @@ class IPCServer(QObject):
try: try:
decoded = data.decode('utf-8') decoded = data.decode('utf-8')
except UnicodeDecodeError: except UnicodeDecodeError:
log.ipc.error("invalid utf-8: {}".format( log.ipc.error("invalid utf-8: {}".format(binascii.hexlify(data)))
binascii.hexlify(data)))
self._handle_invalid_data() self._handle_invalid_data()
return return
@ -455,8 +454,7 @@ def send_to_running_instance(socketname, command, target_arg, *,
if socket is None: if socket is None:
socket = QLocalSocket() socket = QLocalSocket()
if (legacy_name is not None and if legacy_name is not None and _has_legacy_server(legacy_name):
_has_legacy_server(legacy_name)):
name_to_use = legacy_name name_to_use = legacy_name
else: else:
name_to_use = socketname name_to_use = socketname

View File

@ -252,8 +252,8 @@ class log_time: # pylint: disable=invalid-name
assert self._started is not None assert self._started is not None
finished = datetime.datetime.now() finished = datetime.datetime.now()
delta = (finished - self._started).total_seconds() delta = (finished - self._started).total_seconds()
self._logger.debug( self._logger.debug("{} took {} seconds.".format(
"{} took {} seconds.".format(self._action.capitalize(), delta)) self._action.capitalize(), delta))
def __call__(self, func): def __call__(self, func):
@functools.wraps(func) @functools.wraps(func)
@ -293,8 +293,7 @@ def get_all_objects(start_obj=None):
pyqt_lines = [] pyqt_lines = []
_get_pyqt_objects(pyqt_lines, start_obj) _get_pyqt_objects(pyqt_lines, start_obj)
pyqt_lines = [' ' + e for e in pyqt_lines] pyqt_lines = [' ' + e for e in pyqt_lines]
pyqt_lines.insert(0, 'Qt objects - {} objects:'.format( pyqt_lines.insert(0, 'Qt objects - {} objects:'.format(len(pyqt_lines)))
len(pyqt_lines)))
output += [''] output += ['']
output += pyqt_lines output += pyqt_lines

View File

@ -387,9 +387,8 @@ def keyevent_to_string(e):
(Qt.ShiftModifier, 'Shift'), (Qt.ShiftModifier, 'Shift'),
]) ])
modifiers = (Qt.Key_Control, Qt.Key_Alt, Qt.Key_Shift, Qt.Key_Meta, modifiers = (Qt.Key_Control, Qt.Key_Alt, Qt.Key_Shift, Qt.Key_Meta,
Qt.Key_AltGr, Qt.Key_Super_L, Qt.Key_Super_R, Qt.Key_AltGr, Qt.Key_Super_L, Qt.Key_Super_R, Qt.Key_Hyper_L,
Qt.Key_Hyper_L, Qt.Key_Hyper_R, Qt.Key_Direction_L, Qt.Key_Hyper_R, Qt.Key_Direction_L, Qt.Key_Direction_R)
Qt.Key_Direction_R)
if e.key() in modifiers: if e.key() in modifiers:
# Only modifier pressed # Only modifier pressed
return None return None

View File

@ -257,9 +257,9 @@ def main_check_all():
for test_file, src_file in PERFECT_FILES: for test_file, src_file in PERFECT_FILES:
if test_file is None: if test_file is None:
continue continue
subprocess.check_call([sys.executable, '-m', 'py.test', '--cov', subprocess.check_call(
'qutebrowser', '--cov-report', 'xml', [sys.executable, '-m', 'py.test', '--cov', 'qutebrowser',
test_file]) '--cov-report', 'xml', test_file])
with open('coverage.xml', encoding='utf-8') as f: with open('coverage.xml', encoding='utf-8') as f:
messages = check(f, [(test_file, src_file)]) messages = check(f, [(test_file, src_file)])
os.remove('coverage.xml') os.remove('coverage.xml')

View File

@ -105,8 +105,7 @@ def whitelist_generator():
yield 'scripts.dev.pylint_checkers.modeline.process_module' yield 'scripts.dev.pylint_checkers.modeline.process_module'
for attr in ('_get_default_metavar_for_optional', for attr in ('_get_default_metavar_for_optional',
'_get_default_metavar_for_positional', '_get_default_metavar_for_positional', '_metavar_formatter'):
'_metavar_formatter'):
yield 'scripts.dev.src2asciidoc.UsageFormatter.' + attr yield 'scripts.dev.src2asciidoc.UsageFormatter.' + attr
@ -169,8 +168,7 @@ def run(files):
def main(): def main():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='*', parser.add_argument('files', nargs='*', default=['qutebrowser', 'scripts'])
default=['qutebrowser', 'scripts'])
args = parser.parse_args() args = parser.parse_args()
out = run(args.files) out = run(args.files)
for line in out: for line in out:

View File

@ -86,9 +86,8 @@ def needs_update(source, dest):
diffs = filecmp.dircmp(source, dest) diffs = filecmp.dircmp(source, dest)
ignored = get_ignored_files(source, diffs.left_only) ignored = get_ignored_files(source, diffs.left_only)
has_new_files = set(ignored) != set(diffs.left_only) has_new_files = set(ignored) != set(diffs.left_only)
return (has_new_files or diffs.right_only or return (has_new_files or diffs.right_only or diffs.common_funny or
diffs.common_funny or diffs.diff_files or diffs.diff_files or diffs.funny_files)
diffs.funny_files)
else: else:
return not filecmp.cmp(source, dest) return not filecmp.cmp(source, dest)

View File

@ -135,8 +135,7 @@ def parse(quteproc):
list_.append(Item(path=item_path, link=li.a['href'], list_.append(Item(path=item_path, link=li.a['href'],
text=str(li.a.string))) text=str(li.a.string)))
return Parsed(path=path, parent=parent, folders=folders, return Parsed(path=path, parent=parent, folders=folders, files=files)
files=files)
@pytest.fixture(scope='module') @pytest.fixture(scope='module')

View File

@ -195,8 +195,8 @@ class Process(QObject):
Should be used in a contextmanager. Should be used in a contextmanager.
""" """
blocker = pytestqt.plugin.SignalBlocker( blocker = pytestqt.plugin.SignalBlocker(timeout=timeout,
timeout=timeout, raising=raising) raising=raising)
blocker.connect(signal) blocker.connect(signal)
return blocker return blocker

View File

@ -93,8 +93,7 @@ class ExpectedRequest:
def __eq__(self, other): def __eq__(self, other):
if isinstance(other, (Request, ExpectedRequest)): if isinstance(other, (Request, ExpectedRequest)):
return (self.verb == other.verb and return self.verb == other.verb and self.path == other.path
self.path == other.path)
else: else:
return NotImplemented return NotImplemented

View File

@ -156,8 +156,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( monkeypatch.setattr('qutebrowser.utils.jinja.utils.resource_filename',
'qutebrowser.utils.jinja.utils.resource_filename',
lambda name: '/test path/foo.svg') lambda name: '/test path/foo.svg')
html = filescheme.dirbrowser_html(os.getcwd()) html = filescheme.dirbrowser_html(os.getcwd())

View File

@ -35,12 +35,10 @@ def handler():
class TestPDFJSHandler: class TestPDFJSHandler:
"""Test the qute://pdfjs endpoint.""" """Test the qute://pdfjs endpoint."""
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def fake_pdfjs(self, monkeypatch): def fake_pdfjs(self, monkeypatch):
def get_pdfjs_res(path): def get_pdfjs_res(path):
if path == '/existing/file': if path == '/existing/file':
return b'foobar' return b'foobar'

View File

@ -130,8 +130,7 @@ def test_purge_old_cookies(config_stub, fake_save_manager):
def test_save(config_stub, fake_save_manager, monkeypatch, qapp): def test_save(config_stub, fake_save_manager, monkeypatch, qapp):
"""Test that expired and session cookies are not saved.""" """Test that expired and session cookies are not saved."""
monkeypatch.setattr(lineparser, monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub)
'LineParser', LineparserSaveStub)
jar = cookies.CookieJar() jar = cookies.CookieJar()
jar._lineparser.data = [COOKIE1, COOKIE2, SESSION_COOKIE, EXPIRED_COOKIE] jar._lineparser.data = [COOKIE1, COOKIE2, SESSION_COOKIE, EXPIRED_COOKIE]
@ -147,24 +146,19 @@ def test_cookies_changed_emit(config_stub, fake_save_manager,
monkeypatch, qtbot): monkeypatch, qtbot):
"""Test that self.changed is emitted.""" """Test that self.changed is emitted."""
config_stub.data = CONFIG_COOKIES_ENABLED config_stub.data = CONFIG_COOKIES_ENABLED
monkeypatch.setattr(lineparser, monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub)
'LineParser', LineparserSaveStub)
jar = cookies.CookieJar() jar = cookies.CookieJar()
with qtbot.waitSignal(jar.changed): with qtbot.waitSignal(jar.changed):
config_stub.set('content', 'cookies-store', False) config_stub.set('content', 'cookies-store', False)
@pytest.mark.parametrize('store_cookies,empty', [ @pytest.mark.parametrize('store_cookies,empty', [(True, False), (False, True)])
(True, False), def test_cookies_changed(config_stub, fake_save_manager, monkeypatch, qtbot,
(False, True) store_cookies, empty):
])
def test_cookies_changed(config_stub, fake_save_manager, monkeypatch,
qtbot, store_cookies, empty):
"""Test that cookies are saved correctly.""" """Test that cookies are saved correctly."""
config_stub.data = CONFIG_COOKIES_ENABLED config_stub.data = CONFIG_COOKIES_ENABLED
monkeypatch.setattr(lineparser, monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub)
'LineParser', LineparserSaveStub)
jar = cookies.CookieJar() jar = cookies.CookieJar()
jar._lineparser.data = [COOKIE1, COOKIE2] jar._lineparser.data = [COOKIE1, COOKIE2]
jar.parse_cookies() jar.parse_cookies()

View File

@ -112,12 +112,10 @@ class TestConfigParser:
def test_interpolation_cross_section(self, objects): def test_interpolation_cross_section(self, objects):
"""Test setting an interpolated value from another section.""" """Test setting an interpolated value from another section."""
objects.cp.read_dict( objects.cp.read_dict({
{
'general': {'ignore-case': '${network:do-not-track}'}, 'general': {'ignore-case': '${network:do-not-track}'},
'network': {'do-not-track': 'false'}, 'network': {'do-not-track': 'false'},
} })
)
objects.cfg._from_cp(objects.cp) objects.cfg._from_cp(objects.cp)
assert not objects.cfg.get('general', 'ignore-case') assert not objects.cfg.get('general', 'ignore-case')
assert not objects.cfg.get('network', 'do-not-track') assert not objects.cfg.get('network', 'do-not-track')

View File

@ -36,8 +36,8 @@ TEXT = (r"At least Python 3.4 is required to run qutebrowser, but "
def test_python2(): def test_python2():
"""Run checkpyver with python 2.""" """Run checkpyver with python 2."""
try: try:
proc = subprocess.Popen(['python2', checkpyver.__file__, proc = subprocess.Popen(
'--no-err-windows'], ['python2', checkpyver.__file__, '--no-err-windows'],
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
stdout, stderr = proc.communicate() stdout, stderr = proc.communicate()

View File

@ -150,8 +150,8 @@ class Patcher:
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( self.monkeypatch.setattr('qutebrowser.utils.utils.qtutils.qVersion',
'qutebrowser.utils.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."""