jenkins-bot has submitted this change and it was merged.
Change subject: Adding a bunch of actions to block on simulate mode
......................................................................
Adding a bunch of actions to block on simulate mode
There were several actions that weren't listed in actions_to_block,
but also perform modifications on the server.
Since there was also a list of write actions in api.py, I've merged
them on that file, and left actions_to_block empty as an additional
list of actions to add for wiki families with more extensions, etc
Repurposed the list of actions in api.py so that they're also checked
when we've specified the -simulate option
I went to https://www.mediawiki.org/w/api.php and added all of them
that are part of core and the description contains "This module
requires write rights"
Bug: 69896
Change-Id: Ibbd05e86bf585e3c9f21670fd2be1978dbe27ebd
---
M pywikibot/config2.py
M pywikibot/data/api.py
M pywikibot/site.py
3 files changed, 20 insertions(+), 12 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
XZise: Looks good to me, but someone else must approve
jenkins-bot: Verified
diff --git a/pywikibot/config2.py b/pywikibot/config2.py
index 4b31fc1..6ea3c45 100644
--- a/pywikibot/config2.py
+++ b/pywikibot/config2.py
@@ -638,11 +638,11 @@
# Simulate settings
-# Defines what actions the bots are NOT allowed to do (e.g. 'edit') on wikipedia
-# servers. Allows simulation runs of bots to be carried out without changing any
-# page on the server side. This setting may be overridden in user_config.py.
-actions_to_block = ['edit', 'watch', 'move', 'delete', 'undelete', 'protect',
- 'emailuser']
+# Defines what additional actions the bots are NOT allowed to do (e.g. 'edit')
+# on the wiki server. Allows simulation runs of bots to be carried out without
+# changing any page on the server side. Use this setting to add more actions
+# in user-config.py for wikis with extra write actions.
+actions_to_block = []
# Set simulate to True or use -simulate option to block all actions given above.
simulate = False
diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index 643369c..bdb39a3 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -137,14 +137,19 @@
if "action" not in kwargs:
raise ValueError("'action' specification missing from Request.")
self.update(**kwargs)
+ # Actions that imply database updates on the server, used for various
+ # things like throttling or skipping actions when we're in simulation
+ # mode
self.write = self.params["action"] in (
"edit", "move", "rollback", "delete", "undelete",
"protect", "block", "unblock", "watch", "patrol",
- "import", "userrights", "upload", "wbeditentity",
- "wbsetlabel", "wbsetdescription", "wbsetaliases",
- "wblinktitles", "wbsetsitelink", "wbcreateclaim",
- "wbremoveclaims", "wbsetclaimvalue", "wbsetreference",
- "wbremovereferences"
+ "import", "userrights", "upload", "emailuser",
+ "createaccount", "setnotificationtimestamp",
+ "filerevert", "options", "purge", "revisiondelete",
+ "wbeditentity", "wbsetlabel", "wbsetdescription",
+ "wbsetaliases", "wblinktitles", "wbsetsitelink",
+ "wbcreateclaim", "wbremoveclaims", "wbsetclaimvalue",
+ "wbsetreference", "wbremovereferences"
)
# MediaWiki 1.23 allows assertion for any action,
# whereas earlier WMF wikis and others used an extension which
@@ -251,7 +256,7 @@
return "%s.%s<%s->%r>" % (self.__class__.__module__, self.__class__.__name__, self.site, str(self))
def _simulate(self, action):
- if action and config.simulate and action in config.actions_to_block:
+ if action and config.simulate and (self.write or action in config.actions_to_block):
pywikibot.output(
u'\03{lightyellow}SIMULATION: %s action blocked.\03{default}'
% action)
diff --git a/pywikibot/site.py b/pywikibot/site.py
index befcf3a..698be2d 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -3950,7 +3950,10 @@
pywikibot.output(u"Upload: unrecognized response: %s" % result)
if result["result"] == "Success":
pywikibot.output(u"Upload successful.")
- filepage._imageinfo = result["imageinfo"]
+ # If we receive a nochange, that would mean we're in simulation
+ # mode, don't attempt to access imageinfo
+ if "nochange" not in result:
+ filepage._imageinfo = result["imageinfo"]
return
@deprecate_arg("number", "step")
--
To view, visit https://gerrit.wikimedia.org/r/155720
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ibbd05e86bf585e3c9f21670fd2be1978dbe27ebd
Gerrit-PatchSet: 4
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Martineznovo <martineznovo(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Martineznovo <martineznovo(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: [FEAT] UploadWarning uses the warning code
......................................................................
[FEAT] UploadWarning uses the warning code
To allow scripts easier to determine what the warning is about the
UploadWarning contains an attribute 'code' which is the warning
code recieved from the API.
The UploadWarning is now a subclass of APIError. This may break
scripts which already parse the warning message but use
'str(exception)' instead of 'exception.message'.
The upload.py script uses this feature to allow abortion only because
of specific warnings.
Bug: 69852
Change-Id: I78e572ce5e40e7cfcdfdf67138c8aa2e41bfebdb
---
M pywikibot/__init__.py
M pywikibot/data/api.py
M pywikibot/exceptions.py
M pywikibot/site.py
M scripts/upload.py
5 files changed, 44 insertions(+), 20 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index 59bb683..0d13cdf 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -36,7 +36,7 @@
Error, InvalidTitle, BadTitle, NoPage, SectionError,
NoSuchSite, NoUsername, UserBlocked,
PageRelatedError, IsRedirectPage, IsNotRedirectPage,
- PageNotSaved, UploadWarning, LockedPage, EditConflict,
+ PageNotSaved, LockedPage, EditConflict,
ServerError, FatalServerError, Server504Error,
CaptchaError, SpamfilterError, CircularRedirect,
WikiBaseError, CoordinateGlobeUnknownException,
@@ -52,6 +52,7 @@
)
from pywikibot.tools import UnicodeMixin, deprecated, deprecate_arg
from pywikibot.i18n import translate
+from pywikibot.data.api import UploadWarning
__all__ = (
'config', 'ui', 'UnicodeMixin', 'translate', 'deprecated', 'deprecate_arg',
diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index 643369c..f295cde 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -46,7 +46,7 @@
lagpattern = re.compile(r"Waiting for [\d.]+: (?P<lag>\d+) seconds? lagged")
-class APIError(pywikibot.Error):
+class APIError(Error):
"""The wiki site returned an error message."""
@@ -58,13 +58,26 @@
self.unicode = unicode(self.__str__())
def __repr__(self):
- return 'APIError("%(code)s", "%(info)s", %(other)s)' % self.__dict__
+ return '{name}("{code}", "{info}", {other})'.format(
+ name=self.__class__.__name__, **self.__dict__)
def __str__(self):
return "%(code)s: %(info)s" % self.__dict__
-class TimeoutError(pywikibot.Error):
+class UploadWarning(APIError):
+
+ """Upload failed with a warning message (passed as the argument)."""
+
+ def __init__(self, code, message):
+ super(UploadWarning, self).__init__(code, message)
+
+ @property
+ def message(self):
+ return self.info
+
+
+class TimeoutError(Error):
pass
diff --git a/pywikibot/exceptions.py b/pywikibot/exceptions.py
index 7f9a06d..35f7d2d 100644
--- a/pywikibot/exceptions.py
+++ b/pywikibot/exceptions.py
@@ -168,11 +168,6 @@
"""Captcha is asked and config.solve_captcha == False."""
-class UploadWarning(Error):
-
- """Upload failed with a warning message (passed as the argument)."""
-
-
class AutoblockUser(Error):
"""
@@ -193,3 +188,7 @@
class CoordinateGlobeUnknownException(WikiBaseError, NotImplementedError):
""" This globe is not implemented yet in either WikiBase or pywikibot """
+
+# TODO: Warn about the deprecated usage
+import pywikibot.data.api
+UploadWarning = pywikibot.data.api.UploadWarning
diff --git a/pywikibot/site.py b/pywikibot/site.py
index befcf3a..565389d 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -3944,7 +3944,7 @@
if "warnings" in result:
warning = list(result["warnings"].keys())[0]
message = result["warnings"][warning]
- raise pywikibot.UploadWarning(upload_warnings[warning]
+ raise pywikibot.UploadWarning(warning, upload_warnings[warning]
% {'msg': message})
elif "result" not in result:
pywikibot.output(u"Upload: unrecognized response: %s" % result)
diff --git a/scripts/upload.py b/scripts/upload.py
index ba59729..8a9a44d 100755
--- a/scripts/upload.py
+++ b/scripts/upload.py
@@ -9,7 +9,8 @@
-filename Target filename
-noverify Do not ask for verification of the upload description if one
is given
- -abortonwarn Abort upload on warning
+ -abortonwarn: Abort upload on the specified warning type. If no warning type
+ is specified abort on all warnings.
If any other arguments are given, the first is the URL or filename to upload,
and the rest is a proposed description to go with the upload. If none of these
@@ -34,6 +35,7 @@
import urlparse
import tempfile
import pywikibot
+import pywikibot.data.api
from pywikibot import config
@@ -41,7 +43,7 @@
def __init__(self, url, urlEncoding=None, description=u'',
useFilename=None, keepFilename=False,
verifyDescription=True, ignoreWarning=False,
- targetSite=None, uploadByUrl=False, abortOnWarn=False):
+ targetSite=None, uploadByUrl=False, aborts=[]):
"""
@param ignoreWarning: Set this to True if you want to upload even if
another file would be overwritten or another mistake would be
@@ -55,7 +57,7 @@
self.keepFilename = keepFilename
self.verifyDescription = verifyDescription
self.ignoreWarning = ignoreWarning
- self.abortOnWarn = abortOnWarn
+ self.aborts = aborts
if config.upload_to_commons:
self.targetSite = targetSite or pywikibot.Site('commons',
'commons')
@@ -189,6 +191,13 @@
self.description = newDescription
return filename
+ def abort_on_warn(self, warn_code):
+ """Determine if the warning message should cause an abort."""
+ if self.aborts is True:
+ return True
+ else:
+ return warn_code in self.aborts
+
def upload_image(self, debug=False):
"""Upload the image at self.url to the target wiki.
@@ -217,10 +226,9 @@
site.upload(imagepage, source_filename=temp,
ignore_warnings=self.ignoreWarning)
- except pywikibot.UploadWarning as warn:
- pywikibot.output(u"We got a warning message: ", newline=False)
- pywikibot.output(str(warn))
- if self.abortOnWarn:
+ except pywikibot.data.api.UploadWarning as warn:
+ pywikibot.output(u"We got a warning message: {0}".format(warn.message))
+ if self.abort_on_warn(warn.code):
answer = "N"
else:
answer = pywikibot.inputChoice(u"Do you want to ignore?",
@@ -257,7 +265,7 @@
keepFilename = False
useFilename = None
verifyDescription = True
- abortOnWarn = False
+ aborts = set()
# process all global bot args
# returns a list of non-global args, i.e. args for upload.py
@@ -270,7 +278,10 @@
elif arg.startswith('-noverify'):
verifyDescription = False
elif arg.startswith('-abortonwarn'):
- abortOnWarn = True
+ if len(arg) > len('-abortonwarn:') and aborts is not True:
+ aborts.add(arg[len('-abortonwarn:'):])
+ else:
+ aborts = True
elif url == u'':
url = arg
else:
@@ -279,7 +290,7 @@
bot = UploadRobot(url, description=description, useFilename=useFilename,
keepFilename=keepFilename,
verifyDescription=verifyDescription,
- abortOnWarn=abortOnWarn)
+ aborts=aborts)
bot.run()
if __name__ == "__main__":
--
To view, visit https://gerrit.wikimedia.org/r/155739
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I78e572ce5e40e7cfcdfdf67138c8aa2e41bfebdb
Gerrit-PatchSet: 3
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
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 <>
jenkins-bot has submitted this change and it was merged.
Change subject: upload.py: Add option to automatically abort upload on warning
......................................................................
upload.py: Add option to automatically abort upload on warning
Useful when a script is issuing a batch of upload.py commands to upload
a lot of files, and we want to skip files that are already uploaded
without user intervention. Unfortunately, it will also skip the upload
if there are warnings not related to upload over an existing filename,
but because how warnings are handled, there's no way to tell what kind
of warning we've received.
Bug: 69852
Change-Id: I5e23049fb51f1804c230bff67525baa15e4c1f1c
---
M scripts/upload.py
1 file changed, 13 insertions(+), 4 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/scripts/upload.py b/scripts/upload.py
index 108f564..ba59729 100755
--- a/scripts/upload.py
+++ b/scripts/upload.py
@@ -9,6 +9,7 @@
-filename Target filename
-noverify Do not ask for verification of the upload description if one
is given
+ -abortonwarn Abort upload on warning
If any other arguments are given, the first is the URL or filename to upload,
and the rest is a proposed description to go with the upload. If none of these
@@ -40,7 +41,7 @@
def __init__(self, url, urlEncoding=None, description=u'',
useFilename=None, keepFilename=False,
verifyDescription=True, ignoreWarning=False,
- targetSite=None, uploadByUrl=False):
+ targetSite=None, uploadByUrl=False, abortOnWarn=False):
"""
@param ignoreWarning: Set this to True if you want to upload even if
another file would be overwritten or another mistake would be
@@ -54,6 +55,7 @@
self.keepFilename = keepFilename
self.verifyDescription = verifyDescription
self.ignoreWarning = ignoreWarning
+ self.abortOnWarn = abortOnWarn
if config.upload_to_commons:
self.targetSite = targetSite or pywikibot.Site('commons',
'commons')
@@ -218,8 +220,11 @@
except pywikibot.UploadWarning as warn:
pywikibot.output(u"We got a warning message: ", newline=False)
pywikibot.output(str(warn))
- answer = pywikibot.inputChoice(u"Do you want to ignore?",
- ['Yes', 'No'], ['y', 'N'], 'N')
+ if self.abortOnWarn:
+ answer = "N"
+ else:
+ answer = pywikibot.inputChoice(u"Do you want to ignore?",
+ ['Yes', 'No'], ['y', 'N'], 'N')
if answer == "y":
self.ignoreWarning = 1
self.keepFilename = True
@@ -252,6 +257,7 @@
keepFilename = False
useFilename = None
verifyDescription = True
+ abortOnWarn = False
# process all global bot args
# returns a list of non-global args, i.e. args for upload.py
@@ -263,6 +269,8 @@
useFilename = arg[10:]
elif arg.startswith('-noverify'):
verifyDescription = False
+ elif arg.startswith('-abortonwarn'):
+ abortOnWarn = True
elif url == u'':
url = arg
else:
@@ -270,7 +278,8 @@
description = u' '.join(description)
bot = UploadRobot(url, description=description, useFilename=useFilename,
keepFilename=keepFilename,
- verifyDescription=verifyDescription)
+ verifyDescription=verifyDescription,
+ abortOnWarn=abortOnWarn)
bot.run()
if __name__ == "__main__":
--
To view, visit https://gerrit.wikimedia.org/r/155560
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I5e23049fb51f1804c230bff67525baa15e4c1f1c
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Martineznovo <martineznovo(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 <>
jenkins-bot has submitted this change and it was merged.
Change subject: Allow tests created by metaclass to be run
......................................................................
Allow tests created by metaclass to be run
Running individual test cases created by metaclasses
fails as unittest uses func.__name__ to find it, while
these test cases have the name of the wrapping method name.
$ python -m unittest -v \
tests.archivebot_tests.TestArchiveBot.test_wikipedia_vi
ValueError: no such test method in
<class 'tests.archivebot_tests.TestArchiveBot'>: test_archivebot
Change-Id: I793b0e1e92f88f7f734bb730cb8d811a2409f282
---
M tests/archivebot_tests.py
M tests/date_tests.py
M tests/script_tests.py
3 files changed, 3 insertions(+), 0 deletions(-)
Approvals:
Merlijn van Deen: Looks good to me, approved
jenkins-bot: Verified
diff --git a/tests/archivebot_tests.py b/tests/archivebot_tests.py
index 8539ef3..765777c 100644
--- a/tests/archivebot_tests.py
+++ b/tests/archivebot_tests.py
@@ -84,6 +84,7 @@
dct[test_name] = unittest.expectedFailure(test_method(code))
else:
dct[test_name] = test_method(code)
+ dct[test_name].__name__ = test_name
return type.__new__(cls, name, bases, dct)
diff --git a/tests/date_tests.py b/tests/date_tests.py
index 7d9a81f..5acf493 100644
--- a/tests/date_tests.py
+++ b/tests/date_tests.py
@@ -46,6 +46,7 @@
for formatname in date.formats:
test_name = "test_" + formatname
dct[test_name] = test_method(formatname)
+ dct[test_name].__name__ = test_name
return type.__new__(cls, name, bases, dct)
diff --git a/tests/script_tests.py b/tests/script_tests.py
index b229222..27a2ce3 100644
--- a/tests/script_tests.py
+++ b/tests/script_tests.py
@@ -230,6 +230,7 @@
dct[test_name] = unittest.expectedFailure(dct[test_name])
dct[test_name].__doc__ = \
'Test running ' + script_name + ' without arguments.'
+ dct[test_name].__name__ = test_name
return type.__new__(cls, name, bases, dct)
--
To view, visit https://gerrit.wikimedia.org/r/155499
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I793b0e1e92f88f7f734bb730cb8d811a2409f282
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: 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 <>
jenkins-bot has submitted this change and it was merged.
Change subject: [FIX] Expiry feature of Siteinfo
......................................................................
[FIX] Expiry feature of Siteinfo
The expiry needs to be converted into a timestamp also if the int
is 0 (it thought it can the cache thing completely). Also one call
used the old "force" parameter which was discontinued.
Change-Id: Ifc3406eab34e5cc5734c0659c9113cd277a23014
---
M pywikibot/site.py
1 file changed, 4 insertions(+), 4 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 96e5ee2..befcf3a 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -1080,10 +1080,10 @@
# expire = 0 (or timedelta(0)) are always expired and their bool is
# False, so skip them EXCEPT if it's literally False, then they expire
# never: "expiry is False" is different than "not expiry"!
+ # if it's a int convert to timedelta
+ if expiry is not False and isinstance(expiry, (int, float)):
+ expiry = datetime.timedelta(expiry)
if expiry or expiry is False:
- # if it's a int convert to timedelta
- if expiry is not False and isinstance(expiry, (int, float)):
- expiry = datetime.timedelta(expiry)
try:
cached = self._get_cached(key)
except KeyError:
@@ -1664,7 +1664,7 @@
"""
if LV(self.version()) >= LV("1.16"):
return pywikibot.Timestamp.fromISOformat(
- self.siteinfo.get('time', force=True))
+ self.siteinfo.get('time', expiry=0))
else:
return pywikibot.Timestamp.fromtimestampformat(
self.expand_text("{{CURRENTTIMESTAMP}}"))
--
To view, visit https://gerrit.wikimedia.org/r/155572
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ifc3406eab34e5cc5734c0659c9113cd277a23014
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
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 <>
jenkins-bot has submitted this change and it was merged.
Change subject: Use 'time' of siprop 'general' for the server time
......................................................................
Use 'time' of siprop 'general' for the server time
Instead of parsing {{CURRENTTIMESTAMP}} this uses 'time' in the
siprop 'general'. Because 'time' was only added in 1.16 it'll use
old way if required.
Change-Id: Ia91ca4ec6d8b5bcc9d7b888d0c976b4f58a1267d
---
M pywikibot/site.py
M tests/site_tests.py
2 files changed, 32 insertions(+), 9 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
XZise: Looks good to me, but someone else must approve
jenkins-bot: Verified
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 5e0d28b..77e3b84 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -1570,6 +1570,7 @@
concat = msgs['and'] + msgs['word-separator']
return msgs['comma-separator'].join(args[:-2] + [concat.join(args[-2:])])
+ @need_version("1.12")
def expand_text(self, text, title=None, includecomments=None):
""" Parse the given text for preprocessing and rendering.
@@ -1600,17 +1601,35 @@
return req.submit()['expandtemplates'][key]
def getcurrenttimestamp(self):
- """Return server time, {{CURRENTTIMESTAMP}}, as a string.
-
- Format is 'yyyymmddhhmmss'
-
"""
- return self.expand_text("{{CURRENTTIMESTAMP}}")
+ Return the server time as a MediaWiki timestamp string.
+
+ It calls L{getcurrenttime} first so it queries the server to get the
+ current server time.
+
+ @return: the server time
+ @rtype: str (as 'yyyymmddhhmmss')
+ """
+ return self.getcurrenttime().totimestampformat()
def getcurrenttime(self):
- """Return a Timestamp object representing the current server time."""
- ts = self.getcurrenttimestamp()
- return pywikibot.Timestamp.fromtimestampformat(ts)
+ """
+ Return a Timestamp object representing the current server time.
+
+ For wikis with a version newer than 1.16 it uses the 'time' property
+ of the siteinfo 'general'. It'll force a reload before returning the
+ time. It requests to expand the text '{{CURRENTTIMESTAMP}}' for older
+ wikis.
+
+ @return the current server time
+ @rtype: L{Timestamp}
+ """
+ if LV(self.version()) >= LV("1.16"):
+ return pywikibot.Timestamp.fromISOformat(
+ self.siteinfo.get('time', force=True))
+ else:
+ return pywikibot.Timestamp.fromtimestampformat(
+ self.expand_text("{{CURRENTTIMESTAMP}}"))
def getmagicwords(self, word):
"""Return list of localized "word" magic words for the site."""
diff --git a/tests/site_tests.py b/tests/site_tests.py
index 241bcbe..a2b7cb3 100644
--- a/tests/site_tests.py
+++ b/tests/site_tests.py
@@ -197,7 +197,11 @@
self.assertTrue(len(mysite.mediawiki_messages(['*'])) > 10)
self.assertFalse('*' in mysite.mediawiki_messages(['*']))
- self.assertType(mysite.getcurrenttimestamp(), basestring)
+ self.assertType(mysite.getcurrenttime(), pywikibot.Timestamp)
+ ts = mysite.getcurrenttimestamp()
+ self.assertType(ts, basestring)
+ self.assertRegexpMatches(ts, r'(19|20)\d\d[0-1]\d[0-3]\d[0-2]\d[0-5]\d[0-5]\d')
+
self.assertType(mysite.siteinfo, pywikibot.site.Siteinfo)
self.assertType(mysite.months_names, list)
self.assertEqual(mysite.months_names[4], (u'May', u'May'))
--
To view, visit https://gerrit.wikimedia.org/r/155009
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ia91ca4ec6d8b5bcc9d7b888d0c976b4f58a1267d
Gerrit-PatchSet: 5
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
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 <>