jenkins-bot has submitted this change. (
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/662107 )
Change subject: Adopted use of context Manager call for
assertRaises/assertRaisesRegex
......................................................................
Adopted use of context Manager call for assertRaises/assertRaisesRegex
Bug: T267801
Change-Id: I54196adfea71eb9071be6c797e84667bd7b0811f
---
M tests/siteinfo_tests.py
M tests/token_tests.py
M tests/tools_formatter_tests.py
M tests/tools_tests.py
M tests/ui_options_tests.py
M tests/user_tests.py
M tests/weblinkchecker_tests.py
M tests/wikibase_edit_tests.py
M tests/wikibase_tests.py
9 files changed, 158 insertions(+), 114 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/tests/siteinfo_tests.py b/tests/siteinfo_tests.py
index 4bb48e5..c3350ee 100644
--- a/tests/siteinfo_tests.py
+++ b/tests/siteinfo_tests.py
@@ -79,7 +79,8 @@
"""Test accessing a property not in siteinfo."""
not_exists = 'this-property-does-not-exist'
mysite = self.site
- self.assertRaises(KeyError, mysite.siteinfo.__getitem__, not_exists)
+ with self.assertRaises(KeyError):
+ mysite.siteinfo.__getitem__(not_exists)
self.assertNotIn(not_exists, mysite.siteinfo)
self.assertIsEmpty(mysite.siteinfo.get(not_exists))
self.assertFalse(entered_loop(mysite.siteinfo.get(not_exists)))
diff --git a/tests/token_tests.py b/tests/token_tests.py
index 56181c4..05b2471 100644
--- a/tests/token_tests.py
+++ b/tests/token_tests.py
@@ -99,8 +99,8 @@
def test_invalid_token(self):
"""Test invalid token."""
- self.assertRaises(pywikibot.Error, lambda t: self.mysite.tokens[t],
- 'invalidtype')
+ with self.assertRaises(pywikibot.Error):
+ self.mysite.tokens['invalidtype']
class TokenTestBase(TestCaseBase):
@@ -153,7 +153,8 @@
rc = rc[0]
# site.patrol() needs params
- self.assertRaises(pywikibot.Error, lambda x: list(x), mysite.patrol())
+ with self.assertRaises(pywikibot.Error):
+ list(mysite.patrol())
try:
result = list(mysite.patrol(rcid=rc['rcid']))
except api.APIError as error:
diff --git a/tests/tools_formatter_tests.py b/tests/tools_formatter_tests.py
index c570378..c4e92f7 100644
--- a/tests/tools_formatter_tests.py
+++ b/tests/tools_formatter_tests.py
@@ -1,6 +1,6 @@
"""Tests for the C{pywikibot.tools.formatter} module."""
#
-# (C) Pywikibot team, 2015-2020
+# (C) Pywikibot team, 2015-2021
#
# Distributed under the terms of the MIT license.
#
@@ -61,29 +61,33 @@
"""Test with colors in template string."""
self.assert_format('{0}{black}', '42\03{black}', 42)
self.assert_format('{ans}{black}', '42\03{black}', ans=42)
- self.assertRaisesRegex(
- ValueError, r'.*conversion.*', formatter.color_format,
- '{0}{black!r}', 42)
- self.assertRaisesRegex(
- ValueError, r'.*format spec.*', formatter.color_format,
- '{0}{black:03}', 42)
+ with self.assertRaisesRegex(
+ ValueError,
+ r'.*conversion.*'):
+ formatter.color_format('{0}{black!r}', 42)
+ with self.assertRaisesRegex(
+ ValueError,
+ r'.*format spec.*'):
+ formatter.color_format('{0}{black:03}', 42)
def test_marker(self):
r"""Test that the \03 marker is only allowed in front of colors."""
self.assert_format('{0}\03{black}', '42\03{black}', 42)
# literal before a normal field
- self.assertRaisesRegex(
- ValueError, r'.*\\03', formatter.color_format,
- '\03{0}{black}', 42)
+ with self.assertRaisesRegex(
+ ValueError,
+ r'.*\\03'):
+ formatter.color_format('\03{0}{black}', 42)
# literal before a color field
- self.assertRaisesRegex(
- ValueError, r'.*\\03', formatter.color_format,
- '{0}\03before{black}', 42)
+ with self.assertRaisesRegex(
+ ValueError,
+ r'.*\\03'):
+ formatter.color_format('{0}\03before{black}', 42)
def test_color_kwargs(self):
"""Test with a color as keyword argument."""
- self.assertRaises(ValueError,
- formatter.color_format, '{aqua}{black}', aqua=42)
+ with self.assertRaises(ValueError):
+ formatter.color_format('{aqua}{black}', aqua=42)
def test_non_ascii(self):
"""Test non-ASCII replacements."""
@@ -94,9 +98,10 @@
def test_bytes_format(self):
"""Test that using `bytes` is not allowed."""
- self.assertRaises(TypeError, formatter.color_format, b'{0}', 'a')
- self.assertRaises(TypeError, formatter.color_format, b'{black}{0}',
- 'a')
+ with self.assertRaises(TypeError):
+ formatter.color_format(b'{0}', 'a')
+ with self.assertRaises(TypeError):
+ formatter.color_format(b'{black}{0}', 'a')
def test_variant_colors(self):
"""Test variant colors with {color} parameter."""
diff --git a/tests/tools_tests.py b/tests/tools_tests.py
index 1335459..384332a 100644
--- a/tests/tools_tests.py
+++ b/tests/tools_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/python
"""Test tools package alone which don't fit into other tests."""
#
-# (C) Pywikibot team, 2015-2020
+# (C) Pywikibot team, 2015-2021
#
# Distributed under the terms of the MIT license.
import decimal
@@ -81,10 +81,10 @@
'used when bz2 and bz2file are not importable')
try:
tools.bz2 = ImportError(bz2_import_error)
- self.assertRaisesRegex(ImportError,
- bz2_import_error,
- self._get_content,
- self.base_file + '.bz2')
+ with self.assertRaisesRegex(
+ ImportError,
+ bz2_import_error):
+ self._get_content(self.base_file + '.bz2')
finally:
tools.bz2 = old_bz2
@@ -101,11 +101,11 @@
self.skipTest('7za not installed')
self.assertEqual(
self._get_content(self.base_file + '.7z'), self.original_content)
- self.assertRaisesRegex(OSError,
- 'Unexpected STDERR output from 7za ',
- self._get_content,
- self.base_file + '_invalid.7z',
- use_extension=True)
+ with self.assertRaisesRegex(
+ OSError,
+ 'Unexpected STDERR output from 7za '):
+ self._get_content(self.base_file + '_invalid.7z',
+ use_extension=True)
def test_open_archive_lzma(self):
"""Test open_archive with lzma compressor in the standard library."""
@@ -128,14 +128,14 @@
'used when lzma is not importable')
try:
tools.lzma = ImportError(lzma_import_error)
- self.assertRaisesRegex(ImportError,
- lzma_import_error,
- self._get_content,
- self.base_file + '.lzma')
- self.assertRaisesRegex(ImportError,
- lzma_import_error,
- self._get_content,
- self.base_file + '.xz')
+ with self.assertRaisesRegex(
+ ImportError,
+ lzma_import_error):
+ self._get_content(self.base_file + '.lzma')
+ with self.assertRaisesRegex(
+ ImportError,
+ lzma_import_error):
+ self._get_content(self.base_file + '.xz')
finally:
tools.lzma = old_lzma
@@ -169,23 +169,23 @@
def test_invalid_modes(self):
"""Test various invalid mode configurations."""
- self.assertRaisesRegex(ValueError,
- 'Invalid mode: "ra"',
- tools.open_archive,
- '/dev/null', 'ra') # two modes besides
- self.assertRaisesRegex(ValueError,
- 'Invalid mode: "rt"',
- tools.open_archive,
- '/dev/null', 'rt') # text mode
- self.assertRaisesRegex(ValueError,
- 'Invalid mode: "br"',
- tools.open_archive,
- '/dev/null', 'br') # binary at front
- self.assertRaisesRegex(ValueError,
- 'Magic number detection only when reading',
- tools.open_archive,
- # writing without extension
- '/dev/null', 'wb', False)
+ with self.assertRaisesRegex(
+ ValueError,
+ 'Invalid mode: "ra"'):
+ tools.open_archive('/dev/null', 'ra') # two modes besides
+ with self.assertRaisesRegex(
+ ValueError,
+ 'Invalid mode: "rt"'):
+ tools.open_archive('/dev/null', 'rt') # text mode
+ with self.assertRaisesRegex(
+ ValueError,
+ 'Invalid mode: "br"'):
+ tools.open_archive('/dev/null', 'br') # binary at front
+ with self.assertRaisesRegex(
+ ValueError,
+ 'Magic number detection only when reading'):
+ tools.open_archive('/dev/null', # writing without extension
+ 'wb', False)
def test_binary_mode(self):
"""Test that it uses binary mode."""
@@ -206,11 +206,10 @@
def test_write_archive_7z(self):
"""Test writing an archive as a 7z archive."""
- self.assertRaisesRegex(NotImplementedError,
- 'It is not possible to write a 7z file.',
- tools.open_archive,
- '/dev/null.7z',
- mode='wb')
+ with self.assertRaisesRegex(
+ NotImplementedError,
+ 'It is not possible to write a 7z file.'):
+ tools.open_archive('/dev/null.7z', mode='wb')
def test_write_archive_lzma(self):
"""Test writing a lzma archive."""
@@ -259,13 +258,12 @@
def test_conflict(self):
"""Test that it detects conflicts."""
- self.assertRaisesRegex(
- ValueError, '42', tools.merge_unique_dicts, self.dct1,
- **{'42': 'bad'})
- self.assertRaisesRegex(
- ValueError, '42', tools.merge_unique_dicts, self.dct1, self.dct1)
- self.assertRaisesRegex(
- ValueError, '42', tools.merge_unique_dicts, self.dct1, **self.dct1)
+ with self.assertRaisesRegex(ValueError, '42'):
+ tools.merge_unique_dicts(self.dct1, **{'42': 'bad'})
+ with self.assertRaisesRegex(ValueError, '42'):
+ tools.merge_unique_dicts(self.dct1, self.dct1)
+ with self.assertRaisesRegex(ValueError, '42'):
+ tools.merge_unique_dicts(self.dct1, **self.dct1)
class TestIsSliceWithEllipsis(TestCase):
@@ -451,7 +449,8 @@
else:
self.assertEqual(deduped, {1, 2, 3, 4})
- self.assertRaises(StopIteration, next, deduper)
+ with self.assertRaises(StopIteration):
+ next(deduper)
def _test_dedup_str(self, deduped, deduper, key=None):
"""Test filter_unique results for str."""
@@ -478,7 +477,8 @@
else:
self.assertEqual(deduped, {key(i) for i in self.strs})
- self.assertRaises(StopIteration, next, deduper)
+ with self.assertRaises(StopIteration):
+ next(deduper)
def test_set(self):
"""Test filter_unique with a set."""
@@ -530,7 +530,8 @@
self.assertIsEmpty(deduped)
for _ in self.decs:
self.assertEqual(id(next(deduper)), deduped.pop())
- self.assertRaises(StopIteration, next, deduper)
+ with self.assertRaises(StopIteration):
+ next(deduper)
# len(Decimal with distinct ids) != len(Decimal with distinct value).
deduper_ids = list(tools.filter_unique(self.decs, key=id))
self.assertNotEqual(len(deduper_ids), len(set(deduper_ids)))
@@ -558,7 +559,8 @@
self.assertEqual(deduped, [1, 3, 2])
last = next(gen2)
self.assertEqual(last, 4)
- self.assertRaises(StopIteration, next, gen2)
+ with self.assertRaises(StopIteration):
+ next(gen2)
def test_skip(self):
"""Test filter_unique with a container that skips items."""
@@ -586,7 +588,8 @@
self.assertEqual(deduped, {1, 3})
# And it should not resume
- self.assertRaises(StopIteration, next, deduper)
+ with self.assertRaises(StopIteration):
+ next(deduper)
deduped = AddStopList()
deduped.stop_list = [4]
@@ -596,7 +599,8 @@
self.assertEqual(deduped, {1, 2, 3})
# And it should not resume
- self.assertRaises(StopIteration, next, deduper)
+ with self.assertRaises(StopIteration):
+ next(deduper)
class TestFileModeChecker(TestCase):
diff --git a/tests/ui_options_tests.py b/tests/ui_options_tests.py
index 3013552..478f31b 100644
--- a/tests/ui_options_tests.py
+++ b/tests/ui_options_tests.py
@@ -1,6 +1,6 @@
"""Bot tests for input_choice options."""
#
-# (C) Pywikibot team, 2015-2020
+# (C) Pywikibot team, 2015-2021
#
# Distributed under the terms of the MIT license.
#
@@ -86,7 +86,8 @@
self.assertEqual(message('?', [option], None), '? (r<number> [1-5])')
self.assertEqual(message('?', [option], 'r3'),
'? (r<number> [1-[3]-5])')
- self.assertRaisesRegex(AttributeError, self.TEST_RE, option.test, 1)
+ with self.assertRaisesRegex(AttributeError, self.TEST_RE):
+ option.test(1)
self.assertFalse(option.test('0'))
self.assertFalse(option.test('r0'))
self.assertFalse(option.test('r6'))
@@ -98,8 +99,10 @@
def test_List(self):
"""Test ListOption."""
- self.assertRaisesRegex(ValueError, self.SEQ_EMPTY_RE,
- bot.ListOption, [])
+ with self.assertRaisesRegex(
+ ValueError,
+ self.SEQ_EMPTY_RE):
+ bot.ListOption([])
options = ['foo', 'bar']
option = bot.ListOption(options)
self.assertTrue(option.stop)
@@ -112,9 +115,14 @@
self.assertEqual(message('?', [option], None), '? (<number> [1])')
self.assertEqual(message('?', [option], '1'), '? (<number> [[1]])')
options.pop()
- self.assertRaisesRegex(ValueError, self.SEQ_EMPTY_RE, option.format,
- None)
- self.assertRaisesRegex(ValueError, self.SEQ_EMPTY_RE, option.format)
+ with self.assertRaisesRegex(
+ ValueError,
+ self.SEQ_EMPTY_RE):
+ option.format(None)
+ with self.assertRaisesRegex(
+ ValueError,
+ self.SEQ_EMPTY_RE):
+ option.format()
self.assertFalse(option.test('0'))
options += ['baz', 'quux', 'norf']
self.assertEqual(message('?', [option], None), '? (<number> [1-3])')
@@ -135,16 +143,20 @@
def test_showing_list(self):
"""Test ShowingListOption."""
- self.assertRaisesRegex(ValueError, self.SEQ_EMPTY_RE,
- bot.ShowingListOption, [])
+ with self.assertRaisesRegex(
+ ValueError,
+ self.SEQ_EMPTY_RE):
+ bot.ShowingListOption([])
options = ['foo', 'bar']
option = bot.ShowingListOption(options)
self.assertEqual(message('?', [option]), '? (<number> [1-2])')
def test_multiple_choice_list(self):
"""Test MultipleChoiceList."""
- self.assertRaisesRegex(ValueError, self.SEQ_EMPTY_RE,
- bot.MultipleChoiceList, [])
+ with self.assertRaisesRegex(
+ ValueError,
+ self.SEQ_EMPTY_RE):
+ bot.MultipleChoiceList([])
options = ['foo', 'bar']
option = bot.MultipleChoiceList(options)
self.assertTrue(option.stop)
@@ -164,8 +176,10 @@
def test_showing_multiple_choice_list(self):
"""Test ShowingMultipleChoiceList."""
- self.assertRaisesRegex(ValueError, self.SEQ_EMPTY_RE,
- bot.ShowingMultipleChoiceList, [])
+ with self.assertRaisesRegex(
+ ValueError,
+ self.SEQ_EMPTY_RE):
+ bot.ShowingMultipleChoiceList([])
options = ['foo', 'bar']
option = bot.ShowingMultipleChoiceList(options)
self.assertEqual(message('?', [option]), '? (<number> [1-2])')
diff --git a/tests/user_tests.py b/tests/user_tests.py
index 09bcca8..4093983 100644
--- a/tests/user_tests.py
+++ b/tests/user_tests.py
@@ -1,6 +1,6 @@
"""Tests for the User page."""
#
-# (C) Pywikibot team, 2016-2020
+# (C) Pywikibot team, 2016-2021
#
# Distributed under the terms of the MIT license.
#
@@ -133,10 +133,14 @@
self.assertFalse(user.isEmailable())
self.assertIn('invalid', user.getprops())
self.assertTrue(user._isAutoblock)
- self.assertRaisesRegex(AutoblockUser, 'This is an autoblock ID',
- user.getUserPage)
- self.assertRaisesRegex(AutoblockUser, 'This is an autoblock ID',
- user.getUserTalkPage)
+ with self.assertRaisesRegex(
+ AutoblockUser,
+ 'This is an autoblock ID'):
+ user.getUserPage()
+ with self.assertRaisesRegex(
+ AutoblockUser,
+ 'This is an autoblock ID'):
+ user.getUserTalkPage()
def test_autoblocked_user_with_namespace(self):
"""Test autoblocked user."""
@@ -153,10 +157,14 @@
self.assertFalse(user.isEmailable())
self.assertIn('invalid', user.getprops())
self.assertTrue(user._isAutoblock)
- self.assertRaisesRegex(AutoblockUser, 'This is an autoblock ID',
- user.getUserPage)
- self.assertRaisesRegex(AutoblockUser, 'This is an autoblock ID',
- user.getUserTalkPage)
+ with self.assertRaisesRegex(
+ AutoblockUser,
+ 'This is an autoblock ID'):
+ user.getUserPage()
+ with self.assertRaisesRegex(
+ AutoblockUser,
+ 'This is an autoblock ID'):
+ user.getUserTalkPage()
class TestUserMethods(DefaultSiteTestCase):
diff --git a/tests/weblinkchecker_tests.py b/tests/weblinkchecker_tests.py
index e756394..57782c2 100644
--- a/tests/weblinkchecker_tests.py
+++ b/tests/weblinkchecker_tests.py
@@ -1,6 +1,6 @@
"""weblinkchecker test module."""
#
-# (C) Pywikibot team, 2015-2020
+# (C) Pywikibot team, 2015-2021
#
# Distributed under the terms of the MIT license.
#
@@ -69,9 +69,10 @@
def test_invalid(self):
"""Test getting memento for invalid URL."""
# memento_client raises 'Exception', not a subclass.
- self.assertRaisesRegex(
- Exception, 'Only HTTP URIs are supported',
- self._get_archive_url, 'invalid')
+ with self.assertRaisesRegex(
+ Exception,
+ 'Only HTTP URIs are supported'):
+ self._get_archive_url('invalid')
if __name__ == '__main__': # pragma: no cover
diff --git a/tests/wikibase_edit_tests.py b/tests/wikibase_edit_tests.py
index 5d2a1a9..e0ba7de 100644
--- a/tests/wikibase_edit_tests.py
+++ b/tests/wikibase_edit_tests.py
@@ -5,7 +5,7 @@
class in edit_failiure_tests.py
"""
#
-# (C) Pywikibot team, 2014-2020
+# (C) Pywikibot team, 2014-2021
#
# Distributed under the terms of the MIT license.
#
diff --git a/tests/wikibase_tests.py b/tests/wikibase_tests.py
index 6a9740b..c28d2bf 100644
--- a/tests/wikibase_tests.py
+++ b/tests/wikibase_tests.py
@@ -349,7 +349,8 @@
t = pywikibot.WbTime(site=repo, year=-2010, hour=12, minute=43)
regex = r'^You cannot turn BC dates into a Timestamp$'
- self.assertRaisesRegex(ValueError, regex, t.toTimestamp)
+ with self.assertRaisesRegex(ValueError, regex):
+ t.toTimestamp()
t = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=0)
@@ -1065,13 +1066,17 @@
self.assertEqual(numeric_id, 7)
self.assertFalse(hasattr(item, '_content'))
regex = r"^Page .+ doesn't exist\.$"
- self.assertRaisesRegex(pywikibot.NoPage, regex, item.get)
+ with self.assertRaisesRegex(
+ pywikibot.NoPage,
+ regex):
+ item.get()
self.assertTrue(hasattr(item, '_content'))
self.assertEqual(item.id, 'Q7')
self.assertEqual(item.getID(), 'Q7')
self.assertEqual(item._link._title, 'Q7')
self.assertEqual(item.title(), 'Q7')
- self.assertRaisesRegex(pywikibot.NoPage, regex, item.get)
+ with self.assertRaisesRegex(pywikibot.NoPage, regex):
+ item.get()
self.assertTrue(hasattr(item, '_content'))
self.assertEqual(item._link._title, 'Q7')
self.assertEqual(item.getID(), 'Q7')
@@ -1085,7 +1090,8 @@
self.assertFalse(item.exists())
self.assertEqual(item.getID(), 'Q9999999999999999999')
regex = r"^Page .+ doesn't exist\.$"
- self.assertRaisesRegex(pywikibot.NoPage, regex, item.get)
+ with self.assertRaisesRegex(pywikibot.NoPage, regex):
+ item.get()
def test_fromPage_noprops(self):
"""Test item from page without properties."""
@@ -1264,7 +1270,8 @@
# without a full debug log.
# It should raise NoPage on the source page, with title 'Test page'
# as that is what the bot operator needs to see in the log output.
- self.assertRaisesRegex(pywikibot.NoPage, 'Test page', item.get)
+ with self.assertRaisesRegex(pywikibot.NoPage, 'Test page'):
+ item.get()
def test_from_entity_uri(self):
"""Test ItemPage.from_entity_uri."""
@@ -1329,8 +1336,8 @@
self.assertFalse(item.isRedirectPage())
self.assertTrue(item.exists())
regex = r'^Page .+ is not a redirect page\.$'
- self.assertRaisesRegex(pywikibot.IsNotRedirectPage, regex,
- item.getRedirectTarget)
+ with self.assertRaisesRegex(pywikibot.IsNotRedirectPage, regex):
+ item.getRedirectTarget()
def test_redirect_item(self):
"""Test redirect item."""
@@ -1344,7 +1351,8 @@
self.assertEqual(item.getRedirectTarget(), target)
self.assertIsInstance(item.getRedirectTarget(), ItemPage)
regex = r'^Page .+ is a redirect page\.$'
- self.assertRaisesRegex(pywikibot.IsRedirectPage, regex, item.get)
+ with self.assertRaisesRegex(pywikibot.IsRedirectPage, regex):
+ item.get()
def test_redirect_item_without_get(self):
"""Test redirect item without explicit get operation."""
@@ -2114,9 +2122,11 @@
wikidata = self.get_repo()
page = WikibasePage(wikidata)
regex = r' object has no attribute '
- self.assertRaisesRegex(AttributeError, regex, page.namespace)
+ with self.assertRaisesRegex(AttributeError, regex):
+ page.namespace()
page = WikibasePage(wikidata, title='')
- self.assertRaisesRegex(AttributeError, regex, page.namespace)
+ with self.assertRaisesRegex(AttributeError, regex):
+ page.namespace()
page = WikibasePage(wikidata, ns=0)
self.assertEqual(page.namespace(), 0)
@@ -2331,8 +2341,8 @@
regex = r' has no data repository$'
with self.assertRaisesRegex(pywikibot.WikiBaseError, regex):
ItemPage.fromPage(self.wdp)
- self.assertRaisesRegex(pywikibot.WikiBaseError, regex,
- self.wdp.data_item)
+ with self.assertRaisesRegex(pywikibot.WikiBaseError, regex):
+ self.wdp.data_item()
def test_has_data_repository(self, key):
"""Test that site has no data repository."""
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/662107
To unsubscribe, or for help writing mail filters, visit
https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I54196adfea71eb9071be6c797e84667bd7b0811f
Gerrit-Change-Number: 662107
Gerrit-PatchSet: 4
Gerrit-Owner: Homeboy 445 <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged
_______________________________________________
Pywikibot-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/pywikibot-commits