Newer
Older
from copy import deepcopy
from datetime import date
import unittest
import unittest.mock as mock
import pytest
import requests
import responses
if __name__ == "__main__":
print()
print("Note: Running in stand-alone mode. Consult the README")
print(" (section 'Contributing') for advice on running tests.")
print()
logging.basicConfig(level=logging.DEBUG)
def metaResponse(self, version='1.24wmf17', rights=None):
if rights is None:
rights = [
"createaccount", "read", "edit", "createpage", "createtalk",
"editmyusercss", "editmyuserjs", "viewmywatchlist",
"editmywatchlist", "viewmyprivateinfo", "editmyprivateinfo",
"editmyoptions", "centralauth-merge", "abusefilter-view",
"abusefilter-log", "translate", "vipsscaler-test", "upload"
]
# @formatter:off
namespaces = {
-2: {"id": -2, "*": "Media", "canonical": "Media", "case": "first-letter"},
-1: {"id": -1, "*": "Special", "canonical": "Special", "case": "first-letter"},
0: {"id": 0, "*": "", "case": "first-letter", "content": ""},
1: {"id": 1, "*": "Talk", "canonical": "Talk", "case": "first-letter", "subpages": ""},
2: {"id": 2, "*": "User", "canonical": "User", "case": "first-letter", "subpages": ""},
3: {"id": 3, "*": "User talk", "canonical": "User talk", "case": "first-letter", "subpages": ""},
4: {"id": 4, "*": "Wikipedia", "canonical": "Project", "case": "first-letter", "subpages": ""},
5: {"id": 5, "*": "Wikipedia talk", "canonical": "Project talk", "case": "first-letter", "subpages": ""},
6: {"id": 6, "*": "File", "canonical": "File", "case": "first-letter"},
7: {"id": 7, "*": "File talk", "canonical": "File talk", "case": "first-letter", "subpages": ""},
8: {"id": 8, "*": "MediaWiki", "canonical": "MediaWiki", "case": "first-letter", "subpages": ""},
9: {"id": 9, "*": "MediaWiki talk", "canonical": "MediaWiki talk", "case": "first-letter", "subpages": ""},
10: {"id": 10, "*": "Template", "canonical": "Template", "case": "first-letter", "subpages": ""},
11: {"id": 11, "*": "Template talk", "canonical": "Template talk", "case": "first-letter", "subpages": ""},
12: {"id": 12, "*": "Help", "canonical": "Help", "case": "first-letter", "subpages": ""},
13: {"id": 13, "*": "Help talk", "canonical": "Help talk", "case": "first-letter", "subpages": ""},
14: {"id": 14, "*": "Category", "canonical": "Category", "case": "first-letter"},
15: {"id": 15, "*": "Category talk", "canonical": "Category talk", "case": "first-letter", "subpages": ""},
}
# @formatter:on
return {
"query": {
"general": {
"generator": f"MediaWiki {version}"
},
"namespaces": namespaces,
"userinfo": {
"anon": "",
"groups": ["*"],
"id": 0,
"name": "127.0.0.1",
"rights": rights
}
}
}
def metaResponseAsJson(self, **kwargs):
return json.dumps(self.metaResponse(**kwargs))
def httpShouldReturn(self, body=None, callback=None, scheme='https', host='test.wikipedia.org', path='/w/',
script='api', headers=None, status=200, method='GET'):
url = f'{scheme}://{host}{path}{script}.php'
mock = responses.GET if method == 'GET' else responses.POST
responses.add_callback(mock, url, callback=callback)
responses.add(mock, url, body=body, content_type='application/json',
adding_headers=headers, status=status)
self.httpShouldReturn(self.metaResponseAsJson())
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
site = mwclient.Site('test.wikipedia.org')
responses.reset()
return site
def makePageResponse(self, title='Dummy.jpg', **kwargs):
# Creates a dummy page response
pageinfo = {
"contentmodel": "wikitext",
"lastrevid": 112353797,
"length": 389,
"ns": 6,
"pageid": 738154,
"pagelanguage": "en",
"protection": [],
"title": title,
"touched": "2014-09-10T20:37:25Z"
}
pageinfo.update(**kwargs)
res = {
"query": {
"pages": {
"9": pageinfo
}
}
}
return json.dumps(res)
class TestClient(TestCase):
def setUp(self):
pass
def testVersion(self):
# The version specified in setup.py should equal the one specified in client.py
if sys.version_info >= (3, 8):
import importlib.metadata
version = importlib.metadata.version("mwclient")
else:
import pkg_resources # part of setuptools
version = pkg_resources.require("mwclient")[0].version
@responses.activate
def test_https_as_default(self):
# 'https' should be the default scheme
self.httpShouldReturn(self.metaResponseAsJson(), scheme='https')
site = mwclient.Site('test.wikipedia.org')
assert len(responses.calls) == 1
assert responses.calls[0].request.method == 'GET'
@responses.activate
def test_max_lag(self):
# Client should wait and retry if lag exceeds max-lag
def request_callback(request):
if len(responses.calls) == 0:
return (200, {'x-database-lag': '0', 'retry-after': '0'}, '')
else:
return (200, {}, self.metaResponseAsJson())
self.httpShouldReturn(callback=request_callback, scheme='https')
site = mwclient.Site('test.wikipedia.org')
assert len(responses.calls) == 2
assert 'retry-after' in responses.calls[0].response.headers # type: ignore
assert 'retry-after' not in responses.calls[1].response.headers # type: ignore
@responses.activate
def test_http_error(self):
# Client should raise HTTPError
self.httpShouldReturn('Uh oh', scheme='https', status=400)
with pytest.raises(requests.exceptions.HTTPError):
site = mwclient.Site('test.wikipedia.org')
@responses.activate
def test_force_http(self):
# Setting http should work
self.httpShouldReturn(self.metaResponseAsJson(), scheme='http')
site = mwclient.Site('test.wikipedia.org', scheme='http')
assert len(responses.calls) == 1
@responses.activate
def test_user_agent_is_sent(self):
# User specified user agent should be sent sent to server
self.httpShouldReturn(self.metaResponseAsJson())
site = mwclient.Site('test.wikipedia.org', clients_useragent='MyFabulousClient')
assert 'MyFabulousClient' in responses.calls[0].request.headers['user-agent']
@responses.activate
def test_custom_headers_are_sent(self):
# Custom headers should be sent to the server
self.httpShouldReturn(self.metaResponseAsJson())
site = mwclient.Site('test.wikipedia.org', custom_headers={'X-Wikimedia-Debug': 'host=mw1099.eqiad.wmnet; log'})
assert 'host=mw1099.eqiad.wmnet; log' in responses.calls[0].request.headers['X-Wikimedia-Debug']
@responses.activate
def test_basic_request(self):
self.httpShouldReturn(self.metaResponseAsJson())
site = mwclient.Site('test.wikipedia.org')
assert responses.calls[0].request.url is not None
assert 'action=query' in responses.calls[0].request.url
assert 'meta=siteinfo%7Cuserinfo' in responses.calls[0].request.url
@responses.activate
def test_httpauth_defaults_to_basic_auth(self):
self.httpShouldReturn(self.metaResponseAsJson())
site = mwclient.Site('test.wikipedia.org', httpauth=('me', 'verysecret'))
assert isinstance(site.connection.auth, requests.auth.HTTPBasicAuth)
@responses.activate
def test_basic_auth_non_latin(self):
self.httpShouldReturn(self.metaResponseAsJson())
site = mwclient.Site('test.wikipedia.org', httpauth=('我', '非常秘密'))
assert isinstance(site.connection.auth, requests.auth.HTTPBasicAuth)
@responses.activate
def test_httpauth_raise_error_on_invalid_type(self):
self.httpShouldReturn(self.metaResponseAsJson())
with pytest.raises(RuntimeError):
site = mwclient.Site('test.wikipedia.org',
httpauth=1) # type: ignore[arg-type]
@responses.activate
def test_oauth(self):
self.httpShouldReturn(self.metaResponseAsJson())
site = mwclient.Site('test.wikipedia.org',
consumer_token='a', consumer_secret='b',
access_token='c', access_secret='d')
assert isinstance(site.connection.auth, OAuth1)
@responses.activate
def test_api_disabled(self):
# Should raise APIDisabledError if API is not enabled
self.httpShouldReturn('MediaWiki API is not enabled for this site.')
with pytest.raises(mwclient.errors.APIDisabledError):
site = mwclient.Site('test.wikipedia.org')
@responses.activate
def test_version(self):
# Should parse the MediaWiki version number correctly
self.httpShouldReturn(self.metaResponseAsJson(version='1.16'))
site = mwclient.Site('test.wikipedia.org')
assert site.initialized is True
assert site.version == (1, 16)
@responses.activate
def test_min_version(self):
# Should raise MediaWikiVersionError if API version is < 1.16
self.httpShouldReturn(self.metaResponseAsJson(version='1.15'))
with pytest.raises(mwclient.errors.MediaWikiVersionError):
site = mwclient.Site('test.wikipedia.org')
@responses.activate
def test_private_wiki(self):
# Should not raise error
self.httpShouldReturn(json.dumps({
'error': {
'code': 'readapidenied',
'info': 'You need read permission to use this module'
}
}))
site = mwclient.Site('test.wikipedia.org')
assert site.initialized is False
# ----- Use standard setup for rest
@responses.activate
def test_headers(self):
# Content-type should be 'application/x-www-form-urlencoded' for POST requests
site = self.stdSetup()
self.httpShouldReturn('{}', method='POST')
site.post('purge', title='Main Page')
assert len(responses.calls) == 1
assert 'content-type' in responses.calls[0].request.headers
assert responses.calls[0].request.headers['content-type'] == 'application/x-www-form-urlencoded'
@responses.activate
def test_raw_index(self):
# Initializing the client should result in one request
site = self.stdSetup()
self.httpShouldReturn('Some data', script='index')
site.raw_index(action='purge', title='Main Page', http_method='GET')
assert len(responses.calls) == 1
@responses.activate
def test_api_error_response(self):
# Test that APIError is thrown on error response
site = self.stdSetup()
self.httpShouldReturn(json.dumps({
'error': {
'code': 'assertuserfailed',
'info': 'Assertion that the user is logged in failed',
'*': 'See https://en.wikipedia.org/w/api.php for API usage'
}
with pytest.raises(mwclient.errors.APIError) as excinfo:
site.api(action='edit', title='Wikipedia:Sandbox')
assert excinfo.value.code == 'assertuserfailed'
assert excinfo.value.info == 'Assertion that the user is logged in failed'
assert len(responses.calls) == 1
@responses.activate
def test_smw_error_response(self):
# Test that APIError is thrown on error response from SMW
site = self.stdSetup()
self.httpShouldReturn(json.dumps({
'error': {
'query': 'Certains « <nowiki>[[</nowiki> » dans votre requête n’ont pas été clos par des « ]] » correspondants.'
}
}), method='GET')
with pytest.raises(mwclient.errors.APIError) as excinfo:
list(site.ask('test'))
assert excinfo.value.code is None
assert excinfo.value.info == 'Certains « <nowiki>[[</nowiki> » dans votre requête n’ont pas été clos par des « ]] » correspondants.'
assert len(responses.calls) == 1
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
@responses.activate
def test_smw_response_v0_5(self):
# Test that the old SMW results format is handled
site = self.stdSetup()
self.httpShouldReturn(json.dumps({
"query": {
"results": [
{
"exists": "",
"fulltext": "Indeks (bibliotekfag)",
"fullurl": "http://example.com/wiki/Indeks_(bibliotekfag)",
"namespace": 0,
"printouts": [
{
"0": "1508611329",
"label": "Endringsdato"
}
]
},
{
"exists": "",
"fulltext": "Serendipitet",
"fullurl": "http://example.com/wiki/Serendipitet",
"namespace": 0,
"printouts": [
{
"0": "1508611394",
"label": "Endringsdato"
}
]
}
],
"serializer": "SMW\\Serializers\\QueryResultSerializer",
"version": 0.5
}
}), method='GET')
answers = {result['fulltext'] for result in site.ask('test')}
assert answers == {'Serendipitet', 'Indeks (bibliotekfag)'}
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
@responses.activate
def test_smw_response_v2(self):
# Test that the new SMW results format is handled
site = self.stdSetup()
self.httpShouldReturn(json.dumps({
"query": {
"results": {
"Indeks (bibliotekfag)": {
"exists": "1",
"fulltext": "Indeks (bibliotekfag)",
"fullurl": "http://example.com/wiki/Indeks_(bibliotekfag)",
"namespace": 0,
"printouts": {
"Endringsdato": [{
"raw": "1/2017/10/17/22/50/4/0",
"label": "Endringsdato"
}]
}
},
"Serendipitet": {
"exists": "1",
"fulltext": "Serendipitet",
"fullurl": "http://example.com/wiki/Serendipitet",
"namespace": 0,
"printouts": {
"Endringsdato": [{
"raw": "1/2017/10/17/22/50/4/0",
"label": "Endringsdato"
}]
}
}
},
"serializer": "SMW\\Serializers\\QueryResultSerializer",
"version": 2
}
}), method='GET')
answers = {result['fulltext'] for result in site.ask('test')}
assert answers == {'Serendipitet', 'Indeks (bibliotekfag)'}
@responses.activate
def test_repr(self):
# Test repr()
site = self.stdSetup()
assert repr(site) == '<Site object \'test.wikipedia.org/w/\'>'
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
@mock.patch("time.sleep")
@responses.activate
def test_api_http_error(self, timesleep):
# Test error paths in raw_call, via raw_api as it's more
# convenient to call. This would be way nicer with pytest
# parametrization but you can't use parametrization inside
# unittest.TestCase :(
site = self.stdSetup()
# All HTTP errors should raise HTTPError with or without retries
self.httpShouldReturn(body="foo", status=401)
with pytest.raises(requests.exceptions.HTTPError):
site.raw_api("query", "GET")
# for a 4xx response we should *not* retry
assert timesleep.call_count == 0
with pytest.raises(requests.exceptions.HTTPError):
site.raw_api("query", "GET", retry_on_error=False)
self.httpShouldReturn(body="foo", status=503)
with pytest.raises(requests.exceptions.HTTPError):
site.raw_api("query", "GET")
# for a 5xx response we *should* retry
assert timesleep.call_count == 25
timesleep.reset_mock()
with pytest.raises(requests.exceptions.HTTPError):
site.raw_api("query", "GET", retry_on_error=False)
# check we did not retry
assert timesleep.call_count == 0
# stop sending bad statuses
self.httpShouldReturn(body="foo", status=200)
# ConnectionError should retry then pass through, takes
# advantage of responses raising ConnectionError if you
# hit a URL that hasn't been configured. Timeout follows
# the same path so we don't bother testing it separately
realhost = site.host
site.host = "notthere"
with pytest.raises(requests.exceptions.ConnectionError):
site.raw_api("query", "GET")
assert timesleep.call_count == 25
timesleep.reset_mock()
with pytest.raises(requests.exceptions.ConnectionError):
site.raw_api("query", "GET", retry_on_error=False)
# check we did not retry
assert timesleep.call_count == 0
@mock.patch("time.sleep")
@responses.activate
def test_api_dblag(self, timesleep):
site = self.stdSetup()
# db lag should retry then raise MaximumRetriesExceeded,
# even with retry_on_error set
self.httpShouldReturn(
body="foo",
status=200,
headers={"x-database-lag": "true", "retry-after": "5"}
)
with pytest.raises(mwclient.errors.MaximumRetriesExceeded):
site.raw_api("query", "GET")
assert timesleep.call_count == 25
timesleep.reset_mock()
with pytest.raises(mwclient.errors.MaximumRetriesExceeded):
site.raw_api("query", "GET", retry_on_error=False)
assert timesleep.call_count == 25
@responses.activate
def test_connection_options(self):
self.httpShouldReturn(self.metaResponseAsJson())
args = {"timeout": 60, "stream": False}
site = mwclient.Site('test.wikipedia.org', connection_options=args)
assert site.requests == args
with pytest.warns(DeprecationWarning):
site = mwclient.Site('test.wikipedia.org', reqs=args)
assert site.requests == args
with pytest.raises(ValueError):
site = mwclient.Site('test.wikipedia.org', reqs=args, connection_options=args)
class TestLogin(TestCase):
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_old_login_flow(self, raw_api, site_init):
# The login flow used before MW 1.27 that starts with a action=login POST request
login_token = 'abc+\\'
def side_effect(*args, **kwargs):
if 'lgtoken' not in kwargs:
return {
'login': {'result': 'NeedToken', 'token': login_token}
}
elif 'lgname' in kwargs:
assert kwargs['lgtoken'] == login_token
return {
'login': {'result': 'Success'}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
site.login('myusername', 'mypassword')
call_args = raw_api.call_args_list
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='login')
assert call_args[1] == mock.call('login', 'POST', lgname='myusername', lgpassword='mypassword')
assert call_args[2] == mock.call('login', 'POST', lgname='myusername', lgpassword='mypassword', lgtoken=login_token)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_new_login_flow(self, raw_api, site_init):
# The login flow used from MW 1.27 that starts with a meta=tokens GET request
login_token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'logintoken': login_token}}
}
elif 'lgname' in kwargs:
assert kwargs['lgtoken'] == login_token
return {
'login': {'result': 'Success'}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
site.login('myusername', 'mypassword')
call_args = raw_api.call_args_list
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='login')
assert call_args[1] == mock.call('login', 'POST', lgname='myusername', lgpassword='mypassword', lgtoken=login_token)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_clientlogin_success(self, raw_api, site_init):
login_token = 'abc+\\'
def api_side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'logintoken': login_token}}
}
elif 'username' in kwargs:
assert kwargs['logintoken'] == login_token
assert kwargs.get('loginreturnurl')
return {
'clientlogin': {'status': 'PASS'}
}
raw_api.side_effect = api_side_effect
site = mwclient.Site('test.wikipedia.org')
# this would be done by site_init usually, but we're mocking it
site.version = (1, 28, 0)
success = site.clientlogin(username='myusername', password='mypassword')
url = f'{site.scheme}://{site.host}'
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
call_args = raw_api.call_args_list
assert success is True
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='login')
assert call_args[1] == mock.call(
'clientlogin', 'POST',
username='myusername',
password='mypassword',
loginreturnurl=url,
logintoken=login_token
)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_clientlogin_fail(self, raw_api, site_init):
login_token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'logintoken': login_token}}
}
elif 'username' in kwargs:
assert kwargs['logintoken'] == login_token
assert kwargs.get('loginreturnurl')
return {
'clientlogin': {'status': 'FAIL'}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
# this would be done by site_init usually, but we're mocking it
site.version = (1, 28, 0)
with pytest.raises(mwclient.errors.LoginError):
success = site.clientlogin(username='myusername', password='mypassword')
call_args = raw_api.call_args_list
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='login')
assert call_args[1] == mock.call(
'clientlogin', 'POST',
username='myusername',
password='mypassword',
loginreturnurl=f'{site.scheme}://{site.host}',
logintoken=login_token
)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_clientlogin_continue(self, raw_api, site_init):
login_token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'logintoken': login_token}}
}
elif 'username' in kwargs:
assert kwargs['logintoken'] == login_token
assert kwargs.get('loginreturnurl')
return {
'clientlogin': {'status': 'UI'}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
# this would be done by site_init usually, but we're mocking it
site.version = (1, 28, 0)
success = site.clientlogin(username='myusername', password='mypassword')
url = f'{site.scheme}://{site.host}'
call_args = raw_api.call_args_list
assert success == {'status': 'UI'}
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='login')
assert call_args[1] == mock.call(
'clientlogin', 'POST',
username='myusername',
password='mypassword',
loginreturnurl=url,
logintoken=login_token
)
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
class TestClientApiMethods(TestCase):
def setUp(self):
self.api = mock.patch('mwclient.client.Site.api').start()
self.api.return_value = self.metaResponse()
self.site = mwclient.Site('test.wikipedia.org')
def tearDown(self):
mock.patch.stopall()
def test_revisions(self):
self.api.return_value = {
'query': {'pages': {'1': {
'pageid': 1,
'title': 'Test page',
'revisions': [{
'revid': 689697696,
'timestamp': '2015-11-08T21:52:46Z',
'comment': 'Test comment 1'
}, {
'revid': 689816909,
'timestamp': '2015-11-09T16:09:28Z',
'comment': 'Test comment 2'
}]
}}}}
revisions = [rev for rev in self.site.revisions([689697696, 689816909], prop='content')]
args, kwargs = self.api.call_args
assert kwargs.get('revids') == '689697696|689816909'
assert len(revisions) == 2
assert revisions[0]['pageid'] == 1
assert revisions[0]['pagetitle'] == 'Test page'
assert revisions[0]['revid'] == 689697696
assert revisions[0]['timestamp'] == time.strptime('2015-11-08T21:52:46Z', '%Y-%m-%dT%H:%M:%SZ')
assert revisions[1]['revid'] == 689816909
class TestVersionTupleFromGenerator:
@pytest.mark.parametrize('version, expected', [
('MediaWiki 1.24', (1, 24)),
('MediaWiki 1.24.0', (1, 24, 0)),
('MediaWiki 1.24.0-wmf.1', (1, 24, 0, 'wmf', 1)),
('MediaWiki 1.24.1alpha', (1, 24, 1, 'alpha')),
('MediaWiki 1.24.1alpha1', (1, 24, 1, 'alpha', 1)),
('MediaWiki 1.24.1-rc.3', (1, 24, 1, 'rc', 3)),
])
def test_version_tuple_from_generator(self, version, expected):
assert mwclient.Site.version_tuple_from_generator(version) == expected
def test_version_tuple_from_generator_empty(self):
with pytest.raises(mwclient.errors.MediaWikiVersionError):
mwclient.Site.version_tuple_from_generator('')
def test_version_tuple_from_generator_invalid_prefix(self):
with pytest.raises(mwclient.errors.MediaWikiVersionError):
mwclient.Site.version_tuple_from_generator('Foo 1.24.1')
def test_version_tuple_from_generator_no_minor(self):
with pytest.raises(mwclient.errors.MediaWikiVersionError):
mwclient.Site.version_tuple_from_generator('MediaWiki 1')
def test_version_tuple_from_generator_major_is_not_number(self):
with pytest.raises(mwclient.errors.MediaWikiVersionError):
mwclient.Site.version_tuple_from_generator('MediaWiki foo.24.1')
def test_version_tuple_from_generator_minor_is_not_number(self):
with pytest.raises(mwclient.errors.MediaWikiVersionError):
mwclient.Site.version_tuple_from_generator('MediaWiki 1.foo.1')
def test_version_tuple_from_generator_major_and_minor_are_not_numbers(self):
with pytest.raises(mwclient.errors.MediaWikiVersionError):
mwclient.Site.version_tuple_from_generator('MediaWiki foo.bar.1')
def test_version_tuple_from_generator_patch_is_not_number(self):
assert mwclient.Site.version_tuple_from_generator('MediaWiki 1.24.foo') == (1, 24, 'foo')
class TestClientUploadArgs(TestCase):
def setUp(self):
self.raw_call = mock.patch('mwclient.client.Site.raw_call').start()
def configure(self, rights=['read', 'upload']):
self.raw_call.side_effect = [self.metaResponseAsJson(rights=rights)]
self.site = mwclient.Site('test.wikipedia.org')
self.vars = {
'fname': 'Some "ßeta" æøå.jpg',
'comment': 'Some slightly complex comment<br> π ≈ 3, © Me.jpg',
'token': 'abc+\\'
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
}
self.raw_call.side_effect = [
# 1st response:
self.makePageResponse(title='File:Test.jpg', imagerepository='local', imageinfo=[{
"comment": "",
"height": 1440,
"metadata": [],
"sha1": "69a764a9cf8307ea4130831a0aa0b9b7f9585726",
"size": 123,
"timestamp": "2013-12-22T07:11:07Z",
"user": "TestUser",
"width": 2160
}]),
# 2nd response:
json.dumps({'query': {'tokens': {'csrftoken': self.vars['token']}}}),
# 3rd response:
json.dumps({
"upload": {
"result": "Success",
"filename": self.vars['fname'],
"imageinfo": []
}
})
]
def tearDown(self):
mock.patch.stopall()
def test_upload_args(self):
# Test that methods are called, and arguments sent as expected
self.configure()
self.site.upload(file=BytesIO(b'test'), filename=self.vars['fname'], comment=self.vars['comment'])
args, kwargs = self.raw_call.call_args
data = args[1]
files = args[2]
assert data.get('action') == 'upload'
assert data.get('filename') == self.vars['fname']
assert data.get('comment') == self.vars['comment']
assert data.get('token') == self.vars['token']
assert 'file' in files
def test_upload_missing_filename(self):
self.configure()
with pytest.raises(TypeError):
self.site.upload(file=BytesIO(b'test'))
def test_upload_ambigitious_args(self):
self.configure()
with pytest.raises(TypeError):
self.site.upload(filename='Test', file=BytesIO(b'test'), filekey='abc')
def test_upload_missing_upload_permission(self):
self.configure(rights=['read'])
with pytest.raises(mwclient.errors.InsufficientPermission):
self.site.upload(filename='Test', file=BytesIO(b'test'))
def test_upload_file_exists(self):
self.configure()
self.raw_call.side_effect = [
self.makePageResponse(title='File:Test.jpg', imagerepository='local',
imageinfo=[{
"comment": "",
"height": 1440,
"metadata": [],
"sha1": "69a764a9cf8307ea4130831a0aa0b9b7f9585726",
"size": 123,
"timestamp": "2013-12-22T07:11:07Z",
"user": "TestUser",
"width": 2160
}]),
json.dumps({'query': {'tokens': {'csrftoken': self.vars['token']}}}),
json.dumps({
'upload': {'result': 'Warning',
'warnings': {'duplicate': ['Test.jpg'],
'exists': 'Test.jpg'},
'filekey': '1apyzwruya84.da2cdk.1.jpg',
'sessionkey': '1apyzwruya84.da2cdk.1.jpg'}
})
]
with pytest.raises(mwclient.errors.FileExists):
self.site.upload(file=BytesIO(b'test'), filename='Test.jpg', ignore=False)
class TestClientGetTokens(TestCase):
def setUp(self):
self.raw_call = mock.patch('mwclient.client.Site.raw_call').start()
def configure(self, version='1.24'):
self.raw_call.return_value = self.metaResponseAsJson(version=version)
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
self.site = mwclient.Site('test.wikipedia.org')
responses.reset()
def tearDown(self):
mock.patch.stopall()
def test_token_new_system(self):
# Test get_token for MW >= 1.24
self.configure(version='1.24')
self.raw_call.return_value = json.dumps({
'query': {'tokens': {'csrftoken': 'sometoken'}}
})
self.site.get_token('edit')
args, kwargs = self.raw_call.call_args
data = args[1]
assert 'intoken' not in data
assert data.get('type') == 'csrf'
assert 'csrf' in self.site.tokens
assert self.site.tokens['csrf'] == 'sometoken'
assert 'edit' not in self.site.tokens
def test_token_old_system_without_specifying_title(self):
# Test get_token for MW < 1.24
self.configure(version='1.23')
self.raw_call.return_value = self.makePageResponse(edittoken='sometoken', title='Test')
self.site.get_token('edit')
args, kwargs = self.raw_call.call_args
data = args[1]
assert 'type' not in data
assert data.get('intoken') == 'edit'
assert 'edit' in self.site.tokens
assert self.site.tokens['edit'] == 'sometoken'
assert 'csrf' not in self.site.tokens
def test_token_old_system_with_specifying_title(self):
# Test get_token for MW < 1.24
self.configure(version='1.23')
self.raw_call.return_value = self.makePageResponse(edittoken='sometoken', title='Some page')
self.site.get_token('edit', title='Some page')
args, kwargs = self.raw_call.call_args
data = args[1]
assert self.site.tokens['edit'] == 'sometoken'
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
class TestClientPatrol(TestCase):
def setUp(self):
self.raw_call = mock.patch('mwclient.client.Site.raw_call').start()
def configure(self, version='1.24'):
self.raw_call.return_value = self.metaResponseAsJson(version=version)
self.site = mwclient.Site('test.wikipedia.org')
def tearDown(self):
mock.patch.stopall()
@mock.patch('mwclient.client.Site.get_token')
def test_patrol(self, get_token):
self.configure('1.24')
get_token.return_value = 'sometoken'
patrol_response = {"patrol": {"rcid": 12345, "ns": 0, "title": "Foo"}}
self.raw_call.return_value = json.dumps(patrol_response)
resp = self.site.patrol(12345)
assert resp == patrol_response["patrol"]
get_token.assert_called_once_with('patrol')
@mock.patch('mwclient.client.Site.get_token')
def test_patrol_on_mediawiki_below_1_17(self, get_token):
self.configure('1.16')
get_token.return_value = 'sometoken'
patrol_response = {"patrol": {"rcid": 12345, "ns": 0, "title": "Foo"}}
self.raw_call.return_value = json.dumps(patrol_response)
resp = self.site.patrol(12345)
assert resp == patrol_response["patrol"]
get_token.assert_called_once_with('edit')
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
class TestUser(TestCase):
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_create_user(self, raw_api, site_init):
createaccount_token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'createaccounttoken': createaccount_token}}
}
elif 'username' in kwargs:
assert kwargs['createtoken'] == createaccount_token
assert kwargs['retype'] == kwargs['password']
assert kwargs.get('createreturnurl')
return {
'createaccount': {'status': 'PASS'}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
password = 'password'
url = '%s://%s' % (site.scheme, site.host)
site.create_user(username='myusername', password=password)
call_args = raw_api.call_args_list
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET',
meta='tokens', type='createaccount')
assert call_args[1] == mock.call('createaccount', 'POST',
username='myusername', password=password,
retype=password, createreturnurl=url,
createtoken=createaccount_token)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_create_user_fail_badretype(self, raw_api, site_init):
createaccount_token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'createaccounttoken': createaccount_token}}
}
elif 'username' in kwargs:
assert kwargs['createtoken'] == createaccount_token
assert kwargs['retype'] != kwargs['password']
assert kwargs.get('createreturnurl')
return {
'createaccount': {'status': 'FAIL',
'messagecode': 'badretype',
'message': 'oups'}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
password = 'password'
url = '%s://%s' % (site.scheme, site.host)
with pytest.raises(mwclient.errors.UserCreateError):
site.create_user(username='myusername', password=password, retype=password[::-1])
call_args = raw_api.call_args_list
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET',
meta='tokens', type='createaccount')
assert call_args[1] == mock.call('createaccount', 'POST',
username='myusername', password=password,
retype=password[::-1], createreturnurl=url,
createtoken=createaccount_token)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_get_user(self, raw_api, site_init):
def side_effect(*args, **kwargs):
if kwargs.get('list') == 'users':
return {
'query': {
'users': [{
'userid': 1,
'user': 'myusername',
'groups': ['*', 'user']
}]
}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
site.get_user(username='myusername')
call_kwargs = {
'ususers': 'myusername',
'list': 'users',
'continue': '',
'meta': 'userinfo',
'uiprop': 'blockinfo|hasmsg',
'usprop': 'registration|groups|blockinfo'
}
call_args = raw_api.call_args_list
assert len(call_args) == 1
assert call_args[0] == mock.call('query', 'GET', **call_kwargs)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_get_user_fail_notfound(self, raw_api, site_init):
def side_effect(*args, **kwargs):
if kwargs.get('list') == 'users':
ret = {
'query': {
'users': [{
'missing': ''
}]
}
}
if 'ususers' in kwargs:
ret['query']['users'][0]['user'] = kwargs['ususers']
elif 'ususerids' in kwargs:
ret['query']['users'][0]['userid'] = kwargs['ususerids']
return ret
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
with pytest.raises(mwclient.errors.UserNotFound):
site.get_user(username='notfounduser')
with pytest.raises(mwclient.errors.UserNotFound):
site.get_user(userid=42)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_get_user_fail_params(self, raw_api, site_init):
site = mwclient.Site('test.wikipedia.org')
with pytest.raises(ValueError):
site.get_user(username=None, userid=None)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_block_user(self, raw_api, site_init):
csrf_token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'csrftoken': csrf_token}}
}
else:
return {
'block': {
'user': 'myusername',
'userID': 1,
'expiry': 'infinite',
'id': 1,
'reason': kwargs['reason']
}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
site.block_user(username='myusername', reason='Test',
tags=['knock', 'knock'])
call_args = raw_api.call_args_list
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='csrf')
assert call_args[1] == mock.call('block', 'POST',
user='myusername', reason='Test',
tags='knock|knock', token=csrf_token)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_unblock_user(self, raw_api, site_init):
csrf_token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'csrftoken': csrf_token}}
}
else:
return {
'id': 1,
'user': 'myusername',
'userID': 1,
'reason': kwargs['reason']
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
site.unblock_user(username='myusername', reason='Test')
call_args = raw_api.call_args_list
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='csrf')
assert call_args[1] == mock.call('unblock', 'POST',
user='myusername', reason='Test',
token=csrf_token)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_block_user_fail_params(self, raw_api, site_init):
site = mwclient.Site('test.wikipedia.org')
with pytest.raises(ValueError):
site.block_user(reason='Test', tags=['knock', 'knock'])
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_block_user_fail_unkown(self, raw_api, site_init):
csrf_token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'csrftoken': csrf_token}}
}
else:
return {
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
with pytest.raises(mwclient.errors.APIError):
site.block_user(userid=42, reason='Test',
tags=['knock', 'knock'])
call_args = raw_api.call_args_list
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='csrf')
assert call_args[1] == mock.call('block', 'POST',
userid=42, reason='Test',
tags='knock|knock', token=csrf_token)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_get_user_groups(self, raw_api, site_init):
def side_effect(*args, **kwargs):
if kwargs.get('list') == 'users':
return {
'query': {
'users': [{
'userid': 1,
'user': 'myusername',
'groups': ['*', 'user']
}]
}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
groups = site.get_user_groups(username='myusername')
call_kwargs = {
'ususers': 'myusername',
'list': 'users',
'continue': '',
'meta': 'userinfo',
'uiprop': 'blockinfo|hasmsg',
'usprop': 'groups'
}
call_args = raw_api.call_args_list
assert len(call_args) == 1
assert call_args[0] == mock.call('query', 'GET', **call_kwargs)
assert groups == ['*', 'user']
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_get_user_groups_fail_params(self, raw_api, site_init):
site = mwclient.Site('test.wikipedia.org')
with pytest.raises(ValueError):
site.get_user_groups(username=None)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_get_user_groups_fail_notfound(self, raw_api, site_init):
def side_effect(*args, **kwargs):
if kwargs.get('list') == 'users':
return {
'query': {
'users': [{
'userid': 42,
'missing': ''
}]
}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
with pytest.raises(mwclient.errors.UserNotFound):
site.get_user_groups(userid=42)
call_kwargs = {
'ususerids': 42,
'list': 'users',
'continue': '',
'meta': 'userinfo',
'uiprop': 'blockinfo|hasmsg',
'usprop': 'groups'
}
call_args = raw_api.call_args_list
assert len(call_args) == 1
assert call_args[0] == mock.call('query', 'GET', **call_kwargs)
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_add_user_groups(self, raw_api, site_init):
token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'userrightstoken': token}}
}
else:
return {
'userrights': {
'userid': 42,
'user': 'myusername',
'added': ['*', 'user', 'bureaucrat', 'sysop'],
'removed': []
}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
added = site.add_user_groups(username='myusername',
groups=['*', 'user', 'bureaucrat', 'sysop'])
mock_call = mock.call('userrights', 'POST', **{
'user': 'myusername',
'add': '*|user|bureaucrat|sysop',
'token': token,
})
call_args = raw_api.call_args_list
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='userrights')
mock_call_kwargs = deepcopy(mock_call[2])
real_call_kwargs = deepcopy(call_args[1][1])
assert 'add' in real_call_kwargs
assert 'add' in mock_call_kwargs
add_kwargs = set(real_call_kwargs.pop('add').split('|'))
assert add_kwargs == set(mock_call_kwargs.pop('add').split('|'))
assert 'remove' not in real_call_kwargs
assert 'remove' not in mock_call_kwargs
if sys.version_info >= (3,8,0):
assert real_call_kwargs == mock_call_kwargs
assert mock_call.args == call_args[1].args
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
assert added == ['*', 'user', 'bureaucrat', 'sysop']
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_add_user_groups_expirty_formats(self, raw_api, site_init):
token = 'abc+\\'
today = date.today()
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'userrightstoken': token}}
}
else:
return {
'userrights': {
'userid': 42,
'user': 'myusername',
'added': ['*', 'user', 'bureaucrat', 'sysop'],
'removed': []
}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
call_kwargs = {
'username': 'myusername',
'groups': ['*', 'user', 'bureaucrat', 'sysop'],
}
mock_call_kwargs = {
'user': 'myusername',
'add': '*|user|bureaucrat|sysop',
'token': token,
}
expirty_formats = (
(['2042-01-01', '2042-01-02'], '2042-01-01|2042-01-02'),
('2042-01-01', '2042-01-01'),
(today, '%s' % today),
)
for call_fmt_expiry, mock_call_expiry in expirty_formats:
call_kwargs['expiry'] = call_fmt_expiry
mock_call_kwargs['expiry'] = mock_call_expiry
added = site.add_user_groups(**call_kwargs)
assert added == ['*', 'user', 'bureaucrat', 'sysop']
real_mock_call_kwargs = mock.call('userrights', 'POST', **mock_call_kwargs)[2]
real_call_kwargs = raw_api.call_args_list[-1][1]
assert real_mock_call_kwargs['expiry'] == real_call_kwargs['expiry']
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_add_user_groups_fail_notfound(self, raw_api, site_init):
token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'userrightstoken': token}}
}
else:
raise mwclient.errors.APIError('nosuchuser', 'Blah', kwargs)
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
with pytest.raises(mwclient.errors.UserNotFound):
site.add_user_groups(username='notfound',
groups=['*', 'user', 'bureaucrat', 'sysop'])
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_add_user_groups_fail_params(self, raw_api, site_init):
site = mwclient.Site('test.wikipedia.org')
with pytest.raises(ValueError):
site.add_user_groups(username=None,
groups=['*', 'user', 'bureaucrat', 'sysop'])
assert [] == site.add_user_groups(userid=42, groups=[])
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_remove_user_groups(self, raw_api, site_init):
token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'userrightstoken': token}}
}
else:
return {
'userrights': {
'userid': 42,
'user': 'myusername',
'removed': ['bureaucrat', 'sysop'],
'added': []
}
}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
removed = site.remove_user_groups(username='myusername',
groups=['bureaucrat', 'sysop'],
reason='Test')
mock_call = mock.call('userrights', 'POST', **{
'user': 'myusername',
'remove': 'bureaucrat|sysop',
'token': token,
'reason': 'Test',
})
call_args = raw_api.call_args_list
assert len(call_args) == 2
assert call_args[0] == mock.call('query', 'GET', meta='tokens', type='userrights')
mock_call_kwargs = deepcopy(mock_call[2])
real_call_kwargs = deepcopy(call_args[1][1])
assert 'remove' in real_call_kwargs
assert 'remove' in mock_call_kwargs
remove_kwargs = set(real_call_kwargs.pop('remove').split('|'))
assert remove_kwargs == set(mock_call_kwargs.pop('remove').split('|'))
assert 'add' not in real_call_kwargs
assert 'add' not in mock_call_kwargs
if sys.version_info >= (3,8,0):
assert real_call_kwargs == mock_call_kwargs
assert mock_call.args == call_args[1].args
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
assert removed == ['bureaucrat', 'sysop']
@mock.patch('mwclient.client.Site.site_init')
@mock.patch('mwclient.client.Site.raw_api')
def test_set_user_groups(self, raw_api, site_init):
token = 'abc+\\'
def side_effect(*args, **kwargs):
if kwargs.get('meta') == 'tokens':
return {
'query': {'tokens': {'userrightstoken': token}}
}
elif kwargs.get('list') == 'users':
return {
'query': {
'users': [{
'userid': 42,
'user': 'myusername',
'groups': ['*', 'user', 'bot', 'interface-admin']
}]
}
}
else:
return {}
raw_api.side_effect = side_effect
site = mwclient.Site('test.wikipedia.org')
site.set_user_groups(userid=42,
tags=['one', 'two'],
reason='Test',
groups=['*', 'user', 'bureaucrat', 'sysop'])
get_groups_call_kwargs = {
'ususerids': 42,
'list': 'users',
'continue': '',
'meta': 'userinfo',
'uiprop': 'blockinfo|hasmsg',
'usprop': 'groups'
}
set_groups_call_kwargs = {
'userid': 42,
'remove': 'bot|interface-admin',
'add': 'bureaucrat|sysop',
'reason': 'Test',
'tags': 'one|two',
'token': token,
}
call_args = raw_api.call_args_list
assert len(call_args) == 3
assert call_args[0] == mock.call('query', 'GET', **get_groups_call_kwargs)
assert call_args[1] == mock.call('query', 'GET', meta='tokens', type='userrights')
mock_call = mock.call('userrights', 'POST', **set_groups_call_kwargs)
mock_call_kwargs = deepcopy(mock_call[2])
real_call_kwargs = deepcopy(call_args[2][1])
assert 'add' in real_call_kwargs
assert 'add' in mock_call_kwargs
add_kwargs = set(real_call_kwargs.pop('add').split('|'))
assert add_kwargs == set(mock_call_kwargs.pop('add').split('|'))
assert 'remove' in real_call_kwargs
assert 'remove' in mock_call_kwargs
remove_kwargs = set(real_call_kwargs.pop('remove').split('|'))
assert remove_kwargs == set(mock_call_kwargs.pop('remove').split('|'))
if sys.version_info >= (3,8,0):
assert real_call_kwargs == mock_call_kwargs
assert mock_call.args == call_args[2].args
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
class TestClientExpandtemplates(TestCase):
def setUp(self):
self.raw_call = mock.patch('mwclient.client.Site.raw_call').start()
def configure(self, version='1.24'):
self.raw_call.return_value = self.metaResponseAsJson(version=version)
self.site = mwclient.Site('test.wikipedia.org')
def tearDown(self):
mock.patch.stopall()
def test_expandtemplates_1_13(self):
self.configure('1.16')
self.raw_call.return_value = json.dumps({
'expandtemplates': {
'*': '2024'
}
})
wikitext = self.site.expandtemplates('{{CURRENTYEAR}}')
assert wikitext == '2024'
def test_expandtemplates_1_13_generatexml(self):
self.configure('1.16')
self.raw_call.return_value = json.dumps({
'parsetree': {
'*': '<root><template><title>CURRENTYEAR</title></template></root>'
},
'expandtemplates': {
'*': '2024'
}
})
expanded = self.site.expandtemplates('{{CURRENTYEAR}}', generatexml=True)
assert isinstance(expanded, tuple)
assert expanded[0] == '2024'
assert expanded[1] == '<root><template><title>CURRENTYEAR</title></template></root>'
def test_expandtemplates_1_24(self):
self.configure('1.24')
self.raw_call.return_value = json.dumps({
'expandtemplates': {
'wikitext': '2024'
}
})
wikitext = self.site.expandtemplates('{{CURRENTYEAR}}')
assert wikitext == '2024'
def test_expandtemplates_1_24_generatexml(self):
self.configure('1.24')
self.raw_call.return_value = json.dumps({
'expandtemplates': {
'parsetree': '<root><template><title>CURRENTYEAR</title></template></root>',
'wikitext': '2024'
}
})
expanded = self.site.expandtemplates('{{CURRENTYEAR}}', generatexml=True)
assert isinstance(expanded, tuple)
assert expanded[0] == '2024'
assert expanded[1] == '<root><template><title>CURRENTYEAR</title></template></root>'
if __name__ == '__main__':
unittest.main()