From 9d44f777c04a7ab9f5ae510cd35a12c436b0ed7b Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sun, 5 Apr 2015 20:30:31 +0200 Subject: [PATCH] Fix lint. --- .pylintrc | 1 + scripts/misc_checks.py | 2 +- .../browser/http/test_content_disposition.py | 14 +- tests/browser/http/test_http.py | 1 - tests/browser/test_tabhistory.py | 33 +++-- tests/browser/test_webelem.py | 3 +- tests/config/test_config.py | 14 +- tests/config/test_configtypes.py | 139 ++++++++++++------ tests/conftest.py | 19 +-- tests/keyinput/test_basekeyparser.py | 12 +- tests/keyinput/test_modeparsers.py | 1 - tests/mainwindow/conftest.py | 28 +++- tests/mainwindow/statusbar/test_percentage.py | 4 +- tests/mainwindow/statusbar/test_progress.py | 18 +-- tests/mainwindow/statusbar/test_textbase.py | 17 +-- tests/misc/test_editor.py | 7 +- tests/misc/test_readline.py | 8 +- tests/stubs.py | 4 +- tests/test_stubs.py | 2 - tests/utils/debug/test_qenum_key.py | 1 - tests/utils/test_standarddir.py | 21 +-- tests/utils/test_urlutils.py | 34 ++--- tests/utils/test_utils.py | 1 - tox.ini | 2 +- 24 files changed, 219 insertions(+), 167 deletions(-) diff --git a/.pylintrc b/.pylintrc index daa68e14a..2cc56909d 100644 --- a/.pylintrc +++ b/.pylintrc @@ -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 diff --git a/scripts/misc_checks.py b/scripts/misc_checks.py index bea0a4628..2ecefc199 100644 --- a/scripts/misc_checks.py +++ b/scripts/misc_checks.py @@ -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: diff --git a/tests/browser/http/test_content_disposition.py b/tests/browser/http/test_content_disposition.py index ce974c752..ae4b70b8e 100644 --- a/tests/browser/http/test_content_disposition.py +++ b/tests/browser/http/test_content_disposition.py @@ -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') - - diff --git a/tests/browser/http/test_http.py b/tests/browser/http/test_http.py index 152f94ea6..38ef1b42b 100644 --- a/tests/browser/http/test_http.py +++ b/tests/browser/http/test_http.py @@ -59,4 +59,3 @@ class TestParseContentType: mimetype, rest = http.parse_content_type(reply) assert mimetype == 'image/example' assert rest == ' encoding=UTF-8' - diff --git a/tests/browser/test_tabhistory.py b/tests/browser/test_tabhistory.py index 3b7f7b170..dcebe94f4 100644 --- a/tests/browser/test_tabhistory.py +++ b/tests/browser/test_tabhistory.py @@ -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 - - diff --git a/tests/browser/test_webelem.py b/tests/browser/test_webelem.py index 2f931444c..33de396db 100644 --- a/tests/browser/test_webelem.py +++ b/tests/browser/test_webelem.py @@ -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() - - diff --git a/tests/config/test_config.py b/tests/config/test_config.py index dcb7d5616..6bee98ee4 100644 --- a/tests/config/test_config.py +++ b/tests/config/test_config.py @@ -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.""" diff --git a/tests/config/test_configtypes.py b/tests/config/test_configtypes.py index 009133af2..90208244b 100644 --- a/tests/config/test_configtypes.py +++ b/tests/config/test_configtypes.py @@ -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) diff --git a/tests/conftest.py b/tests/conftest.py index 33bb99923..d3411694c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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 \ No newline at end of file + return fake_keyevent diff --git a/tests/keyinput/test_basekeyparser.py b/tests/keyinput/test_basekeyparser.py index d28aceda2..7164bffbd 100644 --- a/tests/keyinput/test_basekeyparser.py +++ b/tests/keyinput/test_basekeyparser.py @@ -44,9 +44,7 @@ BINDINGS = {'test': {'': '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 diff --git a/tests/keyinput/test_modeparsers.py b/tests/keyinput/test_modeparsers.py index c59bfe163..e177ad5a3 100644 --- a/tests/keyinput/test_modeparsers.py +++ b/tests/keyinput/test_modeparsers.py @@ -92,4 +92,3 @@ class TestsNormalKeyParser: assert not self.kp.execute.called assert self.kp._keystring == '' keystring_updated_mock.assert_called_once_with('') - diff --git a/tests/mainwindow/conftest.py b/tests/mainwindow/conftest.py index bfa84d337..47dcc5883 100644 --- a/tests/mainwindow/conftest.py +++ b/tests/mainwindow/conftest.py @@ -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) +# +# 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 . + +"""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') \ No newline at end of file + objreg.delete('config') diff --git a/tests/mainwindow/statusbar/test_percentage.py b/tests/mainwindow/statusbar/test_percentage.py index de1dbe03e..80de6b66f 100644 --- a/tests/mainwindow/statusbar/test_percentage.py +++ b/tests/mainwindow/statusbar/test_percentage.py @@ -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() diff --git a/tests/mainwindow/statusbar/test_progress.py b/tests/mainwindow/statusbar/test_progress.py index 4a4038701..a3a9f1797 100644 --- a/tests/mainwindow/statusbar/test_progress.py +++ b/tests/mainwindow/statusbar/test_progress.py @@ -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) \ No newline at end of file + actual = progress_widget.value(), progress_widget.isVisible() + expected = tab.progress, expected_visible + assert actual == expected diff --git a/tests/mainwindow/statusbar/test_textbase.py b/tests/mainwindow/statusbar/test_textbase.py index 1c1082783..0abdf669b 100644 --- a/tests/mainwindow/statusbar/test_textbase.py +++ b/tests/mainwindow/statusbar/test_textbase.py @@ -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 diff --git a/tests/misc/test_editor.py b/tests/misc/test_editor.py index b560291e8..db6280339 100644 --- a/tests/misc/test_editor.py +++ b/tests/misc/test_editor.py @@ -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 - diff --git a/tests/misc/test_readline.py b/tests/misc/test_readline.py index e1536edf4..9ace12b48 100644 --- a/tests/misc/test_readline.py +++ b/tests/misc/test_readline.py @@ -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_'): diff --git a/tests/stubs.py b/tests/stubs.py index 6345c7c00..95c6833b8 100644 --- a/tests/stubs.py +++ b/tests/stubs.py @@ -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) \ No newline at end of file + logging.getLogger('message').info(message) diff --git a/tests/test_stubs.py b/tests/test_stubs.py index 9f340c1fd..aa7816f91 100644 --- a/tests/test_stubs.py +++ b/tests/test_stubs.py @@ -105,5 +105,3 @@ def test_interval(timer): assert timer.interval() == 0 timer.setInterval(1000) assert timer.interval() == 1000 - - diff --git a/tests/utils/debug/test_qenum_key.py b/tests/utils/debug/test_qenum_key.py index c111ff311..c43279a4a 100644 --- a/tests/utils/debug/test_qenum_key.py +++ b/tests/utils/debug/test_qenum_key.py @@ -21,7 +21,6 @@ import pytest -from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QStyle, QFrame from qutebrowser.utils import debug diff --git a/tests/utils/test_standarddir.py b/tests/utils/test_standarddir.py index a27b5b635..e98ab80f9 100644 --- a/tests/utils/test_standarddir.py +++ b/tests/utils/test_standarddir.py @@ -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): diff --git a/tests/utils/test_urlutils.py b/tests/utils/test_urlutils.py index bb5b330e4..501ce2dd1 100644 --- a/tests/utils/test_urlutils.py +++ b/tests/utils/test_urlutils.py @@ -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.""" diff --git a/tests/utils/test_utils.py b/tests/utils/test_utils.py index e82cee184..26dc1cab7 100644 --- a/tests/utils/test_utils.py +++ b/tests/utils/test_utils.py @@ -478,4 +478,3 @@ class TestNewestSlice: items = range(5) sliced = utils.newest_slice(items, 50) assert list(sliced) == list(items) - diff --git a/tox.ini b/tox.ini index 7bbe8ff7b..9eccaf18e 100644 --- a/tox.ini +++ b/tox.ini @@ -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