jenkins-bot has submitted this change and it was merged.
Change subject: Improve comment in page_tests.testBasePageConstructor
......................................................................
Improve comment in page_tests.testBasePageConstructor
Comment in page_tests.testBasePageConstructor was misleading, now fixed.
Change-Id: Iaa3254f56c35dc8e10a4051f374c55e7c0f2a1d4
---
M tests/page_tests.py
1 file changed, 2 insertions(+), 2 deletions(-)
Approvals:
Nullzero: Looks good to me, approved
jenkins-bot: Verified
diff --git a/tests/page_tests.py b/tests/page_tests.py
index 98616e5..460f1e8 100644
--- a/tests/page_tests.py
+++ b/tests/page_tests.py
@@ -281,8 +281,8 @@
site = self.get_site()
# Should not raise an error as the constructor only requires
- # the site parameter, with the title parameter defaulted to
- # empty string
+ # the site parameter.
+ # Empty string or None as title raises error.
page = pywikibot.page.BasePage(site)
self.assertRaises(InvalidTitle, page.title)
page = pywikibot.page.BasePage(site, title=u'')
--
To view, visit https://gerrit.wikimedia.org/r/169220
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Iaa3254f56c35dc8e10a4051f374c55e7c0f2a1d4
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Nullzero <nullzero.free(a)gmail.com>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Bug 64188 - getVersionHistory does not follow total parameter
......................................................................
Bug 64188 - getVersionHistory does not follow total parameter
When a version history is already loaded, decreasing the total
parameter getVersionHistory() now returns the decreased amount
of values.
Fixed also for getVersionHistoryTable() and fullVersionHistory()
methods.
Created namedtuple classes:
- HistEntry
- FullHistEntry
to improve handling of data returned by getVersionHistory().
Adapted scripts to make use of new classes.
Fixed also a bug in page.previousRevision(), when page is new page.
Bug: 64188
Change-Id: I9aa1372e7e6366e3dee454d069b742abbc372b64
---
M pywikibot/page.py
M scripts/checkimages.py
M scripts/newitem.py
3 files changed, 82 insertions(+), 75 deletions(-)
Approvals:
XZise: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 2c3db36..08a27ba 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -518,11 +518,9 @@
return self._lastNonBotUser
self._lastNonBotUser = None
- for vh in self.getVersionHistory():
- (revid, timestmp, username, comment) = vh[:4]
-
- if username and (not self.site.isBot(username)):
- self._lastNonBotUser = username
+ for entry in self.getVersionHistory():
+ if entry.user and (not self.site.isBot(entry.user)):
+ self._lastNonBotUser = entry.user
break
return self._lastNonBotUser
@@ -540,11 +538,16 @@
def previousRevision(self):
"""Return the revision id for the previous revision of this Page.
+ If the page has only one revision, it shall return -1.
+
@return: long
"""
- self.getVersionHistory(total=2)
- revkey = sorted(self._revisions, reverse=True)[1]
- return revkey
+ history = self.getVersionHistory(total=2)
+
+ if len(history) == 1:
+ return -1
+ else:
+ return min(x.revid for x in history)
def exists(self):
"""Return True if page exists on the wiki, even if it's a redirect.
@@ -1360,8 +1363,7 @@
# returned no more than 500 revisions; now, it iterates
# all revisions unless 'total' argument is used
@deprecated_args(forceReload=None, revCount="total", getAll=None)
- def getVersionHistory(self, reverseOrder=False, step=None,
- total=None):
+ def getVersionHistory(self, reverseOrder=False, step=None, total=None):
"""Load the version history page and return history information.
Return value is a list of tuples, where each tuple represents one
@@ -1375,25 +1377,21 @@
"""
self.site.loadrevisions(self, getText=False, rvdir=reverseOrder,
step=step, total=total)
- return [(self._revisions[rev].revid,
- self._revisions[rev].timestamp,
- self._revisions[rev].user,
- self._revisions[rev].comment
- ) for rev in sorted(self._revisions,
- reverse=not reverseOrder)
- ]
+
+ return [rev.hist_entry()
+ for revid, rev in sorted(self._revisions.items(),
+ reverse=not reverseOrder)
+ ][:total]
@deprecated_args(forceReload=None)
def getVersionHistoryTable(self, reverseOrder=False, step=None, total=None):
"""Return the version history as a wiki table."""
result = '{| class="wikitable"\n'
result += '! oldid || date/time || username || edit summary\n'
- for oldid, time, username, summary \
- in self.getVersionHistory(reverseOrder=reverseOrder,
- step=step, total=total):
+ for entry in self.getVersionHistory(reverseOrder=reverseOrder,
+ step=step, total=total):
result += '|----\n'
- result += '| %s || %s || %s || <nowiki>%s</nowiki>\n'\
- % (oldid, time, username, summary)
+ result += '| %s || %s || %s || <nowiki>%s</nowiki>\n' % entry
result += '|}\n'
return result
@@ -1408,17 +1406,13 @@
edit date/time, user name and content
"""
- self.site.loadrevisions(self, getText=True,
- rvdir=reverseOrder,
+ self.site.loadrevisions(self, getText=True, rvdir=reverseOrder,
step=step, total=total, rollback=rollback)
- return [(self._revisions[rev].revid,
- self._revisions[rev].timestamp,
- self._revisions[rev].user,
- self._revisions[rev].text,
- self._revisions[rev].rollbacktoken
- ) for rev in sorted(self._revisions,
- reverse=not reverseOrder)
- ]
+
+ return [rev.hist_entry()
+ for revid, rev in sorted(self._revisions.items(),
+ reverse=not reverseOrder)
+ ][:total]
def contributingUsers(self, step=None, total=None):
"""Return a set of usernames (or IPs) of users who edited this page.
@@ -1427,8 +1421,8 @@
@param total: iterate no more than this number of revisions in total
"""
- edits = self.getVersionHistory(step=step, total=total)
- users = set([edit[2] for edit in edits])
+ history = self.getVersionHistory(step=step, total=total)
+ users = set(entry.user for entry in history)
return users
@deprecate_arg("throttle", None)
@@ -3846,6 +3840,19 @@
"""A structure holding information about a single revision of a Page."""
+ HistEntry = collections.namedtuple('HistEntry',
+ ['revid',
+ 'timestamp',
+ 'user',
+ 'comment'])
+
+ FullHistEntry = collections.namedtuple('FullHistEntry',
+ ['revid',
+ 'timestamp',
+ 'user',
+ 'text',
+ 'rollbacktoken'])
+
def __init__(self, revid, timestamp, user, anon=False, comment=u"",
text=None, minor=False, rollbacktoken=None):
"""
@@ -3879,6 +3886,16 @@
self.minor = minor
self.rollbacktoken = rollbacktoken
+ def hist_entry(self):
+ """Return a namedtuple with a Page history record."""
+ return Revision.HistEntry(self.revid, self.timestamp, self.user,
+ self.comment)
+
+ def full_hist_entry(self):
+ """Return a namedtuple with a Page full history record."""
+ return Revision.FullHistEntry(self.revid, self.timestamp, self.user,
+ self.text, self.rollbacktoken)
+
class Link(ComparableMixin):
diff --git a/scripts/checkimages.py b/scripts/checkimages.py
index ff56c81..8179fff 100644
--- a/scripts/checkimages.py
+++ b/scripts/checkimages.py
@@ -1,9 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-Script to check recently uploaded files. This script checks if a file
-description is present and if there are other problems in the image's
-description.
+Script to check recently uploaded files.
+
+This script checks if a file description is present and if there are other
+problems in the image's description.
This script will have to be configured for each language. Please submit
translations as addition to the Pywikibot framework.
@@ -565,24 +566,16 @@
class LogIsFull(pywikibot.Error):
- """An exception indicating that the log is full and the Bot cannot add
- other data to prevent Errors.
-
- """
+ """Log is full and the Bot cannot add other data to prevent Errors."""
class NothingFound(pywikibot.Error):
- """ An exception indicating that a regex has return [] instead of results.
-
- """
+ """Regex returned [] instead of results."""
def printWithTimeZone(message):
- """ Function to print the messages followed by the TimeZone encoded
- correctly.
-
- """
+ """Print the messages followed by the TimeZone encoded correctly."""
if message[-1] != ' ':
message = '%s ' % unicode(message)
if locale.getlocale()[1]:
@@ -596,6 +589,8 @@
class checkImagesBot(object):
+
+ """A robot to check recently uploaded files."""
def __init__(self, site, logFulNumber=25000, sendemailActive=False,
duplicatesReport=False, logFullError=True):
@@ -639,9 +634,10 @@
self.list_licenses = self.load_licenses()
def setParameters(self, imageName):
- """ Function to set parameters, now only image but maybe it can be used
- for others in "future"
+ """
+ Set parameters.
+ Now only image but maybe it can be used for others in "future".
"""
self.imageName = imageName
self.image = pywikibot.FilePage(self.site, self.imageName)
@@ -707,10 +703,7 @@
return upBotArray[0]
def tag_image(self, put=True):
- """ Function to add the template in the image and to find out
- who's the user that has uploaded the file.
-
- """
+ """Add template to the Image page and find out the uploader."""
# Get the image's description
reportPageObject = pywikibot.FilePage(self.site, self.image_to_report)
@@ -829,9 +822,10 @@
return
def untaggedGenerator(self, untaggedProject, limit):
- """ Generator that yield the files without license. It's based on a
- tool of the toolserver.
+ """
+ Generator that yield the files without license.
+ It's based on a tool of the toolserver.
"""
lang = untaggedProject.split('.', 1)[0]
project = '.%s' % untaggedProject.split('.', 1)[1]
@@ -863,10 +857,7 @@
u'that it works!')
def regexGenerator(self, regexp, textrun):
- """ Generator used when an user use a regex parsing a page to yield the
- results
-
- """
+ """Find page to yield using regex to parse text."""
regex = re.compile(r'%s' % regexp, re.UNICODE | re.DOTALL)
results = regex.findall(textrun)
for image in results:
@@ -935,7 +926,7 @@
user_list = list()
for data in history:
- user_list.append(data[2])
+ user_list.append(data.user)
number_edits = 0
for username in userlist:
@@ -1319,11 +1310,7 @@
return list_licenses
def miniTemplateCheck(self, template):
- """
- Check whether the given template given in the licenses allowed or in the
- licenses to skip.
-
- """
+ """Check if template is in allowed licenses or in licenses to skip."""
# the list_licenses are loaded in the __init__
# (not to load them multimple times)
if template in self.list_licenses:
@@ -1345,11 +1332,12 @@
def templateInList(self):
"""
+ Check if template is in list.
+
The problem is the calls to the Mediawiki system because they can be
pretty slow. While searching in a list of objects is really fast, so
first of all let's see if we can find something in the info that we
already have, then make a deeper check.
-
"""
for template in self.licenses_found:
result = self.miniTemplateCheck(template)
@@ -1368,10 +1356,12 @@
continue
def smartDetection(self):
- """The bot instead of checking if there's a simple template in the
+ """
+ Detect templates.
+
+ The bot instead of checking if there's a simple template in the
image's description, checks also if that template is a license or
something else. In this sense this type of check is smart.
-
"""
self.seems_ok = False
self.license_found = None
@@ -1522,9 +1512,10 @@
pywikibot.output('')
def wait(self, waitTime, generator, normal, limit):
- """ Skip the images uploaded before x seconds to let
- the users to fix the image's problem alone in the
- first x seconds.
+ """
+ Skip the images uploaded before x seconds.
+
+ Let the users to fix the image's problem alone in the first x seconds.
"""
imagesToSkip = 0
# if normal, we can take as many images as "limit" has told us,
diff --git a/scripts/newitem.py b/scripts/newitem.py
index f320e0e..acba3da 100644
--- a/scripts/newitem.py
+++ b/scripts/newitem.py
@@ -78,9 +78,8 @@
% (page, page.editTime().isoformat()))
return
- (revId, revTimestamp, revUser,
- revComment) = page.getVersionHistory(reverseOrder=True, total=1)[0]
- if revTimestamp > self.pageAgeBefore:
+ rev = page.getVersionHistory(reverseOrder=True, total=1)[0]
+ if rev.timestamp > self.pageAgeBefore:
pywikibot.output(
u'Page creation of %s on %s is too recent. Skipping.'
% (page, page.editTime().isoformat()))
--
To view, visit https://gerrit.wikimedia.org/r/168503
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I9aa1372e7e6366e3dee454d069b742abbc372b64
Gerrit-PatchSet: 5
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Sysop and user tests
......................................................................
Sysop and user tests
Some tests require a user or sysop, but are not yet flagged
as user=True.
This changeset also adds a sysop flag, to identify tests which
require a sysop account, skipping the test if this condition is
not met.
All tests except pwb.py-based tests can now be run without
user-config.py, with tests skipping if they require a username.
Change-Id: I690423556f1266f3ebe0bee11aa91b41b9965baf
---
M tests/aspects.py
M tests/page_tests.py
M tests/script_tests.py
M tests/site_tests.py
4 files changed, 100 insertions(+), 53 deletions(-)
Approvals:
John Vandenberg: Looks good to me, but someone else must approve
XZise: Looks good to me, approved
jenkins-bot: Verified
diff --git a/tests/aspects.py b/tests/aspects.py
index 0f3b9f1..3089fc3 100644
--- a/tests/aspects.py
+++ b/tests/aspects.py
@@ -204,12 +204,14 @@
user = True
@classmethod
- def require_site_user(cls):
+ def require_site_user(cls, family, code, sysop=False):
"""Check the user config has a valid login to the site."""
- if not cls.has_site_user(cls.family, cls.code):
+ if not cls.has_site_user(family, code, sysop=sysop):
raise unittest.SkipTest(
- '%s: No username for %s:%s'
- % (cls.__name__, cls.family, cls.code))
+ '%s: No %susername for %s:%s'
+ % (cls.__name__,
+ "sysop " if sysop else "",
+ family, code))
@classmethod
def setUpClass(cls):
@@ -221,14 +223,19 @@
"""
super(RequireUserMixin, cls).setUpClass()
- cls.require_site_user()
+ sysop = hasattr(cls, 'sysop') and cls.sysop
- cls.site.login()
+ for site in cls.sites.values():
+ cls.require_site_user(site['family'], site['code'], sysop)
- if not cls.site.user():
- raise unittest.SkipTest(
- '%s: Unable able to login to %s'
- % cls.__name__, cls.site)
+ site['site'].login(sysop)
+
+ if not site['site'].user():
+ raise unittest.SkipTest(
+ '%s: Unable able to login to %s as %s'
+ % (cls.__name__,
+ 'sysop' if sysop else 'bot',
+ site['site']))
def setUp(self):
"""
@@ -237,9 +244,17 @@
Login to the site if it is not logged in.
"""
super(RequireUserMixin, self).setUp()
- site = self.get_site()
- if not site.logged_in():
- site.login()
+
+ sysop = hasattr(self, 'sysop') and self.sysop
+
+ # There may be many sites, and setUp doesnt know
+ # which site is to be tested; ensure they are all
+ # logged in.
+ for site in self.sites.values():
+ site = site['site']
+
+ if not site.logged_in(sysop):
+ site.login(sysop)
class MetaTestCaseClass(type):
@@ -351,7 +366,7 @@
if 'write' in dct and dct['write']:
bases = tuple([SiteWriteMixin] + list(bases))
- if 'user' in dct and dct['user']:
+ if ('user' in dct and dct['user']) or ('sysop' in dct and dct['sysop']):
bases = tuple([RequireUserMixin] + list(bases))
for test in tests:
@@ -449,15 +464,17 @@
return cls.sites[name]['site']
@classmethod
- def has_site_user(cls, family, code):
+ def has_site_user(cls, family, code, sysop=False):
"""Check the user config has a user for the site."""
if not family:
raise Exception('no family defined for %s' % cls.__name__)
if not code:
raise Exception('no site code defined for %s' % cls.__name__)
- return code in config.usernames[family] or \
- '*' in config.usernames[family]
+ usernames = config.sysopnames if sysop else config.usernames
+
+ return code in usernames[family] or \
+ '*' in usernames[family]
def __init__(self, *args, **kwargs):
"""Constructor."""
@@ -666,6 +683,11 @@
pwb = True
spawn = True
+ # pywikibot.handleArgs currently instantiates a Site object
+ # and tries to fetch the users messages.
+ site = True
+ net = True
+ user = True
class DeprecationTestCase(TestCase):
diff --git a/tests/page_tests.py b/tests/page_tests.py
index 3169d1e..98616e5 100644
--- a/tests/page_tests.py
+++ b/tests/page_tests.py
@@ -409,7 +409,6 @@
self.assertIsInstance(mainpage.editTime(), pywikibot.Timestamp)
self.assertIsInstance(mainpage.previousRevision(), int)
self.assertIsInstance(mainpage.permalink(), basestring)
- self.assertIsInstance(mainpage.purge(), bool)
def testIsDisambig(self):
"""Test the integration with Extension:Disambiguator."""
@@ -579,6 +578,18 @@
self.assertFalse(cat_not_hidden.isHiddenCategory())
+class TestPageUserAction(DefaultSiteTestCase):
+
+ """Test page user actions."""
+
+ cached = True
+ user = True
+
+ def test_purge(self):
+ mainpage = self.get_mainpage()
+ self.assertIsInstance(mainpage.purge(), bool)
+
+
if __name__ == '__main__':
try:
unittest.main()
diff --git a/tests/script_tests.py b/tests/script_tests.py
index 5763c37..0cb3958 100644
--- a/tests/script_tests.py
+++ b/tests/script_tests.py
@@ -415,6 +415,7 @@
site = True
def setUp(self):
+ super(TestScript, self).setUp()
"""Prepare the environment for running the pwb.py script."""
self.old_pywikibot_dir = None
if 'PYWIKIBOT2_DIR' in os.environ:
@@ -423,6 +424,7 @@
def tearDown(self):
"""Restore the environment after running the pwb.py script."""
+ super(TestScript, self).tearDown()
del os.environ['PYWIKIBOT2_DIR']
if self.old_pywikibot_dir:
os.environ['PYWIKIBOT2_DIR'] = self.old_pywikibot_dir
diff --git a/tests/site_tests.py b/tests/site_tests.py
index 6c600c7..1e35899 100644
--- a/tests/site_tests.py
+++ b/tests/site_tests.py
@@ -144,11 +144,6 @@
self.assertFalse(mysite.isInterwikiLink("foo"))
self.assertIsInstance(mysite.redirectRegex().pattern, basestring)
self.assertIsInstance(mysite.category_on_one_line(), bool)
- for grp in ("user", "autoconfirmed", "bot", "sysop", "nosuchgroup"):
- self.assertIsInstance(mysite.has_group(grp), bool)
- for rgt in ("read", "edit", "move", "delete", "rollback", "block",
- "nosuchright"):
- self.assertIsInstance(mysite.has_right(rgt), bool)
def testConstructors(self):
"""Test cases for site constructors."""
@@ -223,21 +218,6 @@
self.assertIsInstance(mysite.logged_in(), bool)
self.assertIsInstance(mysite.logged_in(True), bool)
self.assertIsInstance(mysite.userinfo, dict)
- self.assertIsInstance(mysite.is_blocked(), bool)
- self.assertIsInstance(mysite.messages(), bool)
- self.assertIsInstance(mysite.has_right("edit"), bool)
- self.assertFalse(mysite.has_right("nonexistent_right"))
- self.assertIsInstance(mysite.has_group("bots"), bool)
- self.assertFalse(mysite.has_group("nonexistent_group"))
- try:
- self.assertIsInstance(mysite.is_blocked(True), bool)
- self.assertIsInstance(mysite.has_right("edit", True), bool)
- self.assertFalse(mysite.has_right("nonexistent_right", True))
- self.assertIsInstance(mysite.has_group("bots", True), bool)
- self.assertFalse(mysite.has_group("nonexistent_group", True))
- except pywikibot.NoUsername:
- pywikibot.warning(
- "Cannot test Site methods for sysop; no sysop account configured.")
for msg in ("1movedto2", "about", "aboutpage", "aboutsite",
"accesskey-n-portal"):
@@ -619,9 +599,9 @@
self.assertRaises(pywikibot.Error, mysite.blocks,
starttime="2008-08-03T23:59:59Z",
endtime="2008-08-03T00:00:01Z", reverse=True, total=5)
- for block in mysite.blocks(users=mysite.user(), total=5):
+ for block in mysite.blocks(users='80.100.22.71', total=5):
self.assertIsInstance(block, dict)
- self.assertEqual(block['user'], mysite.user())
+ self.assertEqual(block['user'], '80.100.22.71')
def testExturlusage(self):
"""Test the site.exturlusage() method."""
@@ -712,6 +692,20 @@
"""Test site method using a user."""
user = True
+
+ def test_methods(self):
+ mysite = self.get_site()
+ self.assertIsInstance(mysite.is_blocked(), bool)
+ self.assertIsInstance(mysite.messages(), bool)
+ self.assertIsInstance(mysite.has_right("edit"), bool)
+ self.assertFalse(mysite.has_right("nonexistent_right"))
+ self.assertIsInstance(mysite.has_group("bots"), bool)
+ self.assertFalse(mysite.has_group("nonexistent_group"))
+ for grp in ("user", "autoconfirmed", "bot", "sysop", "nosuchgroup"):
+ self.assertIsInstance(mysite.has_group(grp), bool)
+ for rgt in ("read", "edit", "move", "delete", "rollback", "block",
+ "nosuchright"):
+ self.assertIsInstance(mysite.has_right(rgt), bool)
def testLogEvents(self):
"""Test the site.logevents() method."""
@@ -1028,17 +1022,25 @@
for rev in mysite.watchlist_revs(showAnon=False, total=5):
self.assertIsInstance(rev, dict)
+
+class SiteSysopTestCase(DefaultSiteTestCase):
+
+ """Test site method using a sysop account."""
+
+ sysop = True
+
+ def test_methods(self):
+ mysite = self.get_site()
+ self.assertIsInstance(mysite.is_blocked(True), bool)
+ self.assertIsInstance(mysite.has_right("edit", True), bool)
+ self.assertFalse(mysite.has_right("nonexistent_right", True))
+ self.assertIsInstance(mysite.has_group("bots", True), bool)
+ self.assertFalse(mysite.has_group("nonexistent_group", True))
+
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)
- except pywikibot.NoUsername:
- pywikibot.warning(
- "Cannot test Site.deleted_revs; no sysop account configured.")
- return
gen = mysite.deletedrevs(total=10, page=mainpage)
for dr in gen:
break
@@ -1095,6 +1097,13 @@
page=mainpage, start="2008-09-03T23:59:59Z",
end="2008-09-03T00:00:01Z", reverse=True,
total=5)
+
+
+class SiteUserTestCase2(DefaultSiteTestCase):
+
+ """More tests that rely on a user account."""
+
+ user = True
def testUsers(self):
"""Test the site.users() method."""
@@ -1503,20 +1512,23 @@
'wikidatatest': {
'family': 'wikidata',
'code': 'test',
+ 'enabled': False,
},
'wikipediatest': {
'family': 'wikipedia',
'code': 'test',
+ 'enabled': True,
}
}
- def test_is_uploaddisabled_wp(self):
- site = self.get_site('wikipediatest')
- self.assertFalse(site.is_uploaddisabled())
+ user = True
- def test_is_uploaddisabled_wd(self):
- site = self.get_site('wikidatatest')
- self.assertTrue(site.is_uploaddisabled())
+ def test_is_uploaddisabled(self, key):
+ site = self.get_site(key)
+ if self.sites[key]['enabled']:
+ self.assertFalse(site.is_uploaddisabled())
+ else:
+ self.assertTrue(site.is_uploaddisabled())
class TestDataSitePreloading(WikidataTestCase):
--
To view, visit https://gerrit.wikimedia.org/r/168958
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I690423556f1266f3ebe0bee11aa91b41b9965baf
Gerrit-PatchSet: 3
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
John Vandenberg has submitted this change and it was merged.
Change subject: Bug 72527 - CircularRedirect exception throws another exception
......................................................................
Bug 72527 - CircularRedirect exception throws another exception
CircularRedirect needs a page as input param.
Change-Id: I65cc58a1568b922336fcf5c85651cdc4172444d2
---
M pywikibot/site.py
1 file changed, 1 insertion(+), 1 deletion(-)
Approvals:
John Vandenberg: Verified
XZise: Looks good to me, approved
Mpaa: Looks good to me, approved
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 17611ee..86de719 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -2344,7 +2344,7 @@
target_title = u'%(title)s%(section)s' % redirmap[title]
if target_title == title or "pages" not in result['query']:
# no "pages" element indicates a circular redirect
- raise pywikibot.CircularRedirect(target_title)
+ raise pywikibot.CircularRedirect(page)
pagedata = list(result['query']['pages'].values())[0]
# there should be only one value in 'pages', and it is the target
if self.sametitle(pagedata['title'], target_title):
--
To view, visit https://gerrit.wikimedia.org/r/168837
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I65cc58a1568b922336fcf5c85651cdc4172444d2
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
John Vandenberg has submitted this change and it was merged.
Change subject: Add NoCreateError and fix a bug about issubclass
......................................................................
Add NoCreateError and fix a bug about issubclass
With nocreate=True, if page doesn't exist, API will return
missingtitle which is not recognized by PWB. This patch adds
NoCreateError to match with this missingtitle in this case.
This patch also fixes a bug when issubclass is used but the first
parameter is not a class, leading to an error
"TypeError: issubclass() arg 1 must be a class"
Change-Id: I11f80783c9febce51538e868a0b1edb42cce4ec3
---
M pywikibot/__init__.py
M pywikibot/exceptions.py
M pywikibot/site.py
3 files changed, 15 insertions(+), 5 deletions(-)
Approvals:
John Vandenberg: Verified; Looks good to me, approved
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index ad0c475..14327d2 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -40,7 +40,7 @@
NoUsername, UserBlocked,
PageRelatedError, IsRedirectPage, IsNotRedirectPage,
PageSaveRelatedError, PageNotSaved, OtherPageSaveError,
- LockedPage, CascadeLockedPage, LockedNoPage,
+ LockedPage, CascadeLockedPage, LockedNoPage, NoCreateError,
EditConflict, PageDeletedConflict, PageCreatedConflict,
ServerError, FatalServerError, Server504Error,
CaptchaError, SpamfilterError, CircularRedirect,
@@ -76,7 +76,7 @@
'NoUsername', 'UserBlocked',
'PageRelatedError', 'IsRedirectPage', 'IsNotRedirectPage',
'PageSaveRelatedError', 'PageNotSaved', 'OtherPageSaveError',
- 'LockedPage', 'CascadeLockedPage', 'LockedNoPage',
+ 'LockedPage', 'CascadeLockedPage', 'LockedNoPage', 'NoCreateError',
'EditConflict', 'PageDeletedConflict', 'PageCreatedConflict',
'UploadWarning',
'ServerError', 'FatalServerError', 'Server504Error',
diff --git a/pywikibot/exceptions.py b/pywikibot/exceptions.py
index ad0c566..d735038 100644
--- a/pywikibot/exceptions.py
+++ b/pywikibot/exceptions.py
@@ -35,6 +35,7 @@
- PageDeletedConflict: Page was deleted since being retrieved
- PageCreatedConflict: Page was created by another user
- ArticleExistsConflict: Page article already exists
+ - NoCreateError: parameter nocreate not allow page creation
ServerError: a problem with the server.
- FatalServerError: A fatal/non-recoverable server error
@@ -259,6 +260,13 @@
PageNotSaved = PageSaveRelatedError
+class NoCreateError(PageSaveRelatedError):
+
+ """Parameter nocreate doesn't allow page creation."""
+
+ message = u"Page %s could not be created due to parameter nocreate"
+
+ pass
class EditConflict(PageSaveRelatedError):
diff --git a/pywikibot/site.py b/pywikibot/site.py
index dffd696..17611ee 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -50,6 +50,7 @@
SiteDefinitionError,
NoUsername,
SpamfilterError,
+ NoCreateError,
UserBlocked,
)
@@ -3682,6 +3683,7 @@
"noedit-anon": """Bot is not logged in, and anon users are not authorized to edit on %(site)s wiki""",
"noedit": "User %(user)s not authorized to edit pages on %(site)s wiki",
+ "missingtitle": NoCreateError,
"editconflict": EditConflict,
"articleexists": PageCreatedConflict,
"pagedeleted": PageDeletedConflict,
@@ -3775,9 +3777,7 @@
% err.code,
_logger)
if err.code in self._ep_errors:
- if issubclass(self._ep_errors[err.code], PageSaveRelatedError):
- raise self._ep_errors[err.code](page)
- else:
+ if isinstance(self._ep_errors[err.code], basestring):
errdata = {
'site': self,
'title': page.title(withSection=False),
@@ -3785,6 +3785,8 @@
'info': err.info
}
raise Error(self._ep_errors[err.code] % errdata)
+ else:
+ raise self._ep_errors[err.code](page)
pywikibot.debug(
u"editpage: Unexpected error code '%s' received."
% err.code,
--
To view, visit https://gerrit.wikimedia.org/r/168816
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I11f80783c9febce51538e868a0b1edb42cce4ec3
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero <nullzero.free(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: jenkins-bot <>