jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/370660 )
Change subject: [IMPR] Use with contextlib.suppress context manager ......................................................................
[IMPR] Use with contextlib.suppress context manager
use contextlib.suppress context manager to ignore specified exceptions and replace ignored exceptions with this method
Change-Id: I5bad43fe3bc56c0c268026029394e3610ebbe8b6 --- M pywikibot/i18n.py M scripts/category.py M scripts/category_redirect.py M scripts/imageuncat.py M scripts/interwiki.py M scripts/isbn.py M scripts/patrol.py M scripts/redirect.py M scripts/weblinkchecker.py M tests/category_bot_tests.py M tests/category_tests.py M tests/cosmetic_changes_tests.py M tests/deletionbot_tests.py M tests/disambredir_tests.py M tests/edit_failure_tests.py M tests/edit_tests.py M tests/eventstreams_tests.py M tests/fixes_tests.py M tests/interwiki_graph_tests.py M tests/interwiki_link_tests.py M tests/interwikidata_tests.py M tests/link_tests.py M tests/mediawikiversion_tests.py M tests/oauth_tests.py M tests/patrolbot_tests.py M tests/protectbot_tests.py M tests/replacebot_tests.py M tests/sparql_tests.py M tests/tests_tests.py M tests/textlib_tests.py M tests/timestamp_tests.py M tests/timestripper_tests.py M tests/ui_options_tests.py M tests/ui_tests.py M tests/upload_tests.py M tests/uploadbot_tests.py M tests/uploadscript_tests.py M tests/wikibase_edit_tests.py M tests/xmlreader_tests.py 39 files changed, 198 insertions(+), 320 deletions(-)
Approvals: Hazard-SJ: Looks good to me, but someone else must approve Xqt: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py index d748422..287a86c 100644 --- a/pywikibot/i18n.py +++ b/pywikibot/i18n.py @@ -28,6 +28,7 @@
from collections.abc import Mapping from collections import defaultdict +from contextlib import suppress from textwrap import fill from warnings import warn
@@ -523,7 +524,7 @@ else: self.source = source self.index = -1 - super(_PluralMappingAlias, self).__init__() + super().__init__()
def __getitem__(self, key): self.index += 1 @@ -626,11 +627,10 @@ # else we check for PLURAL variants trans = _extract_plural(code, trans, plural_parameters) if parameters: - try: + # On error: parameter is for PLURAL variants only, + # don't change the string + with suppress(KeyError, TypeError): return trans % parameters - except (KeyError, TypeError): - # parameter is for PLURAL variants only, don't change the string - pass return trans
@@ -759,10 +759,8 @@ # This is called due to the old twntranslate function which ignored # KeyError. Instead only_plural should be used. if isinstance(parameters.source, dict): - try: + with suppress(KeyError): trans %= parameters.source - except KeyError: - pass parameters = None
if parameters is not None and not isinstance(parameters, Mapping): diff --git a/scripts/category.py b/scripts/category.py index 1989a3a..51b19aa 100755 --- a/scripts/category.py +++ b/scripts/category.py @@ -124,6 +124,7 @@ import pickle import re
+from contextlib import suppress from operator import methodcaller from typing import Optional, Set
@@ -170,7 +171,7 @@ def __init__(self, follow_redirects=False, edit_redirects=False, create=False, **kwargs): """Initializer.""" - super(CategoryPreprocess, self).__init__(**kwargs) + super().__init__(**kwargs) self.follow_redirects = follow_redirects self.edit_redirects = edit_redirects self.create = create @@ -374,16 +375,11 @@ } # store dump to disk in binary format with open_archive(filename, 'wb') as f: - try: + with suppress(pickle.PicklingError): pickle.dump(databases, f, protocol=config.pickle_protocol) - except pickle.PicklingError: - pass else: - try: + with suppress(EnvironmentError): os.remove(filename) - except EnvironmentError: - pass - else: pywikibot.output('Database is empty. {} removed' .format(config.shortpath(filename)))
@@ -983,9 +979,8 @@
site = pywikibot.Site() self.cat = pywikibot.Category(site, cat_title) - super(CategoryTidyRobot, self).__init__( - generator=pagegenerators.PreloadingGenerator( - self.cat.articles(namespaces=namespaces))) + super().__init__(generator=pagegenerators.PreloadingGenerator( + self.cat.articles(namespaces=namespaces)))
@deprecated_args(article='member') def move_to_category(self, member, original_cat, current_cat) -> None: diff --git a/scripts/category_redirect.py b/scripts/category_redirect.py index 0931e60..6f26920 100755 --- a/scripts/category_redirect.py +++ b/scripts/category_redirect.py @@ -25,27 +25,21 @@
""" # -# (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 pickle import re import time
+from contextlib import suppress from datetime import timedelta
import pywikibot
from pywikibot import i18n, pagegenerators, config from pywikibot.bot import SingleSiteBot -from pywikibot.tools import PY2 - -if PY2: - import cPickle as pickle # noqa: N813 -else: - import pickle
class CategoryRedirectBot(SingleSiteBot): @@ -58,7 +52,7 @@ 'tiny': False, # use Non-empty category redirects only 'delay': 7, # cool down delay in days }) - super(CategoryRedirectBot, self).__init__(**kwargs) + super().__init__(**kwargs) self.cooldown = self.getOption('delay') self.catprefix = self.site.namespace(14) + ':' self.log_text = [] @@ -353,18 +347,14 @@ if cat_title not in record: # make sure every redirect has a record entry record[cat_title] = {today: None} - try: + with suppress(pywikibot.Error): newredirs.append('*# {} → {}'.format( cat.title(as_link=True, textlink=True), cat.getCategoryRedirectTarget().title( as_link=True, textlink=True))) - except pywikibot.Error: - pass # do a null edit on cat - try: + with suppress(Exception): cat.save() - except Exception: - pass
# delete record entries for non-existent categories for cat_name in list(record.keys()): @@ -407,10 +397,8 @@ self.problems.append(message) # do a null edit on cat to update any special redirect # categories this wiki might maintain - try: + with suppress(Exception): cat.save() - except Exception: - pass continue if dest.isCategoryRedirect(): double = dest.getCategoryRedirectTarget() @@ -420,10 +408,8 @@ {'oldcat': dest.title(as_link=True, textlink=True)}) self.log_text.append(message) # do a null edit on cat - try: + with suppress(Exception): cat.save() - except Exception: - pass else: message = i18n.twtranslate( self.site, 'category_redirect-log-double', { @@ -472,10 +458,8 @@ self.log_text.append(message) counts[cat_title] = found # do a null edit on cat - try: + with suppress(Exception): cat.save() - except Exception: - pass
with open(datafile, 'wb') as f: pickle.dump(record, f, protocol=config.pickle_protocol) diff --git a/scripts/imageuncat.py b/scripts/imageuncat.py index 5151df9..0881784 100755 --- a/scripts/imageuncat.py +++ b/scripts/imageuncat.py @@ -11,12 +11,11 @@ ¶ms; """ # -# (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 - +from contextlib import suppress from datetime import timedelta
import pywikibot @@ -1299,15 +1298,8 @@ """ newtext = page.get() + puttext pywikibot.showDiff(page.get(), newtext) - try: + with suppress(pywikibot.EditConflict, pywikibot.LockedPage): page.put(newtext, putcomment) - except pywikibot.EditConflict: - # Skip this page - pass - except pywikibot.LockedPage: - # Skip this page - pass - return
def main(*args): diff --git a/scripts/interwiki.py b/scripts/interwiki.py index 4ed77c1..e071403 100755 --- a/scripts/interwiki.py +++ b/scripts/interwiki.py @@ -333,8 +333,6 @@ # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals - import codecs import os import pickle @@ -343,6 +341,7 @@ import sys
from collections import defaultdict +from contextlib import suppress from itertools import chain from textwrap import fill
@@ -399,7 +398,7 @@ }
-class InterwikiBotConfig(object): +class InterwikiBotConfig:
"""Container class for interwikibot's settings."""
@@ -546,7 +545,7 @@ return True
-class PageTree(object): +class PageTree:
""" Structure to manipulate a set of pages. @@ -578,11 +577,8 @@
def filter(self, site): """Iterate over pages that are in Site site.""" - try: - for page in self.tree[site]: - yield page - except KeyError: - pass + with suppress(KeyError): + yield from self.tree[site]
def __len__(self): """Length of the object.""" @@ -596,20 +592,14 @@
def remove(self, page): """Remove a page from the tree.""" - try: + with suppress(ValueError): self.tree[page.site].remove(page) - except ValueError: - pass - else: self.size -= 1
def removeSite(self, site): """Remove all pages from Site site.""" - try: + with suppress(KeyError): self.size -= len(self.tree[site]) - except KeyError: - pass - else: del self.tree[site]
def siteCounts(self): @@ -619,9 +609,7 @@
def __iter__(self): """Iterate through all items of the tree.""" - for site, plist in self.tree.items(): - for page in plist: - yield page + yield from chain.from_iterable(self.tree.values())
class Subject(interwiki_graph.Subject): @@ -697,7 +685,7 @@ """ self.conf = conf
- super(Subject, self).__init__(originPage) + super().__init__(originPage)
self.repoPage = None # todo is a list of all pages that still need to be analyzed. @@ -1625,28 +1613,22 @@
# remove interwiki links to ignore for iw in re.finditer(r'<!-- *\[\[(.*?:.*?)\]\] *-->', pagetext): - try: + with suppress(KeyError, + pywikibot.SiteDefinitionError, + pywikibot.InvalidTitle): ignorepage = pywikibot.Page(page.site, iw.groups()[0]) - if (new[ignorepage.site] == ignorepage) and \ - (ignorepage.site != page.site): - if (ignorepage not in interwikis): - pywikibot.output( - 'Ignoring link to %(to)s for %(from)s' - % {'to': ignorepage, - 'from': page}) + if new[ignorepage.site] == ignorepage \ + and ignorepage.site != page.site: + param = {'to': ignorepage, 'from': page} + if ignorepage not in interwikis: + pywikibot.output('Ignoring link to {to} for {from}' + .format_map(param)) new.pop(ignorepage.site) else: pywikibot.output( - 'NOTE: Not removing interwiki from %(from)s to ' - '%(to)s (exists both commented and non-commented)' - % {'to': ignorepage, - 'from': page}) - except KeyError: - pass - except pywikibot.SiteDefinitionError: - pass - except pywikibot.InvalidTitle: - pass + 'NOTE: Not removing interwiki from {from} to ' + '{to} (exists both commented and non-commented)' + .format_map(param))
# sanity check - the page we are fixing must be the only one for that # site. @@ -1885,7 +1867,7 @@ pywikibot.output('ERROR: could not report backlinks')
-class InterwikiBot(object): +class InterwikiBot:
""" A class keeping track of a list of subjects. @@ -1984,11 +1966,10 @@ .format(page)) continue if page.namespace() == 10: - try: + loc = None + with suppress(KeyError): tmpl, loc = moved_links[page.site.code] del tmpl - except KeyError: - loc = None if loc is not None and loc in page.title(): pywikibot.output( 'Skipping: {} is a templates subpage' @@ -2074,11 +2055,9 @@ break # If we have a few, getting the home language is a good thing. if not self.conf.restore_all: - try: + with suppress(KeyError): if self.counts[pywikibot.Site()] > 4: return pywikibot.Site() - except KeyError: - pass # If getting the home language doesn't make sense, see how many # foreign page queries we can find. return self.maxOpenSite() @@ -2216,16 +2195,16 @@
def botMayEdit(page): """Test for allowed edits.""" - try: - tmpl, loc = moved_links[page.site.code] - except KeyError: - tmpl = [] + tmpl = [] + with suppress(KeyError): + tmpl, _ = moved_links[page.site.code] + if not isinstance(tmpl, list): tmpl = [tmpl] - try: + + with suppress(KeyError): tmpl += ignoreTemplates[page.site.code] - except KeyError: - pass + tmpl += ignoreTemplates['_default'] if tmpl != []: templates = page.templatesWithParams() @@ -2430,17 +2409,13 @@ pywikibot.output('Script terminated sucessfully.') finally: if dumpFileName: - try: + with suppress(ValueError): restoredFiles.remove(dumpFileName) - except ValueError: - pass for dumpFileName in restoredFiles: - try: + with suppress(OSError): os.remove(dumpFileName) pywikibot.output('Dumpfile {0} deleted' .format(dumpFileName.split('\')[-1])) - except OSError: - pass
if __name__ == '__main__': diff --git a/scripts/isbn.py b/scripts/isbn.py index 2f53779..d7190e7 100755 --- a/scripts/isbn.py +++ b/scripts/isbn.py @@ -39,10 +39,9 @@ # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals - import re
+from contextlib import suppress from functools import partial
import pywikibot @@ -52,10 +51,8 @@ try: import stdnum.isbn except ImportError: - try: + with suppress(ImportError): import isbnlib - except ImportError: - pass
docuReplacements = { '¶ms;': pagegenerators.parameterHelp, @@ -168,7 +165,7 @@ 'to13': False, 'format': False, }) - super(IsbnBot, self).__init__(**kwargs) + super().__init__(**kwargs)
self.generator = generator self.isbnR = re.compile(r'(?<=ISBN )(?P<code>[\d-]+[Xx]?)') @@ -226,7 +223,7 @@ self.isbn_10_prop_id = kwargs.pop('prop-isbn-10', None) self.isbn_13_prop_id = kwargs.pop('prop-isbn-13', None)
- super(IsbnWikibaseBot, self).__init__(**kwargs) + super().__init__(**kwargs)
self.generator = generator if self.isbn_10_prop_id is None: diff --git a/scripts/patrol.py b/scripts/patrol.py index 9e35343..361b005 100755 --- a/scripts/patrol.py +++ b/scripts/patrol.py @@ -42,15 +42,14 @@
""" # -# (C) Pywikibot team, 2011-2019 +# (C) Pywikibot team, 2011-2020 # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals - import time
from collections import defaultdict +from contextlib import suppress
try: import mwparserfromhell @@ -96,7 +95,7 @@ 'versionchecktime': 300, 'autopatroluserns': False }) - super(PatrolBot, self).__init__(site, **kwargs) + super().__init__(site, **kwargs) self.recent_gen = True self.user = None if self.getOption('whitelist'): @@ -266,10 +265,9 @@ if self.site.family.name != 'wikisource': return False
- try: + author_ns = 0 + with suppress(AttributeError, KeyError): author_ns = self.site.family.authornamespaces[self.site.lang][0] - except (AttributeError, KeyError): - author_ns = 0
author_ns_prefix = self.site.namespace(author_ns) + ':' if title.startswith(author_ns_prefix): diff --git a/scripts/redirect.py b/scripts/redirect.py index 69cf441..de3c865 100755 --- a/scripts/redirect.py +++ b/scripts/redirect.py @@ -76,6 +76,7 @@ # import datetime
+from contextlib import suppress from typing import Any, Dict, Generator, List, Optional, Set, Tuple, Union
import pywikibot @@ -274,13 +275,11 @@ try: if pages[target]: final = target - try: + with suppress(KeyError): while result <= maxlen: result += 1 final = redirects[final] # result = None - except KeyError: - pass except KeyError: result = None yield (redirect, result, target, final) @@ -311,15 +310,13 @@ yield self.page_title else: pywikibot.output('Retrieving broken redirect special page...') - for page in self.site.preloadpages(self.site.broken_redirects()): - yield page + yield from self.site.preloadpages(self.site.broken_redirects())
def retrieve_double_redirects(self) -> Generator[ Union[str, pywikibot.Page], None, None]: """Retrieve double redirects.""" if self.use_move_log: - for redir_page in self.get_moved_pages_redirects(): - yield redir_page + yield from self.get_moved_pages_redirects() elif self.use_api: count = 0 for (pagetitle, type, target, final) \ @@ -344,8 +341,7 @@ yield self.page_title else: pywikibot.output('Retrieving double redirect special page...') - for page in self.site.preloadpages(self.site.double_redirects()): - yield page + yield from self.site.preloadpages(self.site.double_redirects())
def get_moved_pages_redirects(self) -> Generator[pywikibot.Page, None, None]: @@ -378,9 +374,8 @@ # moved_page is now a redirect, so any redirects pointing # to it need to be changed try: - for page in moved_page.getReferences(follow_redirects=True, - filter_redirects=True): - yield page + yield from moved_page.getReferences(follow_redirects=True, + filter_redirects=True) except (pywikibot.CircularRedirect, pywikibot.InterwikiRedirectPage, pywikibot.NoPage, @@ -497,10 +492,8 @@ pywikibot.exception() except pywikibot.NoPage: movedTarget = None - try: + with suppress(pywikibot.NoMoveTarget): movedTarget = targetPage.moved_target() - except pywikibot.NoMoveTarget: - pass if movedTarget: if not movedTarget.exists(): # FIXME: Test to another move diff --git a/scripts/weblinkchecker.py b/scripts/weblinkchecker.py index 8076e84..77a659b 100755 --- a/scripts/weblinkchecker.py +++ b/scripts/weblinkchecker.py @@ -129,6 +129,7 @@ import pywikibot
from pywikibot import comms, i18n, config, pagegenerators, textlib, config2 + from pywikibot.bot import ExistingPageBot, SingleSiteBot, suggest_help from pywikibot.pagegenerators import ( XMLDumpPageGenerator as _XMLDumpPageGenerator, @@ -718,9 +719,8 @@ @return: True if previously found dead, else returns False. """ if url in self.historyDict: - with self.semaphore: - with suppress(KeyError): # Not sure why this can happen - del self.historyDict[url] + with self.semaphore, suppress(KeyError): + del self.historyDict[url] return True
return False diff --git a/tests/category_bot_tests.py b/tests/category_bot_tests.py index 601ad92..8cb719f 100644 --- a/tests/category_bot_tests.py +++ b/tests/category_bot_tests.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- """Tests for the category bot script.""" # -# (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 +from contextlib import suppress
import pywikibot from pywikibot import BaseSite @@ -113,7 +113,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/category_tests.py b/tests/category_tests.py index 25c2ee3..e25a5d1 100644 --- a/tests/category_tests.py +++ b/tests/category_tests.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- """Tests for the Category class.""" # -# (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
import pywikibot import pywikibot.page @@ -248,7 +248,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/cosmetic_changes_tests.py b/tests/cosmetic_changes_tests.py index 07bb02e..d9be2b4 100644 --- a/tests/cosmetic_changes_tests.py +++ b/tests/cosmetic_changes_tests.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- """Test cosmetic_changes 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 +from contextlib import suppress
from pywikibot.cosmetic_changes import CosmeticChangesToolkit
@@ -519,7 +519,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/deletionbot_tests.py b/tests/deletionbot_tests.py index 4709825..09fd736 100644 --- a/tests/deletionbot_tests.py +++ b/tests/deletionbot_tests.py @@ -5,7 +5,7 @@ # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals +from contextlib import suppress
import pywikibot import pywikibot.page @@ -128,7 +128,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/disambredir_tests.py b/tests/disambredir_tests.py index 86b7a95..1cf1e2e 100644 --- a/tests/disambredir_tests.py +++ b/tests/disambredir_tests.py @@ -5,11 +5,11 @@ These tests write to the wiki. """ # -# (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 +from contextlib import suppress
import pywikibot
@@ -154,7 +154,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/edit_failure_tests.py b/tests/edit_failure_tests.py index 05df87d..ae23030 100644 --- a/tests/edit_failure_tests.py +++ b/tests/edit_failure_tests.py @@ -12,7 +12,7 @@ # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals +from contextlib import suppress
import pywikibot from pywikibot import ( @@ -208,7 +208,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/edit_tests.py b/tests/edit_tests.py index 403cbf0..639b05b 100644 --- a/tests/edit_tests.py +++ b/tests/edit_tests.py @@ -1,14 +1,14 @@ # -*- coding: utf-8 -*- """Tests for editing pages.""" # -# (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 time
+from contextlib import suppress + import pywikibot
from pywikibot import config @@ -216,7 +216,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/eventstreams_tests.py b/tests/eventstreams_tests.py index dc2c978..cce5f0d 100644 --- a/tests/eventstreams_tests.py +++ b/tests/eventstreams_tests.py @@ -5,10 +5,10 @@ # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals - import json
+from contextlib import suppress + from tests import mock
from pywikibot.comms.eventstreams import EventStreams, EventSource @@ -311,7 +311,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/fixes_tests.py b/tests/fixes_tests.py index 84008b1..a0d820a 100644 --- a/tests/fixes_tests.py +++ b/tests/fixes_tests.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- """Tests for fixes 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 +from contextlib import suppress
from pywikibot import fixes
@@ -45,7 +45,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/interwiki_graph_tests.py b/tests/interwiki_graph_tests.py index e1b64d9..1095599 100644 --- a/tests/interwiki_graph_tests.py +++ b/tests/interwiki_graph_tests.py @@ -6,7 +6,7 @@ # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals +from contextlib import suppress
from pywikibot import interwiki_graph
@@ -80,7 +80,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/interwiki_link_tests.py b/tests/interwiki_link_tests.py index 50b70ef..2cbea5d 100644 --- a/tests/interwiki_link_tests.py +++ b/tests/interwiki_link_tests.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- """Test Interwiki Link functionality.""" # -# (C) Pywikibot team, 2014-2018 +# (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 import config2 as config
@@ -90,7 +90,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/interwikidata_tests.py b/tests/interwikidata_tests.py index e0255a1..0699665 100644 --- a/tests/interwikidata_tests.py +++ b/tests/interwikidata_tests.py @@ -5,7 +5,7 @@ # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals +from contextlib import suppress
import pywikibot
@@ -105,7 +105,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/link_tests.py b/tests/link_tests.py index 9d2af0c..cf891e9 100644 --- a/tests/link_tests.py +++ b/tests/link_tests.py @@ -5,10 +5,10 @@ # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals - import re
+from contextlib import suppress + import pywikibot
from pywikibot import config2 as config @@ -205,13 +205,13 @@
def setUp(self): """Set up test case.""" - super(Issue10254TestCase, self).setUp() + super().setUp() self._orig_unicodedata = pywikibot.page.unicodedata
def tearDown(self): """Tear down test case.""" pywikibot.page.unicodedata = self._orig_unicodedata - super(Issue10254TestCase, self).tearDown() + super().tearDown()
def test_no_change(self): """Test T102461 (Python issue 10254) is not encountered.""" @@ -1032,7 +1032,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/mediawikiversion_tests.py b/tests/mediawikiversion_tests.py index fdab731..94f03e9 100644 --- a/tests/mediawikiversion_tests.py +++ b/tests/mediawikiversion_tests.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- """Tests for the tools.MediaWikiVersion class.""" # -# (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 - +from contextlib import suppress
from pywikibot.tools import MediaWikiVersion
@@ -93,7 +92,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/oauth_tests.py b/tests/oauth_tests.py index 00cbdee..8a6e87f 100644 --- a/tests/oauth_tests.py +++ b/tests/oauth_tests.py @@ -1,14 +1,14 @@ # -*- coding: utf-8 -*- """Test OAuth functionality.""" # -# (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
+from contextlib import suppress + from pywikibot.login import OauthLoginManager
from tests.aspects import ( @@ -35,7 +35,7 @@
def setUp(self): """Check if OAuth extension is installed and OAuth tokens are set.""" - super(OAuthSiteTestCase, self).setUp() + super().setUp() self.site = self.get_site() if not self.site.has_extension('OAuth'): self.skipTest('OAuth extension not loaded on test site') @@ -83,7 +83,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/patrolbot_tests.py b/tests/patrolbot_tests.py index 15d3217..6a89e9a 100644 --- a/tests/patrolbot_tests.py +++ b/tests/patrolbot_tests.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- """Tests for the patrol script.""" # -# (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 - +from contextlib import suppress
from scripts import patrol
@@ -45,7 +44,7 @@
def setUp(self): """Create a bot dummy instance.""" - super(TestPatrolBot, self).setUp() + super().setUp() self.bot = DummyPatrolBot(self.site)
def test_parse_page_tuples(self): @@ -81,7 +80,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/protectbot_tests.py b/tests/protectbot_tests.py index ae00b1e..1f11309 100644 --- a/tests/protectbot_tests.py +++ b/tests/protectbot_tests.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- """Tests for scripts/protect.py.""" # -# (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
import pywikibot import pywikibot.page @@ -61,7 +61,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/replacebot_tests.py b/tests/replacebot_tests.py index 219147f..126fe4f 100644 --- a/tests/replacebot_tests.py +++ b/tests/replacebot_tests.py @@ -5,7 +5,7 @@ # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals +from contextlib import suppress
import pywikibot
@@ -49,7 +49,7 @@ # Unpatch already here, as otherwise super calls will use # this class' super which is the class itself replace.ReplaceRobot = self._original_bot - super(FakeReplaceBot, inner_self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.bots.append(inner_self)
def run(inner_self): # noqa: N805 @@ -66,7 +66,7 @@ site.login = patched_login return site
- super(TestReplacementsMain, self).setUp() + super().setUp() self._original_bot = replace.ReplaceRobot self._original_input = replace.pywikibot.input self._original_site = replace.pywikibot.Site @@ -82,7 +82,7 @@ replace.pywikibot.input = self._original_input replace.pywikibot.Site = self._original_site with empty_sites(): - super(TestReplacementsMain, self).tearDown() + super().tearDown()
def _fake_input(self, message): """Cache the message and return static text "TESTRUN".""" @@ -244,7 +244,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/sparql_tests.py b/tests/sparql_tests.py index 05bd439..df65a8c 100644 --- a/tests/sparql_tests.py +++ b/tests/sparql_tests.py @@ -5,6 +5,8 @@ # # Distributed under the terms of the MIT license. # +from contextlib import suppress + import pywikibot.data.sparql as sparql
from tests.aspects import unittest, TestCase, WikidataTestCase @@ -214,7 +216,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/tests_tests.py b/tests/tests_tests.py index 9dfc32d..08f34a4 100755 --- a/tests/tests_tests.py +++ b/tests/tests_tests.py @@ -2,10 +2,10 @@ # -*- coding: utf-8 -*- """Tests for the tests package.""" # -# (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 tests.aspects import unittest, TestCase
@@ -71,7 +71,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/textlib_tests.py b/tests/textlib_tests.py index 9f07b1f..d9940e6 100644 --- a/tests/textlib_tests.py +++ b/tests/textlib_tests.py @@ -6,11 +6,13 @@ # Distributed under the terms of the MIT license. # import codecs -from collections import OrderedDict import functools import os import re
+from collections import OrderedDict +from contextlib import suppress + import pywikibot import pywikibot.textlib as textlib
@@ -42,7 +44,7 @@ def setUp(self): """Setup tests.""" self.catresult1 = '[[Category:Cat1]]\n[[Category:Cat2]]\n' - super(TestSectionFunctions, self).setUp() + super().setUp()
def contains(self, fn, sn): """Invoke does_text_contain_section().""" @@ -769,7 +771,7 @@ @classmethod def setUpClass(cls): """Create a fake interwiki cache.""" - super(TestReplaceLinks, cls).setUpClass() + super().setUpClass() # make APISite.interwiki work and prevent it from doing requests for site in cls.sites.values(): mapping = {} @@ -1488,7 +1490,7 @@ @classmethod def setUpClass(cls): """Cache namespace 10 (Template) case sensitivity.""" - super(TestMultiTemplateMatchBuilder, cls).setUpClass() + super().setUpClass() cls._template_not_case_sensitive = ( cls.get_site().namespaces.TEMPLATE.case != 'case-sensitive')
@@ -1566,7 +1568,7 @@ @classmethod def setUpClass(cls): """Define set of valid targets for the example text.""" - super(TestGetLanguageLinks, cls).setUpClass() + super().setUpClass() cls.sites_set = {cls.enwp, cls.dewp}
def test_getLanguageLinks(self, key): @@ -1682,7 +1684,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/timestamp_tests.py b/tests/timestamp_tests.py index a688b16..d3ce429 100644 --- a/tests/timestamp_tests.py +++ b/tests/timestamp_tests.py @@ -1,16 +1,16 @@ # -*- coding: utf-8 -*- """Tests for the Timestamp class.""" # -# (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 - import calendar import datetime import re
+from contextlib import suppress + from pywikibot import Timestamp
from tests.aspects import unittest, TestCase @@ -145,7 +145,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/timestripper_tests.py b/tests/timestripper_tests.py index 1e62b24..fbe3a59 100644 --- a/tests/timestripper_tests.py +++ b/tests/timestripper_tests.py @@ -1,15 +1,15 @@ # -*- coding: utf-8 -*- """Tests for archivebot.py/Timestripper.""" # -# (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 - import datetime import re
+from contextlib import suppress + from pywikibot.textlib import TimeStripper, tzoneFixedOffset
from tests.aspects import ( @@ -28,7 +28,7 @@
def setUp(self): """Set up test cases.""" - super(TestTimeStripperCase, self).setUp() + super().setUp() self.ts = TimeStripper(self.get_site())
@@ -432,7 +432,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/ui_options_tests.py b/tests/ui_options_tests.py index 62b6bca..2dad2f9 100644 --- a/tests/ui_options_tests.py +++ b/tests/ui_options_tests.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- """Bot tests for input_choice options.""" # -# (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 +from contextlib import suppress
from pywikibot import bot, bot_choice
@@ -124,7 +124,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 9dddcb4..3da675f 100644 --- a/tests/ui_tests.py +++ b/tests/ui_tests.py @@ -33,6 +33,7 @@ import time import warnings
+from contextlib import suppress
import pywikibot from pywikibot.bot import ( @@ -64,7 +65,7 @@ win32clipboard = None
-class Stream(object): +class Stream:
"""Handler for a StringIO or BytesIO instance able to patch itself."""
@@ -95,7 +96,7 @@
if os.name == 'nt':
- class pywikibotWrapper(object): + class pywikibotWrapper:
"""pywikibot wrapper class."""
@@ -198,7 +199,7 @@ net = False
def setUp(self): - super(UITestCase, self).setUp() + super().setUp() patch()
pywikibot.config.colorized_output = True @@ -207,7 +208,7 @@ pywikibot.ui.encoding = 'utf-8'
def tearDown(self): - super(UITestCase, self).tearDown() + super().tearDown() unpatch()
@@ -510,7 +511,7 @@ except AttributeError as e2: raise unittest.SkipTest('pywinauto Application failed: {}\n{}' .format(e1, e2)) - super(WindowsTerminalTestCase, cls).setUpClass() + super().setUpClass()
@classmethod def setUpProcess(cls, command): @@ -543,7 +544,7 @@ cls._process.kill()
def setUp(self): - super(WindowsTerminalTestCase, self).setUp() + super().setUp() self.setclip('')
def waitForWindow(self): @@ -593,7 +594,7 @@
@classmethod def setUpClass(cls): - super(TestWindowsTerminalUnicode, cls).setUpClass() + super().setUpClass() fn = inspect.getfile(inspect.currentframe()) cls.setUpProcess(['python', 'pwb.py', fn, '--run-as-slave-interpreter']) @@ -607,7 +608,7 @@ cls.tearDownProcess()
def setUp(self): - super(TestWindowsTerminalUnicode, self).setUp() + super().setUp()
self.pywikibot.set_config('colorized_output', True) self.pywikibot.set_config('transliterate', False) @@ -644,7 +645,7 @@
@classmethod def setUpClass(cls): - super(TestWindowsTerminalUnicodeArguments, cls).setUpClass() + super().setUpClass() cls.setUpProcess(['cmd', '/k', 'echo off'])
@classmethod @@ -688,7 +689,7 @@
def setUp(self): """Create dummy instances for the test and patch encounter_color.""" - super(FakeUITest, self).setUp() + super().setUp() self.stream = io.StringIO() self.ui_obj = self.ui_class() self._orig_encounter_color = self.ui_obj.encounter_color @@ -698,7 +699,7 @@ def tearDown(self): """Unpatch the encounter_color method.""" self.ui_obj.encounter_color = self._orig_encounter_color - super(FakeUITest, self).tearDown() + super().tearDown() self.assertEqual(self._index, len(self._colors) if self.expect_color else 0)
@@ -758,14 +759,14 @@
def setUp(self): """Force colorized_output to True.""" - super(FakeUIColorizedTestBase, self).setUp() + super().setUp() self._old_config = pywikibot.config2.colorized_output pywikibot.config2.colorized_output = True
def tearDown(self): """Undo colorized_output configuration.""" pywikibot.config2.colorized_output = self._old_config - super(FakeUIColorizedTestBase, self).tearDown() + super().tearDown()
class FakeUnixTest(FakeUIColorizedTestBase, FakeUITest): @@ -804,7 +805,7 @@
def setUp(self): """Patch the ctypes import and initialize a stream and UI instance.""" - super(FakeWin32Test, self).setUp() + super().setUp() self._orig_ctypes = terminal_interface_win32.ctypes ctypes = FakeModule.create_dotted('ctypes.windll.kernel32') ctypes.windll.kernel32.SetConsoleTextAttribute = self._handle_setattr @@ -814,7 +815,7 @@ def tearDown(self): """Unpatch the ctypes import and check that all colors were used.""" terminal_interface_win32.ctypes = self._orig_ctypes - super(FakeWin32Test, self).tearDown() + super().tearDown()
def _encounter_color(self, color, target_stream): """Call the original method.""" @@ -842,14 +843,13 @@
def setUp(self): """Change the local stream's console to None to disable colors.""" - super(FakeWin32UncolorizedTest, self).setUp() + super().setUp() self.stream._hConsole = None
if __name__ == '__main__': # pragma: no cover try: - unittest.main() - except SystemExit: - pass + with suppress(SystemExit): + unittest.main() finally: unpatch() diff --git a/tests/upload_tests.py b/tests/upload_tests.py index 8dd80a1..5cfbfae 100644 --- a/tests/upload_tests.py +++ b/tests/upload_tests.py @@ -5,11 +5,11 @@ These tests write to the wiki. """ # -# (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
import pywikibot
@@ -152,7 +152,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/uploadbot_tests.py b/tests/uploadbot_tests.py index 29f29a3..cf07331 100644 --- a/tests/uploadbot_tests.py +++ b/tests/uploadbot_tests.py @@ -11,6 +11,8 @@ # import os
+from contextlib import suppress + from pywikibot.specialbots import UploadRobot
from tests import join_images_path @@ -83,7 +85,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/uploadscript_tests.py b/tests/uploadscript_tests.py index 0804039..a6ac241 100644 --- a/tests/uploadscript_tests.py +++ b/tests/uploadscript_tests.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- """upload.py script test.""" # -# (C) Pywikibot team, 2019 +# (C) Pywikibot team, 2019-2020 # # Distributed under the terms of the MIT license. # -from __future__ import absolute_import, division, unicode_literals +from contextlib import suppress
from scripts.upload import CHUNK_SIZE_REGEX, get_chunk_size
@@ -44,7 +44,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/wikibase_edit_tests.py b/tests/wikibase_edit_tests.py index 13a5a6b..0766ef8 100644 --- a/tests/wikibase_edit_tests.py +++ b/tests/wikibase_edit_tests.py @@ -6,14 +6,14 @@ class in edit_failiure_tests.py """ # -# (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 - import time
+from contextlib import suppress + import pywikibot
from tests.aspects import unittest, WikibaseTestCase @@ -394,7 +394,7 @@
def setUp(self): """Add a claim with two qualifiers.""" - super(TestWikibaseRemoveQualifier, self).setUp() + super().setUp() testsite = self.get_repo() item = pywikibot.ItemPage(testsite, 'Q68') item.get() @@ -460,7 +460,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass diff --git a/tests/xmlreader_tests.py b/tests/xmlreader_tests.py index 227d5cd..4f41bb0 100644 --- a/tests/xmlreader_tests.py +++ b/tests/xmlreader_tests.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- """Tests for xmlreader 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 +from contextlib import suppress
from pywikibot import xmlreader
@@ -126,7 +126,5 @@
if __name__ == '__main__': # pragma: no cover - try: + with suppress(SystemExit): unittest.main() - except SystemExit: - pass
pywikibot-commits@lists.wikimedia.org