XZise has submitted this change and it was merged.
Change subject: Remove globals from test cases ......................................................................
Remove globals from test cases
Add TestCase methods get_mainpage and get_missing_article, with caching in get_mainpage, to replace global variables in the test modules.
Also move the 'Site.movepage' test to edit_failure_tests, as it is a 'write' API call, and it may unexpectedly do a write if there is a bug in the codebase. After this move, if it ever does act unexpectedly, it does it on a test wiki.
Change-Id: I94ae444d440f366b353231eecd37ebe1f5411605 --- M tests/aspects.py M tests/edit_failure_tests.py M tests/page_tests.py M tests/site_tests.py M tests/wikibase_tests.py 5 files changed, 143 insertions(+), 55 deletions(-)
Approvals: XZise: Looks good to me, approved
diff --git a/tests/aspects.py b/tests/aspects.py index ccbb273..21a76d6 100644 --- a/tests/aspects.py +++ b/tests/aspects.py @@ -426,6 +426,35 @@ # Create an instance method named the same as the class method self.get_site = lambda name=None: self.__class__.get_site(name)
+ def get_mainpage(self, site=None): + """Create a Page object for the sites main page.""" + if not site: + site = self.get_site() + + if hasattr(self, '_mainpage'): + # For multi-site test classes, or site is specified as a param, + # the cached mainpage object may not be the desired site. + if self._mainpage.site == site: + return self._mainpage + + mainpage = pywikibot.Page(site, site.siteinfo['mainpage']) + if mainpage.isRedirectPage(): + mainpage = mainpage.getRedirectTarget() + + self._mainpage = mainpage + + return mainpage + + def get_missing_article(self, site=None): + if not site: + site = self.get_site() + page = pywikibot.Page(pywikibot.page.Link( + "There is no page with this title", site)) + if page.exists(): + raise unittest.SkipTest("Did not find a page that does not exist.") + + return page +
if sys.version_info[0] > 2: import six diff --git a/tests/edit_failure_tests.py b/tests/edit_failure_tests.py index 0dcfc60..f1d2c91 100644 --- a/tests/edit_failure_tests.py +++ b/tests/edit_failure_tests.py @@ -14,6 +14,8 @@
import pywikibot from pywikibot import ( + Error, + NoPage, LockedPage, SpamfilterError, OtherPageSaveError, @@ -49,6 +51,35 @@ self.assertRaisesRegexp(OtherPageSaveError, 'nobots', page.save)
+class TestActionFailure(SiteTestCase): + + """Test cases for actions which should fail to save.""" + + write = True + + family = 'wikipedia' + code = 'test' + + def test_movepage(self): + """Test that site.movepage raises the appropriate exceptions.""" + mysite = self.get_site() + mainpage = self.get_mainpage() + try: + mysite.tokens['move'] + except KeyError: + raise unittest.SkipTest( + "movepage test requires 'move' token not given to user on %s" + % self.site) + + self.assertRaises(Error, mysite.movepage, + mainpage, mainpage.title(), 'test') + + page_from = self.get_missing_article() + if not page_from.exists(): + self.assertRaises(NoPage, mysite.movepage, + page_from, 'Main Page', 'test') + + if __name__ == '__main__': try: unittest.main() diff --git a/tests/page_tests.py b/tests/page_tests.py index 9921407..d32acdd 100644 --- a/tests/page_tests.py +++ b/tests/page_tests.py @@ -17,10 +17,6 @@ basestring = (str, ) unicode = str
-# These two globals are only used in TestPageObject. -site = None -mainpage = None -
class TestLinkObject(TestCase):
@@ -167,37 +163,37 @@
cached = True
- @classmethod - def setUpClass(cls): - global site, mainpage - super(TestPageObject, cls).setUpClass() - site = cls.get_site() - mainpage = pywikibot.Page(pywikibot.page.Link("Main Page", site)) - cls.maintalk = pywikibot.Page(pywikibot.page.Link("Talk:Main Page", site)) - cls.badpage = pywikibot.Page(pywikibot.page.Link( - "There is no page with this title", site)) - def testGeneral(self): + site = self.get_site() + mainpage = self.get_mainpage() + maintalk = mainpage.toggleTalkPage() + family_name = (site.family.name + ':' if pywikibot.config2.family != site.family.name else u'') self.assertEqual(str(mainpage), "[[%s%s:%s]]" % (family_name, site.code, mainpage.title())) - self.assertLess(mainpage, self.maintalk) + self.assertLess(mainpage, maintalk)
def testSite(self): """Test site() method""" - self.assertEqual(mainpage.site, site) + mainpage = self.get_mainpage() + self.assertEqual(mainpage.site, self.site)
def testNamespace(self): """Test namespace() method""" + mainpage = self.get_mainpage() + maintalk = mainpage.toggleTalkPage() + badpage = self.get_missing_article() + self.assertEqual(mainpage.namespace(), 0) - self.assertEqual(self.maintalk.namespace(), 1) - self.assertEqual(self.badpage.namespace(), 0) + self.assertEqual(maintalk.namespace(), 1) + self.assertEqual(badpage.namespace(), 0)
def testTitle(self): """Test title() method options.""" + site = self.get_site() p1 = pywikibot.Page(site, u"Help:Test page#Testing") self.assertEqual(p1.title(), u"Help:Test page#Testing") @@ -297,6 +293,7 @@ def testSection(self): """Test section() method.""" # use same pages as in previous test + site = self.get_site() p1 = pywikibot.Page(site, u"Help:Test page#Testing") p2 = pywikibot.Page(site, u"File:Jean-Léon Gérôme 003.jpg") self.assertEqual(p1.section(), u"Testing") @@ -304,6 +301,7 @@
def testIsTalkPage(self): """Test isTalkPage() method.""" + site = self.get_site() p1 = pywikibot.Page(site, u"First page") p2 = pywikibot.Page(site, u"Talk:First page") p3 = pywikibot.Page(site, u"User:Second page") @@ -315,6 +313,7 @@
def testIsCategory(self): """Test isCategory method.""" + site = self.get_site() p1 = pywikibot.Page(site, u"First page") p2 = pywikibot.Page(site, u"Category:Second page") p3 = pywikibot.Page(site, u"Category talk:Second page") @@ -323,6 +322,7 @@ self.assertEqual(p3.isCategory(), False)
def testIsImage(self): + site = self.get_site() p1 = pywikibot.Page(site, u"First page") p2 = pywikibot.Page(site, u"File:Second page") p3 = pywikibot.Page(site, u"Image talk:Second page") @@ -331,12 +331,14 @@ self.assertEqual(p3.isImage(), False)
def testIsRedirect(self): + site = self.get_site() p1 = pywikibot.Page(site, u'User:Legoktm/R1') p2 = pywikibot.Page(site, u'User:Legoktm/R2') self.assertTrue(p1.isRedirectPage()) self.assertEqual(p1.getRedirectTarget(), p2)
def testPageGet(self): + site = self.get_site() p1 = pywikibot.Page(site, u'User:Legoktm/R2') p2 = pywikibot.Page(site, u'User:Legoktm/R1') p3 = pywikibot.Page(site, u'User:Legoktm/R3') @@ -348,18 +350,21 @@
def testApiMethods(self): """Test various methods that rely on API.""" + mainpage = self.get_mainpage() + maintalk = mainpage.toggleTalkPage() + badpage = self.get_missing_article() # 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(self.maintalk.get(), unicode) - self.assertRaises(pywikibot.NoPage, self.badpage.get) + self.assertIsInstance(maintalk.get(), unicode) + self.assertRaises(pywikibot.NoPage, badpage.get) self.assertIsInstance(mainpage.latestRevision(), int) self.assertIsInstance(mainpage.userName(), unicode) self.assertIsInstance(mainpage.isIpEdit(), bool) self.assertIsInstance(mainpage.exists(), bool) self.assertIsInstance(mainpage.isRedirectPage(), bool) self.assertIsInstance(mainpage.isEmpty(), bool) - self.assertEqual(mainpage.toggleTalkPage(), self.maintalk) - self.assertEqual(self.maintalk.toggleTalkPage(), mainpage) + self.assertEqual(mainpage.toggleTalkPage(), maintalk) + self.assertEqual(maintalk.toggleTalkPage(), mainpage) self.assertIsInstance(mainpage.isDisambig(), bool) self.assertIsInstance(mainpage.canBeEdited(), bool) self.assertIsInstance(mainpage.botMayEdit(), bool) @@ -370,9 +375,9 @@
def testIsDisambig(self): """ - Test the integration with - Extension:Disambiguator + Test the integration with Extension:Disambiguator. """ + site = self.get_site() if not site.has_extension('Disambiguator'): raise unittest.SkipTest('Disambiguator extension not loaded on test site') pg = pywikibot.Page(site, 'Random') @@ -382,6 +387,7 @@ self.assertFalse(pg.isDisambig())
def testReferences(self): + mainpage = self.get_mainpage() count = 0 # Ignore redirects for time considerations for p in mainpage.getReferences(follow_redirects=False): @@ -403,6 +409,7 @@ break
def testLinks(self): + mainpage = self.get_mainpage() for p in mainpage.linkedPages(): self.assertIsInstance(p, pywikibot.Page) iw = list(mainpage.interwiki(expand=True)) @@ -426,18 +433,18 @@ self.assertIsInstance(p, unicode)
def testPickleAbility(self): + mainpage = self.get_mainpage() import pickle pickle.dumps(mainpage) self.assertTrue(True) # No exception thrown!
def testRepr(self): + mainpage = self.get_mainpage() s = repr(mainpage) self.assertIsInstance(s, str)
def testReprUnicode(self): - site = pywikibot.Site('ar', 'wikipedia') - page = pywikibot.Page(site, 'Main Page') - page = page.toggleTalkPage() + page = pywikibot.Page(self.get_site(), u'Ō') s = repr(page) self.assertIsInstance(s, str)
@@ -465,19 +472,21 @@
class TestCategoryObject(TestCase):
- site = True + family = 'wikipedia' + code = 'en' + cached = True
def test_isEmptyCategory(self): """Test if category is empty or not""" - site = pywikibot.Site('en', 'wikipedia') + site = self.get_site() cat_empty = pywikibot.Category(site, u'Category:foooooo') cat_not_empty = pywikibot.Category(site, u'Category:Wikipedia categories') self.assertTrue(cat_empty.isEmptyCategory()) self.assertFalse(cat_not_empty.isEmptyCategory())
def test_isHiddenCategory(self): - site = pywikibot.Site('en', 'wikipedia') + site = self.get_site() cat_hidden = pywikibot.Category(site, u'Category:Hidden categories') cat_not_hidden = pywikibot.Category(site, u'Category:Wikipedia categories') self.assertTrue(cat_hidden.isHiddenCategory()) diff --git a/tests/site_tests.py b/tests/site_tests.py index 28948df..5bbdc0e 100644 --- a/tests/site_tests.py +++ b/tests/site_tests.py @@ -15,16 +15,11 @@ import re
import pywikibot -from pywikibot.exceptions import Error, NoPage from tests.aspects import unittest, TestCase
if sys.version_info[0] > 2: basestring = (str, ) unicode = str - -mysite = None -mainpage = None -imagepage = None
class TestSiteObject(TestCase): @@ -36,16 +31,9 @@
cached = True
- @classmethod - def setUpClass(cls): - global mysite, mainpage, imagepage - super(TestSiteObject, cls).setUpClass() - mysite = cls.get_site() - mainpage = pywikibot.Page(pywikibot.Link("Main Page", mysite)) - imagepage = next(iter(mainpage.imagelinks())) # 1st image on main page - def testBaseMethods(self): """Test cases for BaseSite methods.""" + mysite = self.get_site() self.assertEqual(mysite.family.name, self.family) self.assertEqual(mysite.code, self.code) self.assertIsInstance(mysite.lang, basestring) @@ -82,6 +70,7 @@
def testLanguageMethods(self): """Test cases for languages() and related methods""" + mysite = self.get_site() langs = mysite.languages() self.assertIsInstance(langs, list) self.assertIn(mysite.code, langs) @@ -95,6 +84,7 @@
def testNamespaceMethods(self): """Test cases for methods manipulating namespace names.""" + mysite = self.get_site() builtins = { '': 0, # these should work in any MW wiki 'Talk': 1, @@ -161,6 +151,7 @@
def testApiMethods(self): """Test generic ApiSite methods.""" + mysite = self.get_site() self.assertIsInstance(mysite.logged_in(), bool) self.assertIsInstance(mysite.logged_in(True), bool) self.assertIsInstance(mysite.userinfo, dict) @@ -214,6 +205,8 @@
def testPageMethods(self): """Test ApiSite methods for getting page-specific info.""" + mysite = self.get_site() + mainpage = self.get_mainpage() self.assertIsInstance(mysite.page_exists(mainpage), bool) self.assertIsInstance(mysite.page_restrictions(mainpage), dict) self.assertIsInstance(mysite.page_can_be_edited(mainpage), bool) @@ -230,14 +223,21 @@
def testTokens(self): """Test ability to get page tokens.""" + mysite = self.get_site() for ttype in ("edit", "move"): # token types for non-sysops - token = mysite.token(mainpage, ttype) + token = mysite.tokens[ttype] self.assertIsInstance(token, basestring) self.assertEqual(token, mysite.tokens[ttype]) + + def testInvalidToken(self): + mysite = self.get_site() + mainpage = self.get_mainpage() self.assertRaises(KeyError, mysite.token, mainpage, "invalidtype")
def testPreload(self): """Test that preloading works.""" + mysite = self.get_site() + mainpage = self.get_mainpage() count = 0 for page in mysite.preloadpages(mysite.pagelinks(mainpage, total=10)): self.assertIsInstance(page, pywikibot.Page) @@ -250,6 +250,7 @@
def testItemPreload(self): """Test that ItemPage preloading works.""" + mysite = self.get_site() datasite = mysite.data_repository()
items = [pywikibot.ItemPage(datasite, 'q' + str(num)) for num in range(1, 6)] @@ -258,6 +259,8 @@
def testLinkMethods(self): """Test site methods for getting links to and from a page.""" + mysite = self.get_site() + mainpage = self.get_mainpage() backlinks = set(mysite.pagebacklinks(mainpage, namespaces=[0])) # only non-redirects: filtered = set(mysite.pagebacklinks(mainpage, namespaces=0, @@ -332,6 +335,7 @@
def testAllPages(self): """Test the site.allpages() method""" + mysite = self.get_site() fwd = list(mysite.allpages(total=10)) self.assertLessEqual(len(fwd), 10) for page in fwd: @@ -398,6 +402,7 @@
def testAllLinks(self): """Test the site.alllinks() method""" + mysite = self.get_site() fwd = list(mysite.alllinks(total=10)) self.assertLessEqual(len(fwd), 10) self.assertTrue(all(isinstance(link, pywikibot.Page) for link in fwd)) @@ -424,6 +429,7 @@
def testAllCategories(self): """Test the site.allcategories() method""" + mysite = self.get_site() ac = list(mysite.allcategories(total=10)) self.assertLessEqual(len(ac), 10) self.assertTrue(all(isinstance(cat, pywikibot.Category) @@ -441,6 +447,7 @@
def testAllUsers(self): """Test the site.allusers() method""" + mysite = self.get_site() au = list(mysite.allusers(total=10)) self.assertLessEqual(len(au), 10) for user in au: @@ -470,6 +477,7 @@
def testAllImages(self): """Test the site.allimages() method""" + mysite = self.get_site() ai = list(mysite.allimages(total=10)) self.assertLessEqual(len(ai), 10) self.assertTrue(all(isinstance(image, pywikibot.FilePage) @@ -498,6 +506,7 @@
def testBlocks(self): """Test the site.blocks() method""" + mysite = self.get_site() props = ("id", "by", "timestamp", "expiry", "reason") bl = list(mysite.blocks(total=10)) self.assertLessEqual(len(bl), 10) @@ -555,6 +564,7 @@
def testExturlusage(self): """Test the site.exturlusage() method""" + mysite = self.get_site() url = "www.google.com" eu = list(mysite.exturlusage(url, total=10)) self.assertLessEqual(len(eu), 10) @@ -566,6 +576,10 @@
def testImageusage(self): """Test the site.imageusage() method""" + mysite = self.get_site() + mainpage = self.get_mainpage() + imagepage = next(iter(mainpage.imagelinks())) # 1st image on main page + iu = list(mysite.imageusage(imagepage, total=10)) self.assertLessEqual(len(iu), 10) self.assertTrue(all(isinstance(link, pywikibot.Page) @@ -582,6 +596,8 @@
def testLogEvents(self): """Test the site.logevents() method""" + mysite = self.get_site() + mainpage = self.get_mainpage() le = list(mysite.logevents(total=10)) self.assertLessEqual(len(le), 10) self.assertTrue(all(isinstance(entry, pywikibot.logentries.LogEntry) @@ -623,6 +639,9 @@
def testRecentchanges(self): """Test the site.recentchanges() method""" + mysite = self.get_site() + mainpage = self.get_mainpage() + imagepage = next(iter(mainpage.imagelinks())) rc = list(mysite.recentchanges(total=10)) self.assertLessEqual(len(rc), 10) self.assertTrue(all(isinstance(change, dict) @@ -716,6 +735,7 @@
def testSearch(self): """Test the site.search() method""" + mysite = self.get_site() try: se = list(mysite.search("wiki", total=10)) self.assertLessEqual(len(se), 10) @@ -742,6 +762,7 @@
def testUsercontribs(self): """Test the site.usercontribs() method""" + mysite = self.get_site() uc = list(mysite.usercontribs(user=mysite.user(), total=10)) self.assertLessEqual(len(uc), 10) self.assertTrue(all(isinstance(contrib, dict) @@ -814,6 +835,7 @@
def testWatchlistrevs(self): """Test the site.watchlist_revs() method""" + mysite = self.get_site() wl = list(mysite.watchlist_revs(total=10)) self.assertLessEqual(len(wl), 10) self.assertTrue(all(isinstance(rev, dict) @@ -881,6 +903,8 @@
def testDeletedrevs(self): """Test the site.deletedrevs() method""" + mysite = self.get_site() + mainpage = self.get_mainpage() if not mysite.logged_in(True): try: mysite.login(True) @@ -939,6 +963,7 @@
def testUsers(self): """Test the site.users() method""" + mysite = self.get_site() us = list(mysite.users(mysite.user())) self.assertEqual(len(us), 1) self.assertIsInstance(us[0], dict) @@ -950,6 +975,7 @@
def testRandompages(self): """Test the site.randompages() method""" + mysite = self.get_site() rn = list(mysite.randompages(total=10)) self.assertLessEqual(len(rn), 10) self.assertTrue(all(isinstance(a_page, pywikibot.Page) @@ -966,6 +992,7 @@ # and the other following methods in site.py
def testExtensions(self): + mysite = self.get_site() # test automatically getting extensions cache if 'extensions' in mysite.siteinfo: del mysite.siteinfo._cache['extensions'] @@ -978,6 +1005,7 @@
def test_API_limits_with_site_methods(self): # test step/total parameters for different sitemethods + mysite = self.get_site() mypage = pywikibot.Page(mysite, 'Albert Einstein') mycat = pywikibot.Page(mysite, 'Category:1879 births')
@@ -997,14 +1025,14 @@ self.assertEqual(len(mypage._revisions), 12)
def testPickleAbility(self): + site = self.get_site() import pickle - site = pywikibot.Site('en', 'wikipedia') pickle.dumps(site) - self.assertTrue(True) # No exception thrown!
def testSiteinfo(self): """Test the siteinfo property.""" # general enteries + mysite = self.get_site() self.assertIsInstance(mysite.siteinfo['timeoffset'], (int, float)) self.assertTrue(-12 * 60 <= mysite.siteinfo['timeoffset'] <= +14 * 60) self.assertEqual(mysite.siteinfo['timeoffset'] % 15, 0) @@ -1043,14 +1071,6 @@ self.assertFalse(entered_loop(mysite.siteinfo.get(not_exists).items())) self.assertFalse(entered_loop(mysite.siteinfo.get(not_exists).values())) self.assertFalse(entered_loop(mysite.siteinfo.get(not_exists).keys())) - - def test_movepage(self): - self.assertRaises(Error, mysite.movepage, mainpage, 'Main Page', 'test') - - page_from = pywikibot.Page(mysite, 'Not exiting page') - if not page_from.exists(): - self.assertRaises(NoPage, mysite.movepage, - page_from, 'Main Page', 'test')
class TestSiteLoadRevisions(TestCase): diff --git a/tests/wikibase_tests.py b/tests/wikibase_tests.py index bee7313..d35318c 100644 --- a/tests/wikibase_tests.py +++ b/tests/wikibase_tests.py @@ -144,7 +144,6 @@
@classmethod def setUpClass(cls): - global wikidata super(TestItemLoad, cls).setUpClass() cls.site = cls.get_site('enwiki') cls.nyc = pywikibot.Page(pywikibot.page.Link("New York City", cls.site))
pywikibot-commits@lists.wikimedia.org