Fix lint.

This commit is contained in:
Florian Bruhin 2015-04-05 20:30:31 +02:00
parent d3a92d505c
commit 9d44f777c0
24 changed files with 219 additions and 167 deletions

View File

@ -40,6 +40,7 @@ argument-rgx=[a-z_][a-z0-9_]{0,30}$
variable-rgx=[a-z_][a-z0-9_]{0,30}$
class-attribute-rgx=[A-Za-z_][A-Za-z0-9_]{1,30}$
inlinevar-rgx=[a-z_][a-z0-9_]*$
docstring-min-length=2
[FORMAT]
max-line-length=79

View File

@ -76,7 +76,7 @@ def check_spelling(target):
# Words which look better when splitted, but might need some fine tuning.
words |= {'keystrings', 'webelements', 'mouseevent', 'keysequence',
'normalmode', 'eventloops', 'sizehint', 'statemachine',
'metaobject', 'logrecord', 'monkeypatch', 'filetype'}
'metaobject', 'logrecord', 'filetype'}
seen = collections.defaultdict(list)
try:

View File

@ -105,8 +105,8 @@ class TestInline:
Some UAs use this filename in a subsequent "save" operation.
"""
header_checker.check_filename('inline; filename="foo.html"', 'foo.html',
expected_inline=True)
header_checker.check_filename('inline; filename="foo.html"',
'foo.html', expected_inline=True)
def test_inlwithfnattach(self, header_checker):
"""'inline', specifying a filename of "Not an attachment!".
@ -851,7 +851,7 @@ class TestEncodingFallback:
"filename=\"foo-ae.html\"", 'foo-ä.html')
def test_attfnboth3(self, header_checker):
"""'attachment', specifying an ambigious filename.
"""'attachment', specifying an ambiguous filename.
currency-sign=¤ in the simple RFC2231/5987 format, and euro-sign= in
RFC2231-with-continuations format.
@ -859,9 +859,9 @@ class TestEncodingFallback:
A UA that supports could pick either, or ignore both because of the
ambiguity.
"""
header_checker.check_ignored("attachment; "
"filename*0*=ISO-8859-15''euro-sign%3d%a4; "
"filename*=ISO-8859-1''currency-sign%3d%a4")
header_checker.check_ignored(
"attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4; "
"filename*=ISO-8859-1''currency-sign%3d%a4")
def test_attnewandfn(self, header_checker):
"""'attachment', specifying a new parameter "foobar".
@ -918,5 +918,3 @@ class TestOur:
"""'attachment' with double space in the filename."""
header_checker.check_filename('attachment; filename="foo bar.html"',
'foo bar.html')

View File

@ -59,4 +59,3 @@ class TestParseContentType:
mimetype, rest = http.parse_content_type(reply)
assert mimetype == 'image/example'
assert rest == ' encoding=UTF-8'

View File

@ -40,18 +40,20 @@ class TestSerializeHistory:
QUrl('http://original.url.example.com/'), 'arg',
user_data={'foo': 23, 'bar': 42}),
# From https://github.com/OtterBrowser/otter-browser/issues/709#issuecomment-74749471
Item(QUrl(
'http://github.com/OtterBrowser/24/134/2344/otter-browser/issues/709/'),
QUrl(
'http://github.com/OtterBrowser/24/134/2344/otter-browser/issues/709/'),
'Page not found | github',
user_data={'zoom': 149, 'scroll-pos': QPoint(0, 0)}),
Item(QUrl(
'https://mail.google.com/mail/u/0/#label/some+label/234lkjsd0932lkjf884jqwerdf4'),
QUrl(
'https://mail.google.com/mail/u/0/#label/some+label/234lkjsd0932lkjf884jqwerdf4'),
'"some label" - email@gmail.com - Gmail"',
user_data={'zoom': 120, 'scroll-pos': QPoint(0, 0)}),
Item(
QUrl('http://github.com/OtterBrowser/24/134/2344/otter-browser/'
'issues/709/'),
QUrl('http://github.com/OtterBrowser/24/134/2344/otter-browser/'
'issues/709/'),
'Page not found | github',
user_data={'zoom': 149, 'scroll-pos': QPoint(0, 0)}),
Item(
QUrl('https://mail.google.com/mail/u/0/#label/some+label/'
'234lkjsd0932lkjf884jqwerdf4'),
QUrl('https://mail.google.com/mail/u/0/#label/some+label/'
'234lkjsd0932lkjf884jqwerdf4'),
'"some label" - email@gmail.com - Gmail"',
user_data={'zoom': 120, 'scroll-pos': QPoint(0, 0)}),
]
@pytest.fixture(autouse=True)
@ -104,10 +106,11 @@ class TestSerializeHistory:
class TestSerializeHistorySpecial:
"""Tests for serialize() without items set up in setUp."""
"""Tests for serialize() without items set up in setup."""
@pytest.fixture(autouse=True)
def setUp(self, webpage):
def setup(self, webpage):
"""Set up the initial QWebPage for each test."""
self.page = webpage
self.history = self.page.history()
assert self.history.count() == 0
@ -134,5 +137,3 @@ class TestSerializeHistorySpecial:
assert self.history.count() == 0
assert self.history.currentItemIndex() == 0
assert not user_data

View File

@ -379,6 +379,7 @@ class TestIsEditable:
@pytest.yield_fixture
def stub_config(self, stubs):
"""Fixture to create a config stub with an input section."""
config = stubs.ConfigStub({'input': {}})
with mock.patch('qutebrowser.browser.webelem.config', new=config):
yield config
@ -557,5 +558,3 @@ class TestIsEditable:
"""Test div-element with codemirror class."""
elem = get_webelem(tagname='div', classes='foo CodeMirror-foo')
assert elem.is_editable()

View File

@ -66,21 +66,19 @@ class TestConfigParser:
def test_transformed_option_old(self):
"""Test a transformed option with the old name."""
# WORKAROUND for unknown PyQt bug
# Instance of 'str' has no 'name' member
self.cp.read_dict({'colors': {'tab.fg.odd': 'pink'}})
self.cfg._from_cp(self.cp)
assert self.cfg.get('colors', 'tabs.fg.odd').name() == \
QColor('pink').name()
actual = self.cfg.get('colors', 'tabs.fg.odd').name()
expected = QColor('pink').name()
assert actual == expected
def test_transformed_option_new(self):
"""Test a transformed section with the new name."""
# WORKAROUND for unknown PyQt bug
# Instance of 'str' has no 'name' member
self.cp.read_dict({'colors': {'tabs.fg.odd': 'pink'}})
self.cfg._from_cp(self.cp)
assert self.cfg.get('colors', 'tabs.fg.odd').name() == \
QColor('pink').name()
actual = self.cfg.get('colors', 'tabs.fg.odd').name()
expected = QColor('pink').name()
assert actual == expected
def test_invalid_value(self):
"""Test setting an invalid value."""

View File

@ -34,6 +34,7 @@ from qutebrowser.utils import debug, utils
class Font(QFont):
"""A QFont with a nicer repr()."""
def __repr__(self):
@ -59,6 +60,7 @@ class Font(QFont):
class NetworkProxy(QNetworkProxy):
"""A QNetworkProxy with a nicer repr()."""
def __repr__(self):
@ -69,11 +71,13 @@ class NetworkProxy(QNetworkProxy):
@pytest.fixture
def os_path(mocker):
"""Fixture that mocks and returns os.path from the configtypes module"""
return mocker.patch('qutebrowser.config.configtypes.os.path', autospec=True)
"""Fixture that mocks and returns os.path from the configtypes module."""
return mocker.patch('qutebrowser.config.configtypes.os.path',
autospec=True)
class TestValidValues:
"""Test ValidValues."""
def test_contains_without_desc(self):
@ -121,6 +125,7 @@ class TestValidValues:
class TestBaseType:
"""Test BaseType."""
@pytest.fixture(autouse=True)
@ -175,6 +180,7 @@ class TestBaseType:
class TestString:
"""Test String."""
def test_minlen_toosmall(self):
@ -269,6 +275,7 @@ class TestString:
class TestList:
"""Test List."""
@pytest.fixture(autouse=True)
@ -318,6 +325,7 @@ class TestList:
class TestBool:
"""Test Bool."""
TESTS = {True: ['1', 'yes', 'YES', 'true', 'TrUe', 'on'],
@ -367,6 +375,7 @@ class TestBool:
class TestInt:
"""Test Int."""
def test_minval_gt_maxval(self):
@ -444,6 +453,7 @@ class TestInt:
class TestIntList:
"""Test IntList."""
@pytest.fixture(autouse=True)
@ -483,6 +493,7 @@ class TestIntList:
class TestFloat:
"""Test Float."""
def test_minval_gt_maxval(self):
@ -570,6 +581,7 @@ class TestFloat:
class TestPerc:
"""Test Perc."""
@pytest.fixture(autouse=True)
@ -651,6 +663,7 @@ class TestPerc:
class TestPercList:
"""Test PercList."""
@pytest.fixture(autouse=True)
@ -731,6 +744,7 @@ class TestPercList:
class TestPercOrInt:
"""Test PercOrInt."""
@pytest.fixture(autouse=True)
@ -868,6 +882,7 @@ class TestPercOrInt:
class TestCommand:
"""Test Command."""
@pytest.fixture(autouse=True)
@ -924,8 +939,12 @@ class TestCommand:
class TestColorSystem:
"""Test ColorSystem."""
# https://bitbucket.org/logilab/pylint/issue/511/
# pylint: disable=undefined-variable
TESTS = {
'RGB': QColor.Rgb,
'rgb': QColor.Rgb,
@ -972,6 +991,7 @@ class TestColorSystem:
class TestQtColor:
"""Test QtColor."""
VALID = ['#123', '#112233', '#111222333', '#111122223333', 'red']
@ -1014,6 +1034,7 @@ class TestQtColor:
class TestCssColor(TestQtColor):
"""Test CssColor."""
VALID = TestQtColor.VALID + ['-foobar(42)']
@ -1039,6 +1060,7 @@ class TestCssColor(TestQtColor):
class TestQssColor(TestQtColor):
"""Test QssColor."""
VALID = TestQtColor.VALID + [
@ -1084,8 +1106,12 @@ FontDesc = collections.namedtuple('FontDesc',
class TestFont:
"""Test Font/QtFont."""
# https://bitbucket.org/logilab/pylint/issue/511/
# pylint: disable=undefined-variable
TESTS = {
# (style, weight, pointsize, pixelsize, family
'"Foobar Neue"':
@ -1144,7 +1170,8 @@ class TestFont:
t.validate('')
t2.validate('')
@pytest.mark.parametrize('val, attr', itertools.product(TESTS, ['t', 't2']))
@pytest.mark.parametrize('val, attr',
itertools.product(TESTS, ['t', 't2']))
def test_validate_valid(self, val, attr):
"""Test validate with valid values."""
getattr(self, attr).validate(val)
@ -1183,6 +1210,7 @@ class TestFont:
class TestFontFamily:
"""Test FontFamily."""
TESTS = ['"Foobar Neue"', 'inconsolatazi4', 'Foobar']
@ -1234,6 +1262,7 @@ class TestFontFamily:
class TestRegex:
"""Test Regex."""
@pytest.fixture(autouse=True)
@ -1269,6 +1298,7 @@ class TestRegex:
class TestRegexList:
"""Test RegexList."""
@pytest.fixture(autouse=True)
@ -1310,13 +1340,13 @@ class TestRegexList:
class TestFile:
"""Test File."""
@pytest.fixture(autouse=True)
def setup(self):
self.t = configtypes.File()
def test_validate_empty(self):
"""Test validate with empty string and none_ok = False."""
with pytest.raises(configexc.ValidationError):
@ -1376,6 +1406,7 @@ class TestFile:
class TestDirectory:
"""Test Directory."""
@pytest.fixture(autouse=True)
@ -1454,6 +1485,7 @@ class TestDirectory:
class TestWebKitByte:
"""Test WebKitBytes."""
@pytest.fixture(autouse=True)
@ -1528,6 +1560,7 @@ class TestWebKitByte:
class TestWebKitBytesList:
"""Test WebKitBytesList."""
@pytest.fixture(autouse=True)
@ -1599,6 +1632,7 @@ class TestWebKitBytesList:
class TestShellCommand:
"""Test ShellCommand."""
@pytest.fixture(autouse=True)
@ -1649,6 +1683,7 @@ class TestShellCommand:
class TestProxy:
"""Test Proxy."""
@pytest.fixture(autouse=True)
@ -1697,11 +1732,12 @@ class TestProxy:
def test_complete(self):
"""Test complete."""
assert self.t.complete() == \
[('system', "Use the system wide proxy."),
('none', "Don't use any proxy"),
('http://', 'HTTP proxy URL'),
('socks://', 'SOCKS proxy URL')]
actual = self.t.complete()
expected = [('system', "Use the system wide proxy."),
('none', "Don't use any proxy"),
('http://', 'HTTP proxy URL'),
('socks://', 'SOCKS proxy URL')]
assert actual == expected
def test_transform_empty(self):
"""Test transform with an empty value."""
@ -1713,51 +1749,53 @@ class TestProxy:
def test_transform_none(self):
"""Test transform with no proxy."""
assert NetworkProxy(self.t.transform('none')) == \
NetworkProxy(QNetworkProxy.NoProxy)
actual = NetworkProxy(self.t.transform('none'))
expected = NetworkProxy(QNetworkProxy.NoProxy)
assert actual == expected
def test_transform_socks(self):
"""Test transform with a socks proxy."""
proxy = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')
val = NetworkProxy(self.t.transform('socks://example.com/'))
assert proxy == val
actual = NetworkProxy(self.t.transform('socks://example.com/'))
expected = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')
assert actual == expected
def test_transform_socks5(self):
"""Test transform with a socks5 proxy."""
proxy = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')
val = NetworkProxy(self.t.transform('socks5://example.com'))
assert proxy == val
actual = NetworkProxy(self.t.transform('socks5://example.com'))
expected = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')
assert actual == expected
def test_transform_http_port(self):
"""Test transform with a http proxy with set port."""
proxy = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2342)
val = NetworkProxy(self.t.transform('socks5://example.com:2342'))
assert proxy == val
actual = NetworkProxy(self.t.transform('socks5://example.com:2342'))
expected = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2342)
assert actual == expected
def test_transform_socks_user(self):
"""Test transform with a socks proxy with set user."""
proxy = NetworkProxy(
actual = NetworkProxy(self.t.transform('socks5://foo@example.com'))
expected = NetworkProxy(
QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo')
val = NetworkProxy(self.t.transform('socks5://foo@example.com'))
assert proxy == val
assert actual == expected
def test_transform_socks_user_password(self):
"""Test transform with a socks proxy with set user/password."""
proxy = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0,
'foo', 'bar')
val = NetworkProxy(self.t.transform('socks5://foo:bar@example.com'))
assert proxy == val
actual = NetworkProxy(self.t.transform('socks5://foo:bar@example.com'))
expected = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0,
'foo', 'bar')
assert actual == expected
def test_transform_socks_user_password_port(self):
"""Test transform with a socks proxy with set port/user/password."""
proxy = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323,
'foo', 'bar')
val = NetworkProxy(
actual = NetworkProxy(
self.t.transform('socks5://foo:bar@example.com:2323'))
assert proxy == val
expected = NetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323,
'foo', 'bar')
assert actual == expected
class TestSearchEngineName:
"""Test SearchEngineName."""
@pytest.fixture(autouse=True)
@ -1784,6 +1822,7 @@ class TestSearchEngineName:
class TestSearchEngineUrl:
"""Test SearchEngineUrl."""
@pytest.fixture(autouse=True)
@ -1824,6 +1863,7 @@ class TestSearchEngineUrl:
class TestFuzzyUrl:
"""Test FuzzyUrl."""
@pytest.fixture(autouse=True)
@ -1868,6 +1908,7 @@ class TestFuzzyUrl:
class TestUserStyleSheet:
"""Test UserStyleSheet."""
@pytest.fixture(autouse=True)
@ -1906,8 +1947,12 @@ class TestUserStyleSheet:
class TestAutoSearch:
"""Test AutoSearch."""
# https://bitbucket.org/logilab/pylint/issue/511/
# pylint: disable=undefined-variable
TESTS = {
'naive': ['naive', 'NAIVE'] + TestBool.TESTS[True],
'dns': ['dns', 'DNS'],
@ -1929,9 +1974,8 @@ class TestAutoSearch:
t = configtypes.AutoSearch(none_ok=True)
t.validate('')
@pytest.mark.parametrize('val',
[val for vallist in TESTS.values() for val in
vallist])
@pytest.mark.parametrize('val', [val for vallist in TESTS.values()
for val in vallist])
def test_validate_valid(self, val):
"""Test validate with valid values."""
self.t.validate(val)
@ -1943,9 +1987,8 @@ class TestAutoSearch:
self.t.validate(val)
@pytest.mark.parametrize('out, inp',
[(out, inp) for (out, inputs) in TESTS.items() for
inp in inputs]
)
[(out, inp) for (out, inputs) in TESTS.items()
for inp in inputs])
def test_transform(self, out, inp):
"""Test transform with all values."""
assert self.t.transform(inp) == out
@ -1956,8 +1999,12 @@ class TestAutoSearch:
class TestIgnoreCase:
"""Test IgnoreCase."""
# https://bitbucket.org/logilab/pylint/issue/511/
# pylint: disable=undefined-variable
TESTS = {
'smart': ['smart', 'SMART'],
True: TestBool.TESTS[True],
@ -1993,9 +2040,8 @@ class TestIgnoreCase:
self.t.validate(val)
@pytest.mark.parametrize('out, inp',
[(out, inp) for (out, inputs) in TESTS.items() for
inp in inputs]
)
[(out, inp) for (out, inputs) in TESTS.items()
for inp in inputs])
def test_transform(self, out, inp):
"""Test transform with all values."""
assert self.t.transform(inp) == out
@ -2006,6 +2052,7 @@ class TestIgnoreCase:
class TestEncoding:
"""Test Encoding."""
@pytest.fixture(autouse=True)
@ -2042,6 +2089,7 @@ class TestEncoding:
class TestUrlList:
"""Test UrlList."""
@pytest.fixture(autouse=True)
@ -2079,14 +2127,15 @@ class TestUrlList:
def test_transform_single(self):
"""Test transform with a single value."""
actual = self.t.transform('http://qutebrowser.org/')
expected = [QUrl('http://qutebrowser.org/')]
assert self.t.transform('http://qutebrowser.org/') == expected
assert actual == expected
def test_transform_more(self):
"""Test transform with multiple values."""
assert (
self.t.transform('http://qutebrowser.org/,http://heise.de/') ==
[QUrl('http://qutebrowser.org/'), QUrl('http://heise.de/')])
actual = self.t.transform('http://qutebrowser.org/,http://heise.de/')
expected = [QUrl('http://qutebrowser.org/'), QUrl('http://heise.de/')]
assert actual == expected
def test_transform_empty(self):
"""Test transform with an empty value."""
@ -2094,6 +2143,7 @@ class TestUrlList:
class TestFormatString:
"""Test FormatString."""
@pytest.fixture(autouse=True)
@ -2134,6 +2184,7 @@ class TestFormatString:
class TestUserAgent:
"""Test UserAgent."""
@pytest.fixture(autouse=True)

View File

@ -24,27 +24,24 @@ import pytest
@pytest.fixture(scope='session', autouse=True)
def app_and_logging(qapp):
"""
Initializes our logging system and ensures that a QApplication is created
and used by all tests.
"""Initialize a QApplication and logging.
This ensures that a QApplication is created and used by all tests.
"""
from log import init
init()
@pytest.fixture(scope='session')
def stubs():
"""
Provides access to stub objects useful for testing.
"""
"""Provide access to stub objects useful for testing."""
import stubs
return stubs
@pytest.fixture(scope='session')
def unicode_encode_err():
"""Provide a fake UnicodeEncodeError exception."""
return UnicodeEncodeError('ascii', # codec
'', # object
0, # start
@ -66,9 +63,7 @@ def webpage():
@pytest.fixture
def fake_keyevent_factory():
"""
Fixture that when called will return a mock instance of a QKeyEvent.
"""
"""Fixture that when called will return a mock instance of a QKeyEvent."""
from unittest import mock
from PyQt5.QtGui import QKeyEvent
@ -80,4 +75,4 @@ def fake_keyevent_factory():
evtmock.text.return_value = text
return evtmock
return fake_keyevent
return fake_keyevent

View File

@ -44,9 +44,7 @@ BINDINGS = {'test': {'<Ctrl-a>': 'ctrla',
@pytest.yield_fixture
def fake_keyconfig():
"""
Creates a mock of a KeyConfiguration and registers it into objreg.
"""
"""Create a mock of a KeyConfiguration and register it into objreg."""
fake_keyconfig = mock.Mock(spec=['get_bindings_for'])
fake_keyconfig.get_bindings_for.side_effect = lambda s: BINDINGS[s]
objreg.register('key-config', fake_keyconfig)
@ -56,9 +54,7 @@ def fake_keyconfig():
@pytest.fixture
def mock_timer(mocker, stubs):
"""Mocks the QTimer class used by the
"qutebrowser.keyinput.basekeyparser.usertypes" module with a stub version.
"""
"""Mock the Timer class used by the usertypes module with a stub."""
mocker.patch('qutebrowser.keyinput.basekeyparser.usertypes.Timer',
new=stubs.FakeTimer)
@ -211,12 +207,12 @@ class TestKeyChain:
assert self.kp._keystring == ''
def test_ambiguous_keychain(self, fake_keyevent_factory, mocker, stubs):
"""Test ambigious keychain."""
"""Test ambiguous keychain."""
mocker.patch('qutebrowser.keyinput.basekeyparser.config',
new=stubs.ConfigStub(CONFIG))
timer = self.kp._ambiguous_timer
assert not timer.isActive()
# We start with 'a' where the keychain gives us an ambigious result.
# We start with 'a' where the keychain gives us an ambiguous result.
# Then we check if the timer has been set up correctly
self.kp.handle(fake_keyevent_factory(Qt.Key_A, text='a'))
assert not self.kp.execute.called

View File

@ -92,4 +92,3 @@ class TestsNormalKeyParser:
assert not self.kp.execute.called
assert self.kp._keystring == ''
keystring_updated_mock.assert_called_once_with('')

View File

@ -1,5 +1,23 @@
"""
pytest fixtures and utilities for testing.
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2015 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""pytest fixtures and utilities for testing.
Fixtures defined here will be visible to all test files in this directory and
below.
@ -16,8 +34,8 @@ def default_config():
"""
Fixture that registers an empty config object into the objreg module.
Should be used by tests which create widgets that obtain their initial state
from the global config object.
Should be used by tests which create widgets that obtain their initial
state from the global config object.
Note:
@ -31,4 +49,4 @@ def default_config():
config_obj = ConfigManager(configdir=None, fname=None, relaxed=True)
objreg.register('config', config_obj)
yield config_obj
objreg.delete('config')
objreg.delete('config')

View File

@ -19,6 +19,7 @@
"""Test Percentage widget."""
import pytest
from qutebrowser.mainwindow.statusbar.percentage import Percentage
@ -37,7 +38,8 @@ def test_percentage_text(qtbot, y, expected):
Args:
qtbot: pytestqt.plugin.QtBot fixture
y: y position of the page as an int in the range [0, 100]. parametrized.
y: y position of the page as an int in the range [0, 100].
parametrized.
expected: expected text given y position. parametrized.
"""
percentage = Percentage()

View File

@ -30,9 +30,7 @@ from qutebrowser.mainwindow.statusbar.progress import Progress
@pytest.fixture
def progress_widget(qtbot, default_config):
"""
Creates a Progress widget and checks it initial state.
"""
"""Create a Progress widget and checks its initial state."""
widget = Progress()
qtbot.add_widget(widget)
assert not widget.isVisible()
@ -41,7 +39,8 @@ def progress_widget(qtbot, default_config):
def test_load_started(progress_widget):
"""
"""Ensure the Progress widget reacts properly when the page starts loading.
Args:
progress_widget: Progress widget that will be tested.
"""
@ -62,13 +61,14 @@ Tab = namedtuple('Tab', 'progress load_status')
(Tab(100, webview.LoadStatus.none), False),
])
def test_tab_changed(progress_widget, tab, expected_visible):
"""
Test that progress widget value and visibility state match expectations,
using a dummy Tab object.
"""Test that progress widget value and visibility state match expectations.
This uses a dummy Tab object.
Args:
progress_widget: Progress widget that will be tested.
"""
progress_widget.on_tab_changed(tab)
assert (progress_widget.value(), progress_widget.isVisible()) == \
(tab.progress, expected_visible)
actual = progress_widget.value(), progress_widget.isVisible()
expected = tab.progress, expected_visible
assert actual == expected

View File

@ -24,18 +24,15 @@ from qutebrowser.mainwindow.statusbar.textbase import TextBase
def test_elided_text(qtbot):
"""
Ensure that a widget that can't hold the entire label text will display
and elided version of the string instead.
"""Ensure that a widget too small to hold the entire label text will elide.
Note:
It is difficult to check what is actually being drawn in a portable
way, so at least we ensure our customized methods are being called and
the elided string contains the horizontal ellipsis character.
Args:
qtbot: pytestqt.plugin.QtBot fixture
Note:
It is difficult to check what is actually being drawn in a
portable way, so at least we ensure our customized methods are being
called and the elided string contains the horizontal ellipsis character.
"""
label = TextBase()
qtbot.add_widget(label)
@ -43,4 +40,4 @@ def test_elided_text(qtbot):
label.setText(long_string)
label.resize(100, 50)
label.show()
assert '' in label._elided_text
assert '' in label._elided_text # pylint: disable=protected-access

View File

@ -23,7 +23,6 @@
import os
import os.path
import unittest
import logging
from unittest import mock
@ -75,14 +74,15 @@ class TestArg:
"bin", ["foo", filename, "bar"])
def test_in_arg_placeholder(self):
"""Test starting editor with placeholder argument inside argument."""
self.config.data = {'general': {'editor': ['bin', 'foo{}bar'],
'editor-encoding': 'utf-8'}}
"""Test starting editor with placeholder argument inside argument."""
self.editor.edit("")
self.editor._proc.start.assert_called_with("bin", ["foo{}bar"])
class TestFileHandling(object):
"""Test creation/deletion of tempfile.
Attributes:
@ -132,6 +132,7 @@ class TestFileHandling(object):
class TestModifyTests(object):
"""Tests to test if the text gets saved/loaded correctly.
Attributes:
@ -202,6 +203,7 @@ class TestModifyTests(object):
class TestErrorMessage:
"""Test if statusbar error messages get emitted correctly.
Attributes:
@ -233,4 +235,3 @@ class TestErrorMessage:
with caplog.atLevel(logging.ERROR, 'message'):
self.editor.on_proc_closed(1, QProcess.NormalExit)
assert len(caplog.records()) == 3

View File

@ -32,20 +32,18 @@ from qutebrowser.misc import readline
@pytest.fixture
def mocked_qapp(mocker, stubs):
"""
Fixture that mocks QApplication in the readline module and returns it.
"""
"""Fixture that mocks readline.QApplication and returns it."""
return mocker.patch('qutebrowser.misc.readline.QApplication',
new_callable=stubs.FakeQApplication)
class TestNoneWidget:
"""Tests when the focused widget is None."""
"""Test if there are no exceptions when the widget is None."""
def test_none(self, mocked_qapp):
"""Call each rl_* method with a None focusWidget."""
self.bridge = readline.ReadlineBridge()
"""Test if there are no exceptions when the widget is None."""
mocked_qapp.focusWidget = mock.Mock(return_value=None)
for name, method in inspect.getmembers(self.bridge, inspect.ismethod):
if name.startswith('rl_'):

View File

@ -20,6 +20,7 @@
# pylint: disable=invalid-name
"""Fake objects/stubs."""
import logging
from unittest import mock
@ -272,6 +273,7 @@ class FakeTimer(QObject):
class MessageModule:
"""A drop-in replacement for qutebrowser.utils.message."""
def error(self, _win_id, message, _immediately=False):
@ -284,4 +286,4 @@ class MessageModule:
def info(self, _win_id, message, _immediately=True):
"""Log an info message to the message logger."""
logging.getLogger('message').info(message)
logging.getLogger('message').info(message)

View File

@ -105,5 +105,3 @@ def test_interval(timer):
assert timer.interval() == 0
timer.setInterval(1000)
assert timer.interval() == 1000

View File

@ -21,7 +21,6 @@
import pytest
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QStyle, QFrame
from qutebrowser.utils import debug

View File

@ -31,9 +31,10 @@ from qutebrowser.utils import standarddir
@pytest.yield_fixture(autouse=True)
def change_qapp_name():
"""
Change the name of the QApplication instance for all tests in this module
to "qutebrowser_test".
"""Change the name of the QApplication instance.
This changes the applicationName for all tests in this module to
"qutebrowser_test".
"""
old_name = QApplication.instance().applicationName()
QApplication.instance().setApplicationName('qutebrowser_test')
@ -44,23 +45,23 @@ def change_qapp_name():
@pytest.mark.skipif(not sys.platform.startswith("linux"),
reason="requires Linux")
class TestGetStandardDirLinux:
"""Tests for standarddir under Linux.
"""
"""Tests for standarddir under Linux."""
def test_data_explicit(self, monkeypatch, tmpdir):
"""Test data dir with XDG_DATA_HOME explicitely set."""
"""Test data dir with XDG_DATA_HOME explicitly set."""
monkeypatch.setenv('XDG_DATA_HOME', str(tmpdir))
standarddir.init(None)
assert standarddir.data() == str(tmpdir / 'qutebrowser_test')
def test_config_explicit(self, monkeypatch, tmpdir):
"""Test config dir with XDG_CONFIG_HOME explicitely set."""
"""Test config dir with XDG_CONFIG_HOME explicitly set."""
monkeypatch.setenv('XDG_CONFIG_HOME', str(tmpdir))
standarddir.init(None)
assert standarddir.config() == str(tmpdir / 'qutebrowser_test')
def test_cache_explicit(self, monkeypatch, tmpdir):
"""Test cache dir with XDG_CACHE_HOME explicitely set."""
"""Test cache dir with XDG_CACHE_HOME explicitly set."""
monkeypatch.setenv('XDG_CACHE_HOME', str(tmpdir))
standarddir.init(None)
assert standarddir.cache() == str(tmpdir / 'qutebrowser_test')
@ -93,8 +94,8 @@ class TestGetStandardDirLinux:
@pytest.mark.skipif(not sys.platform.startswith("win"),
reason="requires Windows")
class TestGetStandardDirWindows:
"""Tests for standarddir under Windows.
"""
"""Tests for standarddir under Windows."""
@pytest.fixture(autouse=True)
def reset_standarddir(self):

View File

@ -21,9 +21,6 @@
"""Tests for qutebrowser.utils.urlutils."""
import unittest
from unittest import mock
from PyQt5.QtCore import QUrl
import pytest
@ -46,6 +43,7 @@ def get_config_stub(auto_search=True):
class TestSpecialURL:
"""Test is_special_url.
Attributes:
@ -78,10 +76,12 @@ class TestSpecialURL:
class TestSearchUrl:
"""Test _get_search_url."""
@pytest.fixture(autouse=True)
def mock_config(self, stubs, mocker):
"""Fixture to patch urlutils.config with a stub."""
mocker.patch('qutebrowser.utils.urlutils.config',
new=stubs.ConfigStub(get_config_stub()))
@ -123,6 +123,7 @@ class TestSearchUrl:
class TestIsUrl:
"""Tests for is_url.
Class attributes:
@ -179,43 +180,42 @@ class TestIsUrl:
class TestQurlFromUserInput:
"""Tests for qurl_from_user_input."""
def test_url(self):
"""Test a normal URL."""
assert (
urlutils.qurl_from_user_input('qutebrowser.org').toString()
== 'http://qutebrowser.org')
url = urlutils.qurl_from_user_input('qutebrowser.org')
assert url.toString() == 'http://qutebrowser.org'
def test_url_http(self):
"""Test a normal URL with http://."""
assert (
urlutils.qurl_from_user_input('http://qutebrowser.org').toString()
== 'http://qutebrowser.org')
url = urlutils.qurl_from_user_input('http://qutebrowser.org')
assert url.toString() == 'http://qutebrowser.org'
def test_ipv6_bare(self):
"""Test an IPv6 without brackets."""
assert (urlutils.qurl_from_user_input('::1/foo').toString()
== 'http://[::1]/foo')
url = urlutils.qurl_from_user_input('::1/foo')
assert url.toString() == 'http://[::1]/foo'
def test_ipv6(self):
"""Test an IPv6 with brackets."""
assert (urlutils.qurl_from_user_input('[::1]/foo').toString() ==
'http://[::1]/foo')
url = urlutils.qurl_from_user_input('[::1]/foo')
assert url.toString() == 'http://[::1]/foo'
def test_ipv6_http(self):
"""Test an IPv6 with http:// and brackets."""
assert (
urlutils.qurl_from_user_input('http://[::1]').toString() ==
'http://[::1]')
url = urlutils.qurl_from_user_input('http://[::1]')
assert url.toString() == 'http://[::1]'
class TestFilenameFromUrl:
"""Tests for filename_from_url."""
def test_invalid_url(self):
"""Test with an invalid QUrl."""
assert urlutils.filename_from_url(QUrl()) == None
assert urlutils.filename_from_url(QUrl()) is None
def test_url_path(self):
"""Test with an URL with path."""

View File

@ -478,4 +478,3 @@ class TestNewestSlice:
items = range(5)
sliced = utils.newest_slice(items, 50)
assert list(sliced) == list(items)

View File

@ -69,7 +69,7 @@ deps = pep257==0.5.0
# D102: Docstring missing, will be handled by others
# D209: Blank line before closing """ (removed from PEP257)
# D402: First line should not be function's signature (false-positives)
commands = {envpython} -m pep257 scripts tests qutebrowser --ignore=D102,D209,D402 '--match=(?!resources|test_content_disposition).*\.py'
commands = {envpython} -m pep257 scripts tests qutebrowser --ignore=D102,D103,D209,D402 '--match=(?!resources|test_content_disposition).*\.py'
[testenv:flake8]
skip_install = true