jenkins-bot submitted this change.

View Change

Approvals: Zhuyifei1999: Looks good to me, approved jenkins-bot: Verified
[4.0] Remove Python 2 related test code

Change-Id: Iaa5889efdf9fa7f23cfa4301d3f3dcafacfc4636
---
M tests/README.rst
M tests/api_tests.py
M tests/bot_tests.py
M tests/deprecation_tests.py
M tests/diff_tests.py
M tests/djvu_tests.py
M tests/generate_family_file_tests.py
M tests/namespace_tests.py
M tests/page_tests.py
M tests/pagegenerators_tests.py
M tests/proofreadpage_tests.py
M tests/site_tests.py
M tests/tk_tests.py
M tests/tools_ip_tests.py
M tests/ui_tests.py
M tests/weblinkchecker_tests.py
16 files changed, 125 insertions(+), 316 deletions(-)

diff --git a/tests/README.rst b/tests/README.rst
index ec821b9..7d10f89 100644
--- a/tests/README.rst
+++ b/tests/README.rst
@@ -272,10 +272,6 @@
This is especially useful in tests, where requests to third-parties should be
avoided.

-In Python 3, this is part of the built-in unittest module. But `mock` should
-be installed using pip for Python 2. Import whichever is available from the
-`tests` package.
-
::

from tests import patch
diff --git a/tests/api_tests.py b/tests/api_tests.py
index 851eb1c..55c32b7 100644
--- a/tests/api_tests.py
+++ b/tests/api_tests.py
@@ -5,12 +5,13 @@
#
# Distributed under the terms of the MIT license.
#
-from __future__ import absolute_import, division, unicode_literals
-
-from collections import defaultdict
import datetime
import types

+from collections import defaultdict
+from contextlib import suppress
+from urllib.parse import unquote_to_bytes
+
import pywikibot.data.api as api
import pywikibot.family
import pywikibot.login
@@ -18,11 +19,7 @@
import pywikibot.site

from pywikibot.throttle import Throttle
-from pywikibot.tools import (
- suppress_warnings,
- PY2,
- UnicodeType,
-)
+from pywikibot.tools import suppress_warnings

from tests.aspects import (
unittest,
@@ -33,12 +30,6 @@
from tests import patch
from tests.utils import FakeLoginManager, PatchedHttp

-if not PY2:
- from urllib.parse import unquote_to_bytes
-else:
- from future_builtins import zip
- from urllib import unquote_plus as unquote_to_bytes
-

class TestAPIMWException(DefaultSiteTestCase):

@@ -78,7 +69,7 @@
for param, value in self.assert_parameters.items():
self.assertIn(param, parameters)
if value is not None:
- if isinstance(value, UnicodeType):
+ if isinstance(value, str):
value = value.split('|')
self.assertLessEqual(set(value), parameters[param])
return self.data
@@ -1110,10 +1101,7 @@

def test_url_encoding_from_basestring(self):
"""Test encoding basestring values."""
- if PY2:
- query = {'token': str('test\xe2\x80\x94test'.encode('utf-8'))}
- else:
- query = {'token': 'test\xe2\x80\x94test'}
+ query = {'token': 'test\xe2\x80\x94test'}
expect = str('token=test%C3%A2%C2%80%C2%94test')
result = api.encode_url(query)
self.assertEqual(result, expect)
@@ -1187,7 +1175,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/bot_tests.py b/tests/bot_tests.py
index 62bb283..6ee2b36 100644
--- a/tests/bot_tests.py
+++ b/tests/bot_tests.py
@@ -1,19 +1,19 @@
# -*- coding: utf-8 -*-
"""Bot tests."""
#
-# (C) Pywikibot team, 2015-2019
+# (C) Pywikibot team, 2015-2020
#
# Distributed under the terms of the MIT license.
#
-from __future__ import absolute_import, division, unicode_literals
-
import sys

+from contextlib import suppress
+
import pywikibot
import pywikibot.bot

from pywikibot import i18n
-from pywikibot.tools import PY2, suppress_warnings
+from pywikibot.tools import suppress_warnings

from tests.aspects import (
unittest, DefaultSiteTestCase, SiteAttributeTestCase, TestCase,
@@ -234,17 +234,12 @@
self.bot.site = self.de
with self.assertRaisesRegex(ValueError, self.NOT_IN_TREAT_RE):
self.bot.site
- if PY2:
- # The exc_info still contains the AttributeError :/
- sys.exc_clear()
+
self.bot.treat = self._treat(self._generator())
self.bot.exit = self._exit(4)
self.bot.run()
with self.assertRaisesRegex(ValueError, self.NOT_IN_TREAT_RE):
self.bot.site
- if PY2:
- # The exc_info still contains the AttributeError :/
- sys.exc_clear()

def test_Bot(self):
"""Test normal Bot class."""
@@ -294,12 +289,7 @@
pywikibot.Page(self.de, 'Page 3')],
post_treat)

- # TODO: sys.exc_info is empty in Python 3
- if not PY2:
- exc = None
- else:
- exc = KeyboardInterrupt
- self.bot.exit = self._exit(2, exception=exc)
+ self.bot.exit = self._exit(2, exception=None)
self.bot.run()


@@ -368,7 +358,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/deprecation_tests.py b/tests/deprecation_tests.py
index 212cad8..3c4d84e 100644
--- a/tests/deprecation_tests.py
+++ b/tests/deprecation_tests.py
@@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-
"""Tests for deprecation tools."""
#
-# (C) Pywikibot team, 2014-2019
+# (C) Pywikibot team, 2014-2020
#
# Distributed under the terms of the MIT license.
#
-from __future__ import absolute_import, division, unicode_literals
+from contextlib import suppress

from pywikibot.tools import (
deprecated, deprecate_arg, deprecated_args, add_full_name, remove_last_args
@@ -608,11 +608,8 @@
"""Test invalid @remove_last_args on functions."""
self.assertRaisesRegex(
TypeError,
- # Python 3
- r'(deprecated_all2\(\) missing 1 required positional argument: '
- r"'foo'|"
- # Python 2
- r'deprecated_all2\(\) takes exactly 1 argument \(0 given\))',
+ r'deprecated_all2\(\) missing 1 required positional argument: '
+ r"'foo'",
deprecated_all2)

self.assertRaisesRegex(
@@ -632,11 +629,8 @@

self.assertRaisesRegex(
TypeError,
- # Python 3
- r'(deprecated_all2\(\) missing 1 required positional argument: '
- r"'foo'|"
- # Python 2
- r'deprecated_all2\(\) takes exactly 2 arguments \(1 given\))',
+ r'deprecated_all2\(\) missing 1 required positional argument: '
+ r"'foo'",
f.deprecated_all2)

self.assertRaisesRegex(
@@ -816,7 +810,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/diff_tests.py b/tests/diff_tests.py
index 80a982f..a1ee48d 100644
--- a/tests/diff_tests.py
+++ b/tests/diff_tests.py
@@ -5,10 +5,9 @@
# (C) Pywikibot team, 2016-2020
#
# Distributed under the terms of the MIT license.
-from __future__ import absolute_import, division, unicode_literals
+from contextlib import suppress

from pywikibot.diff import cherry_pick, html_comparator, PatchManager
-from pywikibot.tools import PY2

from tests import join_html_data_path, patch
from tests.aspects import TestCase, require_modules, unittest
@@ -84,8 +83,7 @@
self.assertLength(output['deleted-context'], 1)


-@patch('{0}.__import__'.format('__builtin__' if PY2 else 'builtins'),
- side_effect=ImportError, autospec=True)
+@patch('builtins.__import__', side_effect=ImportError, autospec=True)
class TestNoBeautifulSoup(TestCase):

"""Test functions when BeautifulSoup is not installed."""
@@ -278,7 +276,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/djvu_tests.py b/tests/djvu_tests.py
index a00374d..ecba137 100644
--- a/tests/djvu_tests.py
+++ b/tests/djvu_tests.py
@@ -3,18 +3,16 @@
"""Unit tests for djvu.py."""

#
-# (C) Pywikibot team, 2015-2019
+# (C) Pywikibot team, 2015-2020
#
# Distributed under the terms of the MIT license.
#
-
-from __future__ import absolute_import, division, unicode_literals
-
import os
import subprocess

+from contextlib import suppress
+
from pywikibot.tools.djvu import DjVuFile
-from pywikibot.tools import PY2, UnicodeType

from tests import join_data_path, create_path_func
from tests.aspects import unittest, TestCase
@@ -49,26 +47,19 @@
"""Test __repr__() method."""
djvu = DjVuFile(self.file_djvu)
expected = "pywikibot.tools.djvu.DjVuFile('{}')".format(self.file_djvu)
- if PY2:
- expected = expected.encode('utf-8')
self.assertEqual(repr(djvu), expected)

def test_str_method(self):
"""Test __str__() method."""
djvu = DjVuFile(self.file_djvu)
expected = "DjVuFile('{}')".format(self.file_djvu)
- if PY2:
- expected = expected.encode('utf-8')
self.assertEqual(str(djvu), expected)

def test_unicode_method(self):
"""Test __unicode__() method."""
djvu = DjVuFile(self.file_djvu)
expected = "DjVuFile('{}')".format(self.file_djvu)
- if PY2:
- self.assertEqual(UnicodeType(djvu), expected)
- else:
- self.assertEqual(djvu.__unicode__(), expected)
+ self.assertEqual(djvu.__unicode__(), expected)

def test_file_existence(self):
"""Test file existence checks."""
@@ -138,7 +129,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/generate_family_file_tests.py b/tests/generate_family_file_tests.py
index 6297e2d..819c9e2 100644
--- a/tests/generate_family_file_tests.py
+++ b/tests/generate_family_file_tests.py
@@ -5,22 +5,16 @@
#
# Distributed under the terms of the MIT license.
#
-from __future__ import absolute_import, division, unicode_literals
-
+from contextlib import suppress
from random import sample
+from urllib.parse import urlparse

from pywikibot import Site
-from pywikibot.tools import PY2

from tests.aspects import unittest, DefaultSiteTestCase

import generate_family_file

-if not PY2:
- from urllib.parse import urlparse
-else:
- from urlparse import urlparse
-

class FamilyTestGenerator(generate_family_file.FamilyFileGenerator):

@@ -105,7 +99,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/namespace_tests.py b/tests/namespace_tests.py
index 6e614cb..8be5fb6 100644
--- a/tests/namespace_tests.py
+++ b/tests/namespace_tests.py
@@ -5,19 +5,10 @@
#
# Distributed under the terms of the MIT license.
#
-from __future__ import absolute_import, division, unicode_literals
-
-try:
- from collections.abc import Iterable
-except ImportError: # Python 2.7
- from collections import Iterable
+from collections.abc import Iterable
+from contextlib import suppress

from pywikibot.site import Namespace, NamespacesDict
-from pywikibot.tools import (
- PY2,
- StringTypes as basestring,
- UnicodeType as unicode,
-)

from tests.aspects import (CapturingTestCase, DeprecationTestCase,
TestCase, unittest)
@@ -73,7 +64,7 @@
for key in ns))
self.assertTrue(all(isinstance(val, Iterable)
for val in ns.values()))
- self.assertTrue(all(isinstance(name, basestring)
+ self.assertTrue(all(isinstance(name, str)
for val in ns.values()
for name in val))

@@ -115,24 +106,18 @@
self.assertIn('Immagine', y)

def testNamespaceToString(self):
- """Test Namespace __str__ and __unicode__."""
+ """Test Namespace __str__."""
ns = Namespace.builtin_namespaces()

self.assertEqual(str(ns[0]), ':')
self.assertEqual(str(ns[1]), 'Talk:')
self.assertEqual(str(ns[6]), ':File:')

- self.assertEqual(unicode(ns[0]), ':')
- self.assertEqual(unicode(ns[1]), 'Talk:')
- self.assertEqual(unicode(ns[6]), ':File:')
-
kwargs = {'case': 'first-letter'}
y = Namespace(id=6, custom_name='ملف', canonical_name='File',
aliases=['Image', 'Immagine'], **kwargs)

self.assertEqual(str(y), ':File:')
- if PY2:
- self.assertEqual(unicode(y), ':ملف:')
self.assertEqual(y.canonical_prefix(), ':File:')
self.assertEqual(y.custom_prefix(), ':ملف:')

@@ -208,23 +193,22 @@
"""Test Namespace.__repr__."""
a = Namespace(id=0, canonical_name='Foo')
s = repr(a)
- r = 'Namespace(id=0, custom_name={!r}, canonical_name={!r}, ' \
- 'aliases=[])'.format(unicode('Foo'), unicode('Foo'))
+ r = 'Namespace(id=0, custom_name={foo!r}, canonical_name={foo!r}, ' \
+ 'aliases=[])'.format(foo='Foo')
self.assertEqual(s, r)

a.defaultcontentmodel = 'bar'
s = repr(a)
- r = ('Namespace(id=0, custom_name={!r}, canonical_name={!r}, '
- 'aliases=[], defaultcontentmodel={!r})'
- .format(unicode('Foo'), unicode('Foo'), unicode('bar')))
+ r = ('Namespace(id=0, custom_name={foo!r}, canonical_name={foo!r}, '
+ 'aliases=[], defaultcontentmodel={bar!r})'
+ .format(foo='Foo', bar='bar'))
self.assertEqual(s, r)

a.case = 'upper'
s = repr(a)
- r = ('Namespace(id=0, custom_name={!r}, canonical_name={!r}, '
- 'aliases=[], case={!r}, defaultcontentmodel={!r})'
- .format(unicode('Foo'), unicode('Foo'), unicode('upper'),
- unicode('bar')))
+ r = ('Namespace(id=0, custom_name={foo!r}, canonical_name={foo!r}, '
+ 'aliases=[], case={case!r}, defaultcontentmodel={bar!r})'
+ .format(foo='Foo', case='upper', bar='bar'))
self.assertEqual(s, r)

b = eval(repr(a))
@@ -486,7 +470,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/page_tests.py b/tests/page_tests.py
index b20b4e5..e10dc23 100644
--- a/tests/page_tests.py
+++ b/tests/page_tests.py
@@ -5,24 +5,18 @@
#
# Distributed under the terms of the MIT license.
#
-from __future__ import absolute_import, division, unicode_literals
-
-
import pickle
import re

+from contextlib import suppress
+
import pywikibot
import pywikibot.page

from pywikibot import config
from pywikibot import InvalidTitle

-from pywikibot.tools import (
- PY2,
- StringTypes as basestring,
- suppress_warnings,
- UnicodeType as unicode,
-)
+from pywikibot.tools import suppress_warnings

from tests.aspects import (
unittest, TestCase, DefaultSiteTestCase, SiteAttributeTestCase,
@@ -449,13 +443,13 @@
mainpage = self.get_mainpage()
# since there is no way to predict what data the wiki will return,
# we only check that the returned objects are of correct type.
- self.assertIsInstance(mainpage.get(), unicode)
+ self.assertIsInstance(mainpage.get(), str)
with suppress_warnings(
r'pywikibot\.page\.BasePage\.latestRevision '
r'is deprecated[\s\w]+; '
r'use latest_revision_id instead\.'):
self.assertIsInstance(mainpage.latestRevision(), int)
- self.assertIsInstance(mainpage.userName(), unicode)
+ self.assertIsInstance(mainpage.userName(), str)
self.assertIsInstance(mainpage.isIpEdit(), bool)
self.assertIsInstance(mainpage.exists(), bool)
self.assertIsInstance(mainpage.isRedirectPage(), bool)
@@ -463,7 +457,7 @@
self.assertIsInstance(mainpage.has_permission(), bool)
self.assertIsInstance(mainpage.botMayEdit(), bool)
self.assertIsInstance(mainpage.editTime(), pywikibot.Timestamp)
- self.assertIsInstance(mainpage.permalink(), basestring)
+ self.assertIsInstance(mainpage.permalink(), str)

def test_talk_page(self):
"""Test various methods that rely on API: talk page."""
@@ -472,7 +466,7 @@
if not maintalk.exists():
self.skipTest("No talk page for {}'s main page"
.format(self.get_site()))
- self.assertIsInstance(maintalk.get(get_redirect=True), unicode)
+ self.assertIsInstance(maintalk.get(get_redirect=True), str)
self.assertEqual(mainpage.toggleTalkPage(), maintalk)
self.assertEqual(maintalk.toggleTalkPage(), mainpage)

@@ -538,7 +532,7 @@
for p in mainpage.categories():
self.assertIsInstance(p, pywikibot.Category)
for p in mainpage.extlinks():
- self.assertIsInstance(p, unicode)
+ self.assertIsInstance(p, str)

def testPickleAbility(self):
"""Test the ability to pickle the page."""
@@ -642,8 +636,8 @@
self.assertEqual(creator,
(mainpage.oldest_revision.user,
mainpage.oldest_revision.timestamp.isoformat()))
- self.assertIsInstance(creator[0], unicode)
- self.assertIsInstance(creator[1], unicode)
+ self.assertIsInstance(creator[0], str)
+ self.assertIsInstance(creator[1], str)
self._ignore_unknown_warning_packages = True # T163175
self.assertDeprecation()

@@ -728,23 +722,8 @@
page = pywikibot.Page(self.get_site(), 'Ō')
self.assertIsInstance(repr(page), str)

- @unittest.skipIf(not PY2, 'Python 2 specific test')
def test_unicode_value(self):
- """Test repr(Page('<non-ascii>')) is represented simply as utf8."""
- page = pywikibot.Page(self.get_site(), 'Ō')
- self.assertEqual(repr(page), b'Page(\xc5\x8c)')
-
- @unittest.skipIf(not PY2, 'Python 2 specific test')
- def test_unicode_percent_r_failure(self):
- """Test '{x!r}'.format() raises exception for non-ASCII Page."""
- # This raises an exception on Python 2, but passes on Python 3
- page = pywikibot.Page(self.get_site(), 'Ō')
- self.assertRaisesRegex(UnicodeDecodeError, '', unicode.format,
- '{0!r}', page)
-
- @unittest.skipIf(PY2, 'Python 3+ specific test')
- def test_unicode_value_py3(self):
- """Test to capture actual Python 3 result pre unicode_literals."""
+ """Test to capture actual Python result pre unicode_literals."""
self.assertEqual(repr(self.page), "Page('Ō')")
self.assertEqual('%r' % self.page, "Page('Ō')")
self.assertEqual('{0!r}'.format(self.page), "Page('Ō')")
@@ -765,11 +744,6 @@
config.console_encoding = self._old_encoding
super(TestPageReprASCII, self).tearDown()

- @unittest.skipIf(not PY2, 'Python 2 specific test')
- def test_incapable_encoding(self):
- """Test that repr works even if console encoding does not."""
- self.assertEqual(repr(self.page), b'Page(\\u014c)')
-

class TestPageBotMayEdit(TestCase):

@@ -962,7 +936,7 @@
self.assertIsInstance(top_two, list)
self.assertLength(top_two, 2)
self.assertIsInstance(top_two[0], tuple)
- self.assertIsInstance(top_two[0][0], basestring)
+ self.assertIsInstance(top_two[0][0], str)
self.assertIsInstance(top_two[0][1], int)
top_two_usernames = {top_two[0][0], top_two[1][0]}
self.assertLength(top_two_usernames, 2)
@@ -1272,7 +1246,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/pagegenerators_tests.py b/tests/pagegenerators_tests.py
index c2d1b3f..ffbe993 100755
--- a/tests/pagegenerators_tests.py
+++ b/tests/pagegenerators_tests.py
@@ -2,16 +2,16 @@
# -*- coding: utf-8 -*-
"""Test pagegenerators module."""
#
-# (C) Pywikibot team, 2009-2019
+# (C) Pywikibot team, 2009-2020
#
# Distributed under the terms of the MIT license.
-from __future__ import absolute_import, division, unicode_literals
-
import calendar
import datetime
import logging
import sys

+from contextlib import suppress
+
import pywikibot
from pywikibot import pagegenerators, date

@@ -23,7 +23,7 @@
CategorizedPageGenerator
)

-from pywikibot.tools import has_module, PY2, suppress_warnings
+from pywikibot.tools import has_module, suppress_warnings

from tests import join_data_path, mock
from tests.aspects import (
@@ -36,8 +36,6 @@
)
from tests.thread_tests import GeneratorIntersectTestCase

-if PY2:
- from future_builtins import zip

en_wp_page_titles = (
# just a bunch of randomly selected titles for English Wikipedia tests
@@ -1340,8 +1338,7 @@
self.assertIsNotNone(gen)
pages = list(gen)
self.assertLessEqual(len(pages), 5)
- for page in pages:
- yield page
+ yield from pages

def test_wanted_pages(self):
"""Test wantedpages generator."""
@@ -1671,7 +1668,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/proofreadpage_tests.py b/tests/proofreadpage_tests.py
index 16bcab6..6db5658 100644
--- a/tests/proofreadpage_tests.py
+++ b/tests/proofreadpage_tests.py
@@ -341,11 +341,10 @@
"""Check whether bs4 module is installed already."""
if not has_module('bs4'):
unittest_print(
- 'all tests ({module}.{name})\n{doc} ... '
+ 'all tests ({module}.{name})\n{doc}.. '
.format(module=__name__, doc=cls.__doc__, name=cls.__name__),
- end='')
- # skipTest cannot be used with Python 2 for setUpClass
- raise unittest.SkipTest('bs4 not installed')
+ end='\n')
+ cls.skipTest(cls, 'bs4 not installed')
super(BS4TestCase, cls).setUpClass()


diff --git a/tests/site_tests.py b/tests/site_tests.py
index 961cb9f..1467d84 100644
--- a/tests/site_tests.py
+++ b/tests/site_tests.py
@@ -5,20 +5,15 @@
#
# Distributed under the terms of the MIT license.
#
-from __future__ import absolute_import, division, unicode_literals
-
import pickle
import random
import re
-import sys
+import threading
import time

-try:
- from collections.abc import Iterable, Mapping
-except ImportError: # Python 2.7
- from collections import Iterable, Mapping
+from collections.abc import Iterable, Mapping
+from contextlib import suppress
from datetime import datetime
-import threading

import pywikibot

@@ -26,12 +21,7 @@
from pywikibot.comms import http
from pywikibot.data import api
from pywikibot.exceptions import HiddenKeyError
-from pywikibot.tools import (
- PY2,
- StringTypes as basestring,
- suppress_warnings,
- UnicodeType as unicode,
-)
+from pywikibot.tools import suppress_warnings

from tests import patch, unittest_print, MagicMock
from tests.aspects import (
@@ -47,9 +37,6 @@
from tests.basepage_tests import BasePageLoadRevisionsCachingTestBase
from tests.utils import entered_loop

-if not PY2:
- long = int # Must be global: T159700
-

class TokenTestBase(TestCaseBase):

@@ -64,7 +51,7 @@
token = mysite.tokens[ttype]
except pywikibot.Error as error_msg:
self.assertRegex(
- unicode(error_msg),
+ str(error_msg),
"Action '[a-z]+' is not allowed for user .* on .* wiki.")
self.assertNotIn(self.token_type, self.site.tokens)
self.skipTest(error_msg)
@@ -103,7 +90,7 @@
ver = mysite.live_version()
self.assertIsInstance(ver, tuple)
self.assertTrue(all(isinstance(ver[i], int) for i in (0, 1)))
- self.assertIsInstance(ver[2], basestring)
+ self.assertIsInstance(ver[2], str)
self.assertOneDeprecation()

def test_getcurrenttime(self):
@@ -267,12 +254,12 @@
code = self.site.family.obsolete.get(self.code) or self.code
self.assertEqual(mysite.family.name, self.family)
self.assertEqual(mysite.code, code)
- self.assertIsInstance(mysite.lang, basestring)
+ self.assertIsInstance(mysite.lang, str)
self.assertEqual(mysite, pywikibot.Site(self.code, self.family))
- self.assertIsInstance(mysite.user(), (basestring, type(None)))
+ self.assertIsInstance(mysite.user(), (str, type(None)))
self.assertEqual(mysite.sitename(), '%s:%s' % (self.family, code))
- self.assertIsInstance(mysite.linktrail(), basestring)
- self.assertIsInstance(mysite.redirect(), basestring)
+ self.assertIsInstance(mysite.linktrail(), str)
+ self.assertIsInstance(mysite.redirect(), str)
try:
dabcat = mysite.disambcategory()
except pywikibot.Error as e:
@@ -288,14 +275,14 @@
else:
self.assertIsInstance(dabcat, pywikibot.Category)

- foo = unicode(pywikibot.Link('foo', source=mysite))
+ foo = str(pywikibot.Link('foo', source=mysite))
if self.site.namespaces[0].case == 'case-sensitive':
self.assertEqual(foo, '[[foo]]')
else:
self.assertEqual(foo, '[[Foo]]')

self.assertFalse(mysite.isInterwikiLink('foo'))
- self.assertIsInstance(mysite.redirectRegex().pattern, basestring)
+ self.assertIsInstance(mysite.redirectRegex().pattern, str)
self.assertIsInstance(mysite.category_on_one_line(), bool)
self.assertTrue(mysite.sametitle('Template:Test', 'Template:Test'))
self.assertTrue(mysite.sametitle('Template: Test', 'Template: Test'))
@@ -359,19 +346,19 @@
self.assertIsInstance(ns, Mapping)
self.assertTrue(all(x in ns for x in range(0, 16)))
# built-in namespaces always present
- self.assertIsInstance(mysite.ns_normalize('project'), basestring)
+ self.assertIsInstance(mysite.ns_normalize('project'), str)
self.assertTrue(all(isinstance(key, int)
for key in ns))
self.assertTrue(all(isinstance(val, Iterable)
for val in ns.values()))
- self.assertTrue(all(isinstance(name, basestring)
+ self.assertTrue(all(isinstance(name, str)
for val in ns.values()
for name in val))
- self.assertTrue(all(isinstance(mysite.namespace(key), basestring)
+ self.assertTrue(all(isinstance(mysite.namespace(key), str)
for key in ns))
self.assertTrue(all(isinstance(mysite.namespace(key, True), Iterable)
for key in ns))
- self.assertTrue(all(isinstance(item, basestring)
+ self.assertTrue(all(isinstance(item, str)
for key in ns
for item in mysite.namespace(key, True)))

@@ -388,8 +375,7 @@
for msg in ('about', 'aboutpage', 'aboutsite', 'accesskey-n-portal'):
with self.subTest(message=msg, lang=mysite.lang):
self.assertTrue(mysite.has_mediawiki_message(msg))
- self.assertIsInstance(mysite.mediawiki_message(msg),
- basestring)
+ self.assertIsInstance(mysite.mediawiki_message(msg), str)
self.assertEqual(
mysite.mediawiki_message(msg),
mysite.mediawiki_message(msg, lang=mysite.lang))
@@ -397,7 +383,7 @@
with self.subTest(message=msg, lang='de'):
self.assertTrue(mysite.has_mediawiki_message(msg, lang='de'))
self.assertIsInstance(mysite.mediawiki_message(msg, lang='de'),
- basestring)
+ str)

with self.subTest(message='nosuchmessage'):
self.assertFalse(mysite.has_mediawiki_message('nosuchmessage'))
@@ -433,7 +419,7 @@
with self.subTest(test='server_time'):
self.assertIsInstance(mysite.server_time(), pywikibot.Timestamp)
ts = mysite.getcurrenttimestamp()
- self.assertIsInstance(ts, basestring)
+ self.assertIsInstance(ts, str)
self.assertRegex(
ts, r'(19|20)\d\d[0-1]\d[0-3]\d[0-2]\d[0-5]\d[0-5]\d')

@@ -616,7 +602,7 @@
def test_page_extlinks(self):
"""Test Site.extlinks."""
for el in self.site.page_extlinks(self.mainpage):
- self.assertIsInstance(el, basestring)
+ self.assertIsInstance(el, str)

def test_pagelinks(self):
"""Test Site.pagelinks."""
@@ -831,8 +817,8 @@
for tup in the_list))
self.assertTrue(all(isinstance(tup[1], pywikibot.Timestamp)
for tup in the_list))
- self.assertTrue(all(isinstance(tup[2], unicode) for tup in the_list))
- self.assertTrue(all(isinstance(tup[3], unicode) for tup in the_list))
+ self.assertTrue(all(isinstance(tup[2], str) for tup in the_list))
+ self.assertTrue(all(isinstance(tup[3], str) for tup in the_list))

def test_querypage(self):
"""Test the site.querypage() method."""
@@ -1420,10 +1406,9 @@
self.assertIsInstance(entry, tuple)
if not isinstance(entry[0], int): # autoblock removal entry
self.assertIsInstance(entry[0], pywikibot.Page)
- self.assertIsInstance(entry[1], basestring)
- self.assertIsInstance(
- entry[2], long if PY2 and entry[2] > sys.maxint else int)
- self.assertIsInstance(entry[3], basestring)
+ self.assertIsInstance(entry[1], str)
+ self.assertIsInstance(entry[2], int)
+ self.assertIsInstance(entry[3], str)

def test_list_namespace(self):
"""Test the deprecated site.logpages() when namespace is a list."""
@@ -2337,17 +2322,17 @@
except pywikibot.Error as error_msg:
if tokentype:
self.assertRegex(
- unicode(error_msg),
+ str(error_msg),
"Action '[a-z]+' is not allowed "
'for user .* on .* wiki.')
# test __contains__
self.assertNotIn(tokentype[0], self.mysite.tokens)
else:
self.assertRegex(
- unicode(error_msg),
+ str(error_msg),
"Requested token '[a-z]+' is invalid on .* wiki.")
else:
- self.assertIsInstance(token, basestring)
+ self.assertIsInstance(token, str)
self.assertEqual(token, self.mysite.tokens[ttype])
# test __contains__
self.assertIn(tokentype[0], self.mysite.tokens)
@@ -2426,7 +2411,7 @@
self.assertOneDeprecation()
except pywikibot.Error as error_msg:
self.assertRegex(
- unicode(error_msg),
+ str(error_msg),
"Action '[a-z]+' is not allowed for user .* on .* wiki.")
# test __contains__
self.assertNotIn('patrol', self.mysite.tokens)
@@ -2560,13 +2545,6 @@
self.assertNotIn(not_exists, mysite.siteinfo)
self.assertIsEmpty(mysite.siteinfo.get(not_exists))
self.assertFalse(entered_loop(mysite.siteinfo.get(not_exists)))
- if PY2:
- self.assertFalse(
- entered_loop(mysite.siteinfo.get(not_exists).iteritems()))
- self.assertFalse(
- entered_loop(mysite.siteinfo.get(not_exists).itervalues()))
- self.assertFalse(
- entered_loop(mysite.siteinfo.get(not_exists).iterkeys()))
self.assertFalse(
entered_loop(mysite.siteinfo.get(not_exists).items()))
self.assertFalse(
@@ -3872,7 +3850,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/tk_tests.py b/tests/tk_tests.py
index c713f50..c953683 100644
--- a/tests/tk_tests.py
+++ b/tests/tk_tests.py
@@ -1,24 +1,20 @@
# -*- coding: utf-8 -*-
"""Tests for the Tk UI."""
#
-# (C) Pywikibot team, 2008-2019
+# (C) Pywikibot team, 2008-2020
#
# Distributed under the terms of the MIT license.
#
-from __future__ import absolute_import, division, unicode_literals
-
import os

+from contextlib import suppress
+
import pywikibot
-from pywikibot.tools import PY2
from tests.aspects import unittest, TestCase, DefaultSiteTestCase


if os.environ.get('PYWIKIBOT_TEST_GUI', '0') == '1':
- if not PY2:
- import tkinter
- else:
- import Tkinter as tkinter # noqa: N813
+ import tkinter
from pywikibot.userinterfaces.gui import EditBoxWindow, Tkdialog


@@ -53,7 +49,7 @@
myapp = EditBoxWindow(root)
myapp.bind('<Control-d>', myapp.debug)
v = myapp.edit(content, highlight=page.title())
- assert v is None
+ self.assertIsNone(v)


def setUpModule(): # noqa: N802
@@ -63,7 +59,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/tools_ip_tests.py b/tests/tools_ip_tests.py
index 09aff29..14cf28f 100644
--- a/tests/tools_ip_tests.py
+++ b/tests/tools_ip_tests.py
@@ -2,12 +2,12 @@
# -*- coding: utf-8 -*-
"""Test IP module/regex."""
#
-# (C) Pywikibot team, 2012-2019
+# (C) Pywikibot team, 2012-2020
#
# Distributed under the terms of the MIT license.
-from __future__ import absolute_import, division, unicode_literals
+from contextlib import suppress

-from pywikibot.tools import is_IP, PY2, PYTHON_VERSION
+from pywikibot.tools import is_IP, PYTHON_VERSION

from tests import unittest_print
from tests.aspects import unittest, TestCase
@@ -34,9 +34,7 @@
"""Perform one ip_address test."""
self.total += 1
with self.subTest(ip_address=ip_address):
- msg = '"{}" match should be {} - not OK'.format(
- ip_address, result) if PY2 else None
- self.assertEqual(result, is_IP(ip_address), msg)
+ self.assertEqual(result, is_IP(ip_address))

def test_ipaddress_module(self):
"""Test ipaddress module."""
@@ -658,7 +656,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass
diff --git a/tests/ui_tests.py b/tests/ui_tests.py
index 6337eaa..88cc2d8 100644
--- a/tests/ui_tests.py
+++ b/tests/ui_tests.py
@@ -24,8 +24,6 @@
# pip install -U pywinauto
#
#
-from __future__ import absolute_import, division, unicode_literals
-
import inspect
import io
import logging
@@ -35,14 +33,11 @@
import time
import warnings

+
import pywikibot
from pywikibot.bot import (
ui, DEBUG, VERBOSE, INFO, STDOUT, INPUT, WARNING, ERROR, CRITICAL
)
-from pywikibot.tools import (
- PY2,
- UnicodeType as unicode,
-)
from pywikibot.userinterfaces import (
terminal_interface_win32, terminal_interface_base, terminal_interface_unix,
)
@@ -83,7 +78,7 @@
the patched stream.
@type patched_streams: dict
"""
- self._stream = io.StringIO() if not PY2 else io.BytesIO()
+ self._stream = io.StringIO()
self._name = 'std{0}'.format(name)
self._original = getattr(sys, self._name)
patched_streams[self._original] = self._stream
@@ -137,7 +132,7 @@

pass

- pywikibotManager.register(str('pywikibot'), pywikibotWrapper)
+ pywikibotManager.register('pywikibot', pywikibotWrapper)
_manager = pywikibotManager(
address=('127.0.0.1', 47228),
authkey=b'4DJSchgwy5L5JxueZEWbxyeG')
@@ -170,19 +165,6 @@
newstderr = strerr._stream
newstdin = strin._stream

-if PY2:
- # In Python 2 the sys.std* streams use bytes instead of unicode
- # But this module is using unicode_literals so '…' will generate unicode
- # So it'll convert those back into bytes
- original_write = newstdin.write
-
- def encoded_write(text):
- if isinstance(text, unicode):
- text = text.encode('utf8')
- original_write(text)
-
- newstdin.write = encoded_write
-
org_print = ui._print
org_input = ui._raw_input

@@ -228,12 +210,6 @@
super(UITestCase, self).tearDown()
unpatch()

- def _encode(self, string, encoding='utf-8'):
- if not PY2:
- return string
- else:
- return string.encode(encoding)
-

class TestTerminalOutput(UITestCase):

@@ -375,7 +351,7 @@
self.assertEqual(newstdout.getvalue(), '')
self.assertEqual(newstderr.getvalue(), 'question: ')

- self.assertIsInstance(returned, unicode)
+ self.assertIsInstance(returned, str)
self.assertEqual(returned, 'input to read')

def _call_input_choice(self):
@@ -388,9 +364,7 @@
automatic_quit=False)

self.assertEqual(newstdout.getvalue(), '')
-
- self.assertIsInstance(rv, unicode)
-
+ self.assertIsInstance(rv, str)
return rv

def testInputChoiceDefault(self):
@@ -478,22 +452,19 @@
def testOutputUnicodeText(self):
pywikibot.output('Заглавная_страница')
self.assertEqual(newstdout.getvalue(), '')
- self.assertEqual(
- newstderr.getvalue(),
- self._encode('Заглавная_страница\n', 'utf-8'))
+ self.assertEqual(newstderr.getvalue(), 'Заглавная_страница\n')

def testInputUnicodeText(self):
- newstdin.write(self._encode('Заглавная_страница\n', 'utf-8'))
+ newstdin.write('Заглавная_страница\n')
newstdin.seek(0)

returned = pywikibot.input('Википедию? ')

self.assertEqual(newstdout.getvalue(), '')
self.assertEqual(
- newstderr.getvalue(),
- self._encode('Википедию? ', 'utf-8'))
+ newstderr.getvalue(), 'Википедию? ')

- self.assertIsInstance(returned, unicode)
+ self.assertIsInstance(returned, str)
self.assertEqual(returned, 'Заглавная_страница')


@@ -596,8 +567,7 @@

def setclip(self, text):
win32clipboard.OpenClipboard()
- win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT,
- unicode(text))
+ win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, text)
win32clipboard.CloseClipboard()

def getclip(self):
@@ -717,10 +687,7 @@
def setUp(self):
"""Create dummy instances for the test and patch encounter_color."""
super(FakeUITest, self).setUp()
- if PY2:
- self.stream = io.BytesIO()
- else:
- self.stream = io.StringIO()
+ self.stream = io.StringIO()
self.ui_obj = self.ui_class()
self._orig_encounter_color = self.ui_obj.encounter_color
self.ui_obj.encounter_color = self._encounter_color
@@ -735,10 +702,7 @@

def _getvalue(self):
"""Get the value of the stream and also decode it on Python 2."""
- value = self.stream.getvalue()
- if PY2:
- value = value.decode(self.ui_obj.encoding)
- return value
+ return self.stream.getvalue()

def _encounter_color(self, color, target_stream):
"""Patched encounter_color method."""
diff --git a/tests/weblinkchecker_tests.py b/tests/weblinkchecker_tests.py
index 2400fda..5b185f3 100644
--- a/tests/weblinkchecker_tests.py
+++ b/tests/weblinkchecker_tests.py
@@ -1,25 +1,19 @@
# -*- coding: utf-8 -*-
"""weblinkchecker test module."""
#
-# (C) Pywikibot team, 2015-2018
+# (C) Pywikibot team, 2015-2020
#
# Distributed under the terms of the MIT license.
#
-from __future__ import absolute_import, division, unicode_literals
-
import datetime

+from contextlib import suppress
from requests.exceptions import ConnectionError as RequestsConnectionError
+from urllib.parse import urlparse

-from pywikibot.tools import PY2
from scripts import weblinkchecker
from tests.aspects import unittest, require_modules, TestCase

-if not PY2:
- from urllib.parse import urlparse
-else:
- from urlparse import urlparse
-

@require_modules('memento_client')
class MementoTestCase(TestCase):
@@ -82,7 +76,5 @@


if __name__ == '__main__': # pragma: no cover
- try:
+ with suppress(SystemExit):
unittest.main()
- except SystemExit:
- pass

To view, visit change 609567. To unsubscribe, or for help writing mail filters, visit settings.

Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Iaa5889efdf9fa7f23cfa4301d3f3dcafacfc4636
Gerrit-Change-Number: 609567
Gerrit-PatchSet: 4
Gerrit-Owner: Xqt <info@gno.de>
Gerrit-Reviewer: Zhuyifei1999 <zhuyifei1999@gmail.com>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged