jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/659857 )
Change subject: Adopted context manager calls for assertRaises/assertRaisesRegex ......................................................................
Adopted context manager calls for assertRaises/assertRaisesRegex
Bug: T267801 Change-Id: I96dd3b0c6a8e13fe74715e7d7c98a27a095009b6 --- M tests/family_tests.py M tests/flow_edit_tests.py M tests/flow_tests.py M tests/http_tests.py M tests/i18n_tests.py M tests/interwiki_link_tests.py M tests/interwikidata_tests.py M tests/isbn_tests.py M tests/link_tests.py M tests/logentries_tests.py M tests/login_tests.py 11 files changed, 170 insertions(+), 135 deletions(-)
Approvals: Xqt: Looks good to me, approved jenkins-bot: Verified
diff --git a/tests/family_tests.py b/tests/family_tests.py index 203efb7..7d3dcd7 100644 --- a/tests/family_tests.py +++ b/tests/family_tests.py @@ -1,6 +1,6 @@ """Tests for the family module.""" # -# (C) Pywikibot team, 2014-2020 +# (C) Pywikibot team, 2014-2021 # # Distributed under the terms of the MIT license. # @@ -60,11 +60,10 @@
def test_family_load_invalid(self): """Test that an invalid family raised UnknownFamily exception.""" - self.assertRaisesRegex( - UnknownFamily, - self.UNKNOWNFAMILY_RE, - Family.load, - 'unknown') + with self.assertRaisesRegex( + UnknownFamily, + self.UNKNOWNFAMILY_RE): + Family.load('unknown')
def test_new_same_family_singleton(self): """Test that two same Family are the same object and equal.""" @@ -98,11 +97,10 @@ """Test that Family and string with different name are not equal.""" family = Family.load('wikipedia') other = 'unknown' - self.assertRaisesRegex( - UnknownFamily, - self.UNKNOWNFAMILY_RE, - family.__eq__, - other) + with self.assertRaisesRegex( + UnknownFamily, + self.UNKNOWNFAMILY_RE): + family.__eq__(other)
def test_get_obsolete_wp(self): """Test three types of obsolete codes.""" @@ -197,11 +195,11 @@ self.assertEqual(f.from_url(prefix + '/w/index.php?title=Foo'), 'vo')
# Text after $1 is not allowed - self.assertRaisesRegex( - ValueError, - r'Text after the $1 placeholder is not supported (T111513)', - f.from_url, - '//vo.wikipedia.org/wiki/$1/foo') + with self.assertRaisesRegex( + ValueError, + r'Text after the $1 placeholder is not supported' + r' (T111513)'): + f.from_url('//vo.wikipedia.org/wiki/$1/foo')
# the IWM may contain the wrong protocol, but it's only used to # determine a site so using HTTP or HTTPS is not an issue diff --git a/tests/flow_edit_tests.py b/tests/flow_edit_tests.py index afc31e3..d6120d3 100644 --- a/tests/flow_edit_tests.py +++ b/tests/flow_edit_tests.py @@ -198,11 +198,14 @@ content = 'I am a reply to a locked topic. This is not good!' topic = Topic(self.site, 'Topic:Smxnipjfs8umm1wt') # Reply (should raise a LockedPage exception) - self.assertRaises(LockedPage, topic.reply, content, 'wikitext') + with self.assertRaises(LockedPage): + topic.reply(content, 'wikitext') topic_root = topic.root - self.assertRaises(LockedPage, topic_root.reply, content, 'wikitext') + with self.assertRaises(LockedPage): + topic_root.reply(content, 'wikitext') topic_reply = topic.root.replies(force=True)[0] - self.assertRaises(LockedPage, topic_reply.reply, content, 'wikitext') + with self.assertRaises(LockedPage): + topic_reply.reply(content, 'wikitext')
class FlowTests(TestCase): diff --git a/tests/flow_tests.py b/tests/flow_tests.py index 8b084b3..5b8fed6 100644 --- a/tests/flow_tests.py +++ b/tests/flow_tests.py @@ -165,19 +165,26 @@ real_topic = Topic(self.site, 'Topic:Slbktgav46omarsd') fake_topic = Topic(self.site, 'Topic:Abcdefgh12345678') # Topic.from_topiclist_data - self.assertRaises(TypeError, Topic.from_topiclist_data, self.site, - '', {}) - self.assertRaises(TypeError, Topic.from_topiclist_data, board, 521, {}) - self.assertRaises(TypeError, Topic.from_topiclist_data, board, - 'slbktgav46omarsd', [0, 1, 2]) - self.assertRaises(NoPage, Topic.from_topiclist_data, board, - 'abc', {'stuff': 'blah'}) + with self.assertRaises(TypeError): + Topic.from_topiclist_data(self.site, '', {}) + with self.assertRaises(TypeError): + Topic.from_topiclist_data(board, 521, {}) + with self.assertRaises(TypeError): + Topic.from_topiclist_data(board, + 'slbktgav46omarsd', [0, 1, 2]) + with self.assertRaises(NoPage): + Topic.from_topiclist_data(board, + 'abc', {'stuff': 'blah'})
# Post.fromJSON - self.assertRaises(TypeError, Post.fromJSON, board, 'abc', {}) - self.assertRaises(TypeError, Post.fromJSON, real_topic, 1234, {}) - self.assertRaises(TypeError, Post.fromJSON, real_topic, 'abc', []) - self.assertRaises(NoPage, Post.fromJSON, fake_topic, 'abc', + with self.assertRaises(TypeError): + Post.fromJSON(board, 'abc', {}) + with self.assertRaises(TypeError): + Post.fromJSON(real_topic, 1234, {}) + with self.assertRaises(TypeError): + Post.fromJSON(real_topic, 'abc', []) + with self.assertRaises(NoPage): + Post.fromJSON(fake_topic, 'abc', {'posts': [], 'revisions': []})
def test_invalid_data(self): @@ -185,28 +192,36 @@ board = Board(self.site, 'Talk:Pywikibot test') real_topic = Topic(self.site, 'Topic:Slbktgav46omarsd') # Topic.from_topiclist_data - self.assertRaises(ValueError, Topic.from_topiclist_data, - board, 'slbktgav46omarsd', {'stuff': 'blah'}) - self.assertRaises(ValueError, Topic.from_topiclist_data, - board, 'slbktgav46omarsd', - {'posts': [], 'revisions': []}) - self.assertRaises(ValueError, Topic.from_topiclist_data, board, - 'slbktgav46omarsd', - {'posts': {'slbktgav46omarsd': ['123']}, - 'revisions': {'456': []}}) - self.assertRaises(AssertionError, Topic.from_topiclist_data, board, - 'slbktgav46omarsd', - {'posts': {'slbktgav46omarsd': ['123']}, - 'revisions': {'123': {'content': 789}}}) + with self.assertRaises(ValueError): + Topic.from_topiclist_data(board, + 'slbktgav46omarsd', {'stuff': 'blah'}) + with self.assertRaises(ValueError): + Topic.from_topiclist_data(board, + 'slbktgav46omarsd', + {'posts': [], 'revisions': []}) + with self.assertRaises(ValueError): + Topic.from_topiclist_data(board, + 'slbktgav46omarsd', + {'posts': {'slbktgav46omarsd': ['123']}, + 'revisions': {'456': []}}) + with self.assertRaises(AssertionError): + Topic.from_topiclist_data(board, + 'slbktgav46omarsd', + {'posts': {'slbktgav46omarsd': ['123']}, + 'revisions': {'123': {'content': 789}}})
# Post.fromJSON - self.assertRaises(ValueError, Post.fromJSON, real_topic, 'abc', {}) - self.assertRaises(ValueError, Post.fromJSON, real_topic, 'abc', + with self.assertRaises(ValueError): + Post.fromJSON(real_topic, 'abc', {}) + with self.assertRaises(ValueError): + Post.fromJSON(real_topic, 'abc', {'stuff': 'blah'}) - self.assertRaises(ValueError, Post.fromJSON, real_topic, 'abc', + with self.assertRaises(ValueError): + Post.fromJSON(real_topic, 'abc', {'posts': {'abc': ['123']}, 'revisions': {'456': []}}) - self.assertRaises(AssertionError, Post.fromJSON, real_topic, 'abc', + with self.assertRaises(AssertionError): + Post.fromJSON(real_topic, 'abc', {'posts': {'abc': ['123']}, 'revisions': {'123': {'content': 789}}})
diff --git a/tests/http_tests.py b/tests/http_tests.py index e8f8dcd..c0a4d63 100644 --- a/tests/http_tests.py +++ b/tests/http_tests.py @@ -1,6 +1,6 @@ """Tests for http module.""" # -# (C) Pywikibot team, 2014-2020 +# (C) Pywikibot team, 2014-2021 # # Distributed under the terms of the MIT license. # @@ -97,9 +97,10 @@
def test_https_cert_error(self): """Test if http.fetch respects disable_ssl_certificate_validation.""" - self.assertRaisesRegex( - pywikibot.FatalServerError, self.CERT_VERIFY_FAILED_RE, http.fetch, - 'https://testssl-expire-r2i2.disig.sk/index.en.html') + with self.assertRaisesRegex( + pywikibot.FatalServerError, + self.CERT_VERIFY_FAILED_RE): + http.fetch('https://testssl-expire-r2i2.disig.sk/index.en.html') http.session.close() # clear the connection
with warnings.catch_warnings(record=True) as warning_log: @@ -111,9 +112,10 @@ http.session.close() # clear the connection
# Verify that it now fails again - self.assertRaisesRegex( - pywikibot.FatalServerError, self.CERT_VERIFY_FAILED_RE, http.fetch, - 'https://testssl-expire-r2i2.disig.sk/index.en.html') + with self.assertRaisesRegex( + pywikibot.FatalServerError, + self.CERT_VERIFY_FAILED_RE): + http.fetch('https://testssl-expire-r2i2.disig.sk/index.en.html') http.session.close() # clear the connection
# Verify that the warning occurred @@ -139,26 +141,27 @@
def test_http_504(self): """Test that a HTTP 504 raises the correct exception.""" - self.assertRaisesRegex(pywikibot.Server504Error, - r'Server ([^:]+|[^:]+:[0-9]+) timed out', - http.fetch, - self.get_httpbin_url('/status/504')) + with self.assertRaisesRegex( + pywikibot.Server504Error, + r'Server ([^:]+|[^:]+:[0-9]+)' + r' timed out'): + http.fetch(self.get_httpbin_url('/status/504'))
def test_server_not_found(self): """Test server not found exception.""" - self.assertRaisesRegex(requests.exceptions.ConnectionError, - 'Max retries exceeded with url: /w/api.php', - http.fetch, - 'http://ru-sib.wikipedia.org/w/api.php', - default_error_handling=True) + with self.assertRaisesRegex( + requests.exceptions.ConnectionError, + 'Max retries exceeded with url: /w/api.php'): + http.fetch('http://ru-sib.wikipedia.org/w/api.php', + default_error_handling=True)
def test_invalid_scheme(self): """Test invalid scheme.""" # A InvalidSchema is raised within requests - self.assertRaisesRegex( - requests.exceptions.InvalidSchema, - "No connection adapters were found for u?'invalid://url'", - http.fetch, 'invalid://url') + with self.assertRaisesRegex( + requests.exceptions.InvalidSchema, + "No connection adapters were found for u?'invalid://url'"): + http.fetch('invalid://url')
def test_follow_redirects(self): """Test follow 301 redirects correctly.""" @@ -294,16 +297,18 @@ self.assertEqual(r.request.headers['user-agent'], 'ARBITRARY')
# Empty value - self.assertRaisesRegex(ValueError, - 'Invalid parameter: use_fake_user_agent', - http.fetch, self.get_httpbin_url('/status/200'), - use_fake_user_agent='') + with self.assertRaisesRegex( + ValueError, + 'Invalid parameter: use_fake_user_agent'): + http.fetch(self.get_httpbin_url('/status/200'), + use_fake_user_agent='')
# Parameter wrongly set to None - self.assertRaisesRegex(ValueError, - 'Invalid parameter: use_fake_user_agent', - http.fetch, self.get_httpbin_url('/status/200'), - use_fake_user_agent=None) + with self.assertRaisesRegex( + ValueError, + 'Invalid parameter: use_fake_user_agent'): + http.fetch(self.get_httpbin_url('/status/200'), + use_fake_user_agent=None)
# Manually overridden domains config.fake_user_agent_exceptions = { @@ -503,9 +508,10 @@ data=CharsetTestCase.LATIN1_BYTES) # Ignore WARNING: Encoding "utf16" requested but "utf-8" received with patch('pywikibot.warning'): - self.assertRaisesRegex( - UnicodeDecodeError, self.CODEC_CANT_DECODE_RE, - http._decide_encoding, resp, charset) + with self.assertRaisesRegex( + UnicodeDecodeError, + self.CODEC_CANT_DECODE_RE): + http._decide_encoding(resp, charset) self.assertEqual(resp.content, CharsetTestCase.LATIN1_BYTES)
try: @@ -514,9 +520,10 @@ resp.encoding = e
with patch('pywikibot.error'): - self.assertRaisesRegex( - UnicodeDecodeError, self.CODEC_CANT_DECODE_RE, - http.error_handling_callback, resp) + with self.assertRaisesRegex( + UnicodeDecodeError, + self.CODEC_CANT_DECODE_RE): + http.error_handling_callback(resp)
# TODO: this is a breaking change # self.assertRaisesRegex( diff --git a/tests/i18n_tests.py b/tests/i18n_tests.py index a0308de..4d31881 100644 --- a/tests/i18n_tests.py +++ b/tests/i18n_tests.py @@ -1,6 +1,6 @@ """Test i18n module.""" # -# (C) Pywikibot team, 2007-2020 +# (C) Pywikibot team, 2007-2021 # # Distributed under the terms of the MIT license. # @@ -295,8 +295,8 @@
def testNoEnglish(self): """Test translating into English with missing entry.""" - self.assertRaises(i18n.TranslationError, i18n.twtranslate, - 'en', 'test-no-english') + with self.assertRaises(i18n.TranslationError): + i18n.twtranslate('en', 'test-no-english')
class TestTWNTranslate(TWNTestCaseBase, AutoDeprecationTestCase): @@ -466,8 +466,8 @@
def test_missing(self): """Test a missing message from a real message bundle.""" - self.assertRaises(i18n.TranslationError, - i18n.twntranslate, 'en', 'pywikibot-missing-key') + with self.assertRaises(i18n.TranslationError): + i18n.twntranslate('en', 'pywikibot-missing-key')
class InputTestCase(TWNTestCaseBase, UserInterfaceLangTestCase, PwbTestCase): diff --git a/tests/interwiki_link_tests.py b/tests/interwiki_link_tests.py index 774f7e6..45be024 100644 --- a/tests/interwiki_link_tests.py +++ b/tests/interwiki_link_tests.py @@ -1,6 +1,6 @@ """Test Interwiki Link functionality.""" # -# (C) Pywikibot team, 2014-2020 +# (C) Pywikibot team, 2014-2021 # # Distributed under the terms of the MIT license. # @@ -81,11 +81,12 @@ def test_via_local_non_local(self): """Test de:translatewiki:Main Page on English Wikipedia.""" link = Link('de:translatewiki:Main Page', self.get_site('wp')) - self.assertRaisesRegex( - InvalidTitle, - 'de:translatewiki:Main Page links to a non local site i18n:i18n ' - 'via an interwiki link to wikipedia:de', - link.parse) + with self.assertRaisesRegex( + InvalidTitle, + 'de:translatewiki:Main Page links to a non local ' + 'site i18n:i18n ' + 'via an interwiki link to wikipedia:de'): + link.parse()
if __name__ == '__main__': # pragma: no cover diff --git a/tests/interwikidata_tests.py b/tests/interwikidata_tests.py index 2c9a932..ea7de14 100644 --- a/tests/interwikidata_tests.py +++ b/tests/interwikidata_tests.py @@ -1,6 +1,6 @@ """Tests for scripts/interwikidata.py.""" # -# (C) Pywikibot team, 2015-2020 +# (C) Pywikibot team, 2015-2021 # # Distributed under the terms of the MIT license. # @@ -90,17 +90,17 @@ def test_without_repo(self): """Test throwing error when site does not have a data repo.""" wt_page = pywikibot.Page(self.wt, 'User:Ladsgroup') - self.assertRaises(ValueError, DummyBot, generator=[wt_page], - site=self.wt) + with self.assertRaises(ValueError): + DummyBot(generator=[wt_page], + site=self.wt)
- self.assertRaisesRegex( - ValueError, - r'wikitech:en does not have a data repository, ' - r'use interwiki.py instead.', - interwikidata.IWBot, - generator=[pywikibot.Page(self.wt, 'User:Dalba')], - site=self.wt, - ) + with self.assertRaisesRegex( + ValueError, + r'wikitech:en does not have a data repository, ' + r'use interwiki.py instead.'): + interwikidata.IWBot( + generator=[pywikibot.Page(self.wt, 'User:Dalba')], + site=self.wt)
if __name__ == '__main__': # pragma: no cover diff --git a/tests/isbn_tests.py b/tests/isbn_tests.py index 46c0cb6..fde5053 100644 --- a/tests/isbn_tests.py +++ b/tests/isbn_tests.py @@ -1,6 +1,6 @@ """Tests for isbn script.""" # -# (C) Pywikibot team, 2014-2020 +# (C) Pywikibot team, 2014-2021 # # Distributed under the terms of the MIT license. # @@ -66,30 +66,34 @@ cc = CosmeticChangesToolkit(self.site, namespace=0)
# Invalid characters - self.assertRaisesRegex(AnyIsbnValidationException, - '|'.join((self.ISBN_DIGITERROR_RE, - self.ISBN_INVALIDERROR_RE, - self.ISBN_INVALIDLENGTHERROR_RE)), - cc.fix_ISBN, 'ISBN 0975229LOL') + with self.assertRaisesRegex( + AnyIsbnValidationException, + '|'.join((self.ISBN_DIGITERROR_RE, + self.ISBN_INVALIDERROR_RE, + self.ISBN_INVALIDLENGTHERROR_RE))): + cc.fix_ISBN('ISBN 0975229LOL') # Invalid checksum - self.assertRaisesRegex(AnyIsbnValidationException, - '|'.join((self.ISBN_CHECKSUMERROR_RE, - self.ISBN_INVALIDERROR_RE, - self.ISBN_INVALIDLENGTHERROR_RE, - self.ISBN_INVALIDCHECKERROR_RE)), - cc.fix_ISBN, 'ISBN 0975229801') + with self.assertRaisesRegex( + AnyIsbnValidationException, + '|'.join((self.ISBN_CHECKSUMERROR_RE, + self.ISBN_INVALIDERROR_RE, + self.ISBN_INVALIDLENGTHERROR_RE, + self.ISBN_INVALIDCHECKERROR_RE))): + cc.fix_ISBN('ISBN 0975229801') # Invalid length - self.assertRaisesRegex(AnyIsbnValidationException, - '|'.join((self.ISBN_DIGITERROR_RE, - self.ISBN_INVALIDERROR_RE, - self.ISBN_INVALIDLENGTHERROR_RE)), - cc.fix_ISBN, 'ISBN 09752298') + with self.assertRaisesRegex( + AnyIsbnValidationException, + '|'.join((self.ISBN_DIGITERROR_RE, + self.ISBN_INVALIDERROR_RE, + self.ISBN_INVALIDLENGTHERROR_RE))): + cc.fix_ISBN('ISBN 09752298') # X in the middle - self.assertRaisesRegex(AnyIsbnValidationException, - '|'.join((self.ISBN_INVALIDCHARERROR_RE, - self.ISBN_INVALIDERROR_RE, - self.ISBN_INVALIDLENGTHERROR_RE)), - cc.fix_ISBN, 'ISBN 09752X9801') + with self.assertRaisesRegex( + AnyIsbnValidationException, + '|'.join((self.ISBN_INVALIDCHARERROR_RE, + self.ISBN_INVALIDERROR_RE, + self.ISBN_INVALIDLENGTHERROR_RE))): + cc.fix_ISBN('ISBN 09752X9801')
def test_ignore_invalid_isbn(self): """Test fixing ISBN numbers with an invalid ISBN.""" diff --git a/tests/link_tests.py b/tests/link_tests.py index a84a330..3f17b1f5 100644 --- a/tests/link_tests.py +++ b/tests/link_tests.py @@ -942,15 +942,18 @@ def test_interwiki_namespace_without_title(self): """Test that Link doesn't allow links without a title.""" link = Link('en:Help:', self.get_site()) - self.assertRaisesRegex( - InvalidTitle, "'en:Help:' has no title.", link.parse) + with self.assertRaisesRegex( + InvalidTitle, + "'en:Help:' has no title."): + link.parse()
def test_no_text(self): """Test that Link doesn't allow empty.""" link = Link('', self.get_site()) - self.assertRaisesRegex( - InvalidTitle, 'The link does not contain a page title', - link.parse) + with self.assertRaisesRegex( + InvalidTitle, + 'The link does not contain a page title'): + link.parse()
def test_namespace_lookalike(self): """Test that Link does only detect valid namespaces.""" diff --git a/tests/logentries_tests.py b/tests/logentries_tests.py index b4bae4e..7201956 100644 --- a/tests/logentries_tests.py +++ b/tests/logentries_tests.py @@ -122,7 +122,8 @@ else: self.assertIsInstance(logentry.page(), pywikibot.Page) else: - self.assertRaises(KeyError, logentry.page) + with self.assertRaises(KeyError): + logentry.page()
self.assertEqual(logentry.type(), logtype) self.assertIsInstance(logentry.user(), str) @@ -312,7 +313,8 @@ self.assertIsInstance(logentry.title(), pywikibot.Page) self.assertIs(logentry.title(), logentry.page()) else: - self.assertRaises(KeyError, logentry.title) + with self.assertRaises(KeyError): + logentry.title() self.assertDeprecation() # T271044 self._reset_messages() # T271044
diff --git a/tests/login_tests.py b/tests/login_tests.py index d0693ac..40bc70a 100644 --- a/tests/login_tests.py +++ b/tests/login_tests.py @@ -4,7 +4,7 @@ e.g. used to test password-file based login. """ # -# (C) Pywikibot team, 2012-2020 +# (C) Pywikibot team, 2012-2021 # # Distributed under the terms of the MIT license. # @@ -72,8 +72,10 @@ del FakeConfig.usernames['*'] FakeConfig.usernames['*']['en'] = FakeUsername error_undefined_username = 'ERROR: username for.*is undefined.\nIf' - self.assertRaisesRegex(NoUsername, error_undefined_username, - LoginManager) + with self.assertRaisesRegex( + NoUsername, + error_undefined_username): + LoginManager() FakeConfig.usernames['*']['*'] = FakeUsername lm = LoginManager() self.assertEqual(lm.username, FakeUsername)
pywikibot-commits@lists.wikimedia.org