forked from wikimedia/pywikibot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpagegenerators_tests.py
executable file
·1765 lines (1490 loc) · 66.9 KB
/
pagegenerators_tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
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
403
404
405
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
445
446
447
448
449
450
451
452
453
454
455
456
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
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
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
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Test pagegenerators module."""
#
# (C) Pywikibot team, 2009-2023
#
# Distributed under the terms of the MIT license.
import calendar
import datetime
import logging
import sys
import unittest
from contextlib import suppress
from typing import Optional
from unittest import mock
import pywikibot
from pywikibot import date, pagegenerators
from pywikibot.exceptions import (
APIError,
NoPageError,
ServerError,
UnknownExtensionError,
)
from pywikibot.pagegenerators import (
CategorizedPageGenerator,
PagesFromTitlesGenerator,
PreloadingGenerator,
WikibaseItemFilterPageGenerator,
)
from pywikibot.tools import has_module
from tests import join_data_path
from tests.aspects import (
DefaultSiteTestCase,
DeprecationTestCase,
RecentChangesTestCase,
TestCase,
WikidataTestCase,
)
from tests.tools_tests import GeneratorIntersectTestCase
from tests.utils import skipping
en_wp_page_titles = (
# just a bunch of randomly selected titles for English Wikipedia tests
'Eastern Sayan',
'The Addams Family (pinball)',
'Talk:Nowy Sącz',
'Talk:Battle of Węgierska Górka',
'Template:!',
'Template:Template',
)
en_wp_nopage_titles = (
'Cities in Burkina Faso',
'Talk:Hispanic (U.S. Census)',
'Talk:Stołpce',
'Template:!/Doc',
'Template:!/Meta',
'Template:Template/Doc',
'Template:Template/Meta',
)
class TestDryPageGenerators(TestCase):
"""Test pagegenerators methods."""
family = 'wikipedia'
code = 'en'
dry = True
titles = en_wp_page_titles + en_wp_nopage_titles
def setUp(self):
"""Setup test."""
super().setUp()
self.site = self.get_site()
def assertFunction(self, obj):
"""Assert function test."""
self.assertTrue(hasattr(pagegenerators, obj))
self.assertTrue(callable(getattr(pagegenerators, obj)))
def test_module_import(self):
"""Test module import."""
self.assertIn('pywikibot.pagegenerators', sys.modules)
def test_PagesFromTitlesGenerator(self):
"""Test PagesFromTitlesGenerator."""
self.assertFunction('PagesFromTitlesGenerator')
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, self.site)
self.assertPageTitlesEqual(gen, self.titles)
def test_NamespaceFilterPageGenerator(self):
"""Test NamespaceFilterPageGenerator."""
self.assertFunction('NamespaceFilterPageGenerator')
site = self.site
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, site)
gen = pagegenerators.NamespaceFilterPageGenerator(gen, 0, site)
self.assertLength(tuple(gen), 3)
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, site)
gen = pagegenerators.NamespaceFilterPageGenerator(gen, 1, site)
self.assertLength(tuple(gen), 4)
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, site)
gen = pagegenerators.NamespaceFilterPageGenerator(gen, 10, site)
self.assertLength(tuple(gen), 6)
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, site)
gen = pagegenerators.NamespaceFilterPageGenerator(gen, (1, 10), site)
self.assertLength(tuple(gen), 10)
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, site)
gen = pagegenerators.NamespaceFilterPageGenerator(
gen, ('Talk', 'Template'), site)
self.assertLength(tuple(gen), 10)
def test_RegexFilterPageGenerator(self):
"""Test RegexFilterPageGenerator."""
self.assertFunction('RegexFilterPageGenerator')
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, self.site)
gen = pagegenerators.RegexFilterPageGenerator(gen, '/doc')
self.assertPageTitlesEqual(gen,
('Template:!/Doc', 'Template:Template/Doc'))
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, self.site)
gen = pagegenerators.RegexFilterPageGenerator(gen, '/doc',
quantifier='none')
self.assertLength(tuple(gen), 11)
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, self.site)
gen = pagegenerators.RegexFilterPageGenerator(gen, ['/doc', '/meta'])
self.assertPageTitlesEqual(gen,
('Template:!/Doc',
'Template:!/Meta',
'Template:Template/Doc',
'Template:Template/Meta'))
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, self.site)
gen = pagegenerators.RegexFilterPageGenerator(gen, ['/doc', '/meta'],
quantifier='none')
self.assertLength(tuple(gen), 9)
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, self.site)
gen = pagegenerators.RegexFilterPageGenerator(gen, ['/doc', '/meta'],
quantifier='all')
self.assertPageTitlesEqual(gen, [])
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, self.site)
gen = pagegenerators.RegexFilterPageGenerator(
gen, ['Template', '/meta'], quantifier='all')
self.assertPageTitlesEqual(gen, ('Template:Template/Meta', ))
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, self.site)
gen = pagegenerators.RegexFilterPageGenerator(
gen, ['template', '/meta'], quantifier='any')
self.assertPageTitlesEqual(gen,
('Template:Template',
'Template:!/Meta',
'Template:Template/Doc',
'Template:Template/Meta'))
gen = pagegenerators.PagesFromTitlesGenerator(self.titles,
site=self.site)
gen = pagegenerators.RegexFilterPageGenerator(
gen, ['template', '/meta'], quantifier='any',
ignore_namespace=False)
self.assertLength(tuple(gen), 6)
gen = pagegenerators.PagesFromTitlesGenerator(self.titles,
site=self.site)
gen = pagegenerators.RegexFilterPageGenerator(
gen, ['template', '/meta'], quantifier='all',
ignore_namespace=False)
self.assertPageTitlesEqual(gen,
('Template:!/Meta',
'Template:Template/Meta'))
gen = pagegenerators.PagesFromTitlesGenerator(self.titles,
site=self.site)
gen = pagegenerators.RegexFilterPageGenerator(
gen, ['template', '/meta'], quantifier='none',
ignore_namespace=False)
self.assertLength(tuple(gen), 7)
def test_RegexBodyFilterPageGenerator(self):
"""Test RegexBodyFilterPageGenerator."""
self.assertFunction('RegexBodyFilterPageGenerator')
gen = pagegenerators.PagesFromTitlesGenerator(self.titles,
site=self.site)
pages = []
for p in gen:
p.text = f'This is the content of {p.title()} as a sample'
pages.append(p)
gen = pagegenerators.RegexBodyFilterPageGenerator(iter(pages), '/doc')
self.assertPageTitlesEqual(gen,
('Template:!/Doc', 'Template:Template/Doc'))
gen = pagegenerators.RegexBodyFilterPageGenerator(iter(pages), 'This')
self.assertPageTitlesEqual(gen, self.titles)
gen = pagegenerators.RegexBodyFilterPageGenerator(iter(pages), 'talk',
quantifier='none')
self.assertLength(tuple(gen), 9)
class BasetitleTestCase(TestCase):
"""Class providing base_title attribute."""
family = 'wikisource'
code = 'en'
base_title = ('Page:06-24-1920 -The Story of the Jones County '
'Calf Case.pdf/{}')
def setUp(self):
"""Setup tests."""
super().setUp()
self.site = self.get_site()
self.titles = [self.base_title.format(i) for i in range(1, 11)]
class TestPagesFromPageidGenerator(BasetitleTestCase):
"""Test PagesFromPageidGenerator method."""
def test_PagesFromPageidGenerator(self):
"""Test PagesFromPageidGenerator."""
gen_pages = pagegenerators.PagesFromTitlesGenerator(self.titles,
self.site)
pageids = (page.pageid for page in gen_pages)
gen = pagegenerators.PagesFromPageidGenerator(pageids, self.site)
self.assertPageTitlesEqual(gen, self.titles)
class TestCategoryFilterPageGenerator(BasetitleTestCase):
"""Test CategoryFilterPageGenerator method."""
category_list = ['Category:Validated']
def setUp(self):
"""Setup tests."""
super().setUp()
self.catfilter_list = [pywikibot.Category(self.site, cat)
for cat in self.category_list]
def test_CategoryFilterPageGenerator(self):
"""Test CategoryFilterPageGenerator."""
site = self.site
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, site)
gen = pagegenerators.CategoryFilterPageGenerator(
gen, self.catfilter_list)
self.assertLength(tuple(gen), 10)
class TestQualityFilterPageGenerator(BasetitleTestCase):
"""Test QualityFilterPageGenerator methods."""
cached = True
base_title = 'Page:Popular Science Monthly Volume 1.djvu/{}'
def test_QualityFilterPageGenerator(self):
"""Test QualityFilterPageGenerator."""
site = self.site
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, site)
gen = pagegenerators.QualityFilterPageGenerator(gen, [0, 3])
self.assertLength(tuple(gen), 7)
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, site)
gen = pagegenerators.QualityFilterPageGenerator(gen, [4])
self.assertLength(tuple(gen), 3)
gen = pagegenerators.PagesFromTitlesGenerator(self.titles, site)
self.assertLength(tuple(gen), 10)
class EdittimeFilterPageGeneratorTestCase(TestCase):
"""Test EdittimeFilterPageGenerator."""
family = 'wikipedia'
code = 'en'
titles = en_wp_page_titles
def test_first_edit(self):
"""Test first edit."""
expect = (
'The Addams Family (pinball)',
'Talk:Nowy Sącz',
'Template:Template',
)
gen = PagesFromTitlesGenerator(self.titles, self.site)
gen = pagegenerators.EdittimeFilterPageGenerator(
gen, first_edit_end=datetime.datetime(2006, 1, 1))
self.assertPageTitlesEqual(gen, titles=expect, site=self.site)
gen = PagesFromTitlesGenerator(self.titles, self.site)
opposite_pages = pagegenerators.EdittimeFilterPageGenerator(
gen, first_edit_start=datetime.datetime(2006, 1, 1))
for p in opposite_pages:
self.assertIsInstance(p, pywikibot.Page)
self.assertNotIn(p.title(), expect)
def test_last_edit(self):
"""Test last edit."""
two_days_ago = datetime.datetime.now() - datetime.timedelta(days=2)
nine_days_ago = datetime.datetime.now() - datetime.timedelta(days=9)
gen = PagesFromTitlesGenerator(['Wikipedia:Sandbox'], self.site)
gen = pagegenerators.EdittimeFilterPageGenerator(
gen, last_edit_start=two_days_ago)
self.assertLength(list(gen), 1)
gen = PagesFromTitlesGenerator(['Wikipedia:Sandbox'], self.site)
gen = pagegenerators.EdittimeFilterPageGenerator(
gen, last_edit_end=two_days_ago)
self.assertIsEmpty(list(gen))
gen = PagesFromTitlesGenerator(['Template:Side box'], self.site)
gen = pagegenerators.EdittimeFilterPageGenerator(
gen, last_edit_end=nine_days_ago)
self.assertLength(list(gen), 1)
gen = PagesFromTitlesGenerator(['Template:Side box'], self.site)
gen = pagegenerators.EdittimeFilterPageGenerator(
gen, last_edit_start=nine_days_ago)
self.assertIsEmpty(list(gen))
class RedirectFilterPageGeneratorTestCase(TestCase):
"""Test RedirectFilterPageGenerator."""
family = 'wikipedia'
code = 'en'
def test_redirect_filter(self):
"""Test RedirectFilterPageGenerator with handle_args()."""
from pywikibot.pagegenerators import RedirectFilterPageGenerator
gf = pagegenerators.GeneratorFactory(site=self.site)
args = gf.handle_args(['-randomredirect:3', '-page:Main_Page'])
self.assertIsEmpty(args)
gen = gf.getCombinedGenerator()
pages = list(gen)
gen = RedirectFilterPageGenerator(pages, no_redirects=True)
self.assertLength(list(gen), 1)
gen = RedirectFilterPageGenerator(pages, no_redirects=False)
self.assertLength(list(gen), 3)
class SubpageFilterGeneratorTestCase(TestCase):
"""Test SubpageFilterGenerator."""
family = 'wikipedia'
code = 'test'
def test_subpage_filter(self):
"""Test SubpageFilterGenerator."""
site = self.get_site()
test_cat = pywikibot.Category(site, 'Subpage testing')
gen = CategorizedPageGenerator(test_cat)
gen = pagegenerators.SubpageFilterGenerator(gen, 0)
expect_0 = ('/home/test',)
self.assertPageTitlesEqual(gen, titles=expect_0, site=site)
gen = CategorizedPageGenerator(test_cat)
gen = pagegenerators.SubpageFilterGenerator(gen, 3)
expect_3 = (
'/home/test',
'User:Sn1per/ProtectTest1/test',
'User:Sn1per/ProtectTest1/test/test',
)
self.assertPageTitlesEqual(gen, titles=expect_3, site=site)
class PetScanPageGeneratorTestCase(TestCase):
"""Test PetScanPageGenerator."""
family = 'wikipedia'
code = 'test'
def test_petscan(self):
"""Test PetScanPageGenerator."""
site = self.get_site()
gen = pagegenerators.PetScanPageGenerator(['Pywikibot Protect Test'],
True, None, site)
with skipping(ServerError,
APIError): # (temporary) disabled due to T352482
self.assertPageTitlesEqual(gen, titles=(
'User:Sn1per/ProtectTest1', 'User:Sn1per/ProtectTest2'),
site=site)
gen = pagegenerators.PetScanPageGenerator(['Pywikibot Protect Test'],
False, None, site)
self.assertPageTitlesEqual(gen, titles=('User:Sn1per/ProtectTest1',
'User:Sn1per/ProtectTest2'),
site=site)
gen = pagegenerators.PetScanPageGenerator(
['Pywikibot PetScan Test',
'Pywikibot Category That Needs&ToBe!Encoded',
'Test'], True, None, site)
self.assertPageTitlesEqual(gen, titles=('User:Sn1per/PetScanTest1', ),
site=site)
class TestRepeatingGenerator(RecentChangesTestCase):
"""Test RepeatingGenerator."""
def test_RepeatingGenerator(self):
"""Test RepeatingGenerator."""
gen = pagegenerators.RepeatingGenerator(
self.site.recentchanges,
key_func=lambda x: x['revid'],
sleep_duration=10,
reverse=True,
namespaces=[0],
total=self.length)
items = list(gen)
self.assertLength(items, self.length)
timestamps = [pywikibot.Timestamp.fromISOformat(item['timestamp'])
for item in items]
self.assertEqual(sorted(timestamps), timestamps)
itemsset = set()
for item in items:
self.assertEqual(item['ns'], 0)
revid = item['revid']
self.assertNotIn(revid, itemsset)
itemsset.add(revid)
class TestTextIOPageGenerator(DefaultSiteTestCase):
"""Test loading pages from a textfile."""
dry = True
title_columns = {
'case-sensitive': 0,
'first-letter': 1,
}
expected_titles = (
('file', 'File'),
('bracket', 'Bracket'),
('MediaWiki:Test', 'MediaWiki:Test'),
('under score', 'Under score'),
('Upper case', 'Upper case'),
)
def test_brackets(self):
"""Test TextIOPageGenerator with brackets."""
filename = join_data_path('pagelist-brackets.txt')
site = self.get_site()
titles = list(pagegenerators.TextIOPageGenerator(filename, site))
self.assertLength(titles, self.expected_titles)
expected_titles = [
expected_title[self.title_columns[site.namespaces[page.namespace()]
.case]]
for expected_title, page in zip(self.expected_titles, titles)]
self.assertPageTitlesEqual(titles, expected_titles)
def test_lines(self):
"""Test TextIOPageGenerator with newlines."""
filename = join_data_path('pagelist-lines.txt')
site = self.get_site()
titles = list(pagegenerators.TextIOPageGenerator(filename, site))
self.assertLength(titles, self.expected_titles)
expected_titles = [
expected_title[self.title_columns[site.namespaces[page.namespace()]
.case]]
for expected_title, page in zip(self.expected_titles, titles)]
self.assertPageTitlesEqual(titles, expected_titles)
@unittest.mock.patch('pywikibot.comms.http.fetch', autospec=True)
def test_url(self, mock_fetch):
"""Test TextIOPageGenerator with URL."""
# Mock return value of fetch()
fetch_return = unittest.mock.Mock()
fetch_return.text = '\n'.join(
[title[0] for title in self.expected_titles])
mock_fetch.return_value = fetch_return
site = self.get_site()
titles = list(
pagegenerators.TextIOPageGenerator('http://www.someurl.org', site))
self.assertLength(titles, self.expected_titles)
class TestYearPageGenerator(DefaultSiteTestCase):
"""Test the year page generator."""
def test_basic(self):
"""Test YearPageGenerator."""
site = self.get_site()
# Some languages are missing (T85681)
if site.lang not in date.formats['YearBC']:
self.skipTest(
'Date formats for {!r} language are missing from date.py'
.format(site.lang))
start = -20
end = 2026
i = 0
for page in pagegenerators.YearPageGenerator(start, end, site):
self.assertIsInstance(page, pywikibot.Page)
self.assertEqual(date.formatYear(site.lang, start + i),
page.title())
self.assertNotEqual(page.title(), '0')
i += 1
if start + i == 0:
i += 1
self.assertEqual(start + i - 1, end)
class TestDayPageGenerator(DefaultSiteTestCase):
"""Test the day page generator."""
def _run_test(self, start_month=1, end_month=12, year=2000):
"""Test method for DayPageGenerator."""
params = {
'start_month': start_month,
'end_month': end_month,
'site': self.site,
}
if year != 2000:
params['year'] = year
# use positional parameter
gen1 = pagegenerators.DayPageGenerator(
start_month, end_month, self.site, year)
# use keyworded parameter and default for year
gen2 = pagegenerators.DayPageGenerator(**params)
for page in gen1:
self.assertIsInstance(page, pywikibot.Page)
self.assertTrue(page.isAutoTitle)
expected = []
for month in range(start_month, end_month + 1):
for day in range(1, calendar.monthrange(year, month)[1] + 1):
expected.append(date.format_date(month, day, self.site))
self.assertPageTitlesEqual(gen2, expected)
def test_basic(self):
"""General test for day page generator."""
self._run_test()
def test_year_2001(self):
"""Test for day page generator of year 2001."""
self._run_test(2, year=2001)
def test_year_2100(self):
"""Test for day page generator of year 2100."""
self._run_test(end_month=2, year=2100)
def test_start_0(self):
"""Test for day page generator with startMonth 0."""
with self.assertRaisesRegex(
calendar.IllegalMonthError,
'bad month number 0; must be 1-12'):
self._run_test(0)
def test_end_13(self):
"""Test for day page generator with endMonth 13."""
with self.assertRaisesRegex(
calendar.IllegalMonthError,
'bad month number 13; must be 1-12'):
self._run_test(12, 13)
class TestPreloadingGenerator(DefaultSiteTestCase):
"""Test preloading generator on lists."""
def test_basic(self):
"""Test PreloadingGenerator with a list of pages."""
mainpage = self.get_mainpage()
links = [page for page in self.site.pagelinks(mainpage, total=20)
if page.exists()]
count = 0
for count, page in enumerate(
PreloadingGenerator(links, groupsize=20), start=1):
self.assertIsInstance(page, pywikibot.Page)
self.assertIsInstance(page.exists(), bool)
self.assertLength(page._revisions, 1)
self.assertIsNotNone(page._revisions[page._revid].text)
self.assertFalse(hasattr(page, '_pageprops'))
self.assertLength(links, count)
def test_low_step(self):
"""Test PreloadingGenerator with a list of pages."""
mainpage = self.get_mainpage()
links = [page for page in self.site.pagelinks(mainpage, total=20)
if page.exists()]
count = 0
for count, page in enumerate(
PreloadingGenerator(links, groupsize=10), start=1):
self.assertIsInstance(page, pywikibot.Page)
self.assertIsInstance(page.exists(), bool)
self.assertLength(page._revisions, 1)
self.assertIsNotNone(page._revisions[page._revid].text)
self.assertFalse(hasattr(page, '_pageprops'))
self.assertLength(links, count)
def test_order(self):
"""Test outcome is following same order of input."""
mainpage = self.get_mainpage()
links = [page for page in self.site.pagelinks(mainpage, total=20)
if page.exists()]
count = -1
for count, page in enumerate(PreloadingGenerator(links, groupsize=10)):
self.assertIsInstance(page, pywikibot.Page)
self.assertIsInstance(page.exists(), bool)
self.assertLength(page._revisions, 1)
self.assertIsNotNone(page._revisions[page._revid].text)
self.assertFalse(hasattr(page, '_pageprops'))
self.assertEqual(page, links[count])
self.assertLength(links, count + 1)
class TestDequePreloadingGenerator(DefaultSiteTestCase):
"""Test preloading generator on lists."""
def test_deque_preloading(self):
"""Test pages being added to a DequePreloadingGenerator."""
mainpage = self.get_mainpage()
pages = pywikibot.tools.collections.DequeGenerator([mainpage])
gen = pagegenerators.DequePreloadingGenerator(pages)
pages_out = []
for page in gen:
pages_out.append(page)
# Add a page to the generator
if not page.isTalkPage():
pages.extend([page.toggleTalkPage()])
self.assertIn(mainpage, pages_out)
self.assertIn(mainpage.toggleTalkPage(), pages_out)
self.assertLength(pages_out, 2)
self.assertTrue(pages_out[1].isTalkPage())
for page in pages_out:
self.assertIsInstance(page, pywikibot.Page)
class TestPreloadingEntityGenerator(WikidataTestCase):
"""Test preloading item generator."""
def test_non_item_gen(self):
"""Test TestPreloadingEntityGenerator with getReferences."""
site = self.get_site()
page = pywikibot.Page(site, 'Property:P31')
ref_gen = page.getReferences(follow_redirects=False, total=5)
gen = pagegenerators.PreloadingEntityGenerator(ref_gen)
for ipage in gen:
self.assertIsInstance(ipage, pywikibot.ItemPage)
class WikibaseItemFilterPageGeneratorTestCase(TestCase):
"""Test WikibaseItemFilterPageGenerator."""
family = 'wikipedia'
code = 'en'
def test_filter_pages_with_item(self):
"""Test WikibaseItemFilterPageGenerator on pages with item."""
gf = pagegenerators.GeneratorFactory(site=self.site)
gf.handle_arg('-page:Main_Page')
gen = gf.getCombinedGenerator()
pages = list(gen)
gen = WikibaseItemFilterPageGenerator(pages, has_item=True)
self.assertLength(list(gen), 1)
gen = WikibaseItemFilterPageGenerator(pages, has_item=False)
self.assertLength(list(gen), 0)
def test_filter_pages_without_item(self):
"""Test WikibaseItemFilterPageGenerator on pages without item."""
gf = pagegenerators.GeneratorFactory(site=self.site)
gf.handle_arg('-page:Talk:Main_Page')
gen = gf.getCombinedGenerator()
pages = list(gen)
gen = WikibaseItemFilterPageGenerator(pages, has_item=True)
self.assertLength(list(gen), 0)
gen = WikibaseItemFilterPageGenerator(pages, has_item=False)
self.assertLength(list(gen), 1)
class DryFactoryGeneratorTest(TestCase):
"""Dry tests for pagegenerators.GeneratorFactory."""
family = 'wikipedia'
code = 'en'
dry = True
def test_one_namespace(self):
"""Test one namespace."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:2')
self.assertEqual(gf.namespaces, {2})
def test_two_namespaces(self):
"""Test two namespaces."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:2')
gf.handle_arg('-ns:Talk')
self.assertEqual(gf.namespaces, {2, 1})
def test_two_named_namespaces(self):
"""Test two named namespaces."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:Talk,File')
self.assertEqual(gf.namespaces, {1, 6})
def test_two_numeric_namespaces(self):
"""Test two namespaces delimited by colon."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:1,6')
self.assertEqual(gf.namespaces, {1, 6})
def test_immutable_namespaces_on_read(self):
"""Test immutable namespaces on read."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:1,6')
self.assertEqual(gf.namespaces, {1, 6})
self.assertIsInstance(gf.namespaces, frozenset)
with self.assertRaises(RuntimeError):
gf.handle_arg('-ns:0')
self.assertEqual(gf.namespaces, {1, 6})
def test_unsupported_quality_level_filter(self):
"""Test unsupported option."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
with self.assertRaises(UnknownExtensionError):
gf.handle_arg('-ql:2')
def test_one_excluded_namespaces(self):
"""Test one excluded namespaces."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:not:2')
ns = set(range(16))
ns.remove(2)
self.assertTrue(ns.issubset(gf.namespaces))
def test_two_excluded_namespaces(self):
"""Test two excluded namespaces."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:not:2')
gf.handle_arg('-ns:not:Talk')
ns = set(range(16))
ns.remove(2)
ns.remove(1)
self.assertTrue(ns.issubset(gf.namespaces))
def test_two_excluded_named_namespaces(self):
"""Test two excluded named namespaces."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:not:Talk,File')
ns = set(range(16))
ns.remove(1)
ns.remove(6)
self.assertTrue(ns.issubset(gf.namespaces))
def test_two_excluded_numeric_namespaces(self):
"""Test two excluded namespaces delimited by colon."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:not:1,6')
ns = set(range(16))
ns.remove(1)
ns.remove(6)
self.assertTrue(ns.issubset(gf.namespaces))
def test_mixed_namespaces_with_exclusion(self):
"""Test mixed namespaces with exclusion."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:not:2,File')
gf.handle_arg('-ns:not:3,4,5')
gf.handle_arg('-ns:6,7')
ns = set(range(16))
for i in range(2, 6):
ns.remove(i)
self.assertTrue(ns.issubset(gf.namespaces))
def test_given_namespaces_with_exclusion(self):
"""Test mixed namespaces with exclusion."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
gf.handle_arg('-ns:1,2,3,4,5')
gf.handle_arg('-ns:not:User')
self.assertEqual(gf.namespaces, {1, 3, 4, 5})
def test_invalid_arg(self):
"""Test invalid / non-generator arguments."""
gf = pagegenerators.GeneratorFactory(site=self.get_site())
self.assertFalse(gf.handle_arg('-foobar'))
self.assertFalse(gf.handle_arg('barbaz'))
self.assertFalse(gf.handle_arg('-ì'))
self.assertFalse(gf.handle_arg('ì'))
class TestItemClaimFilterPageGenerator(WikidataTestCase):
"""Test item claim filter page generator generator."""
def _simple_claim_test(self, prop: str, claim, qualifiers: Optional[dict],
valid: bool, negate: bool = False):
"""
Test given claim on sample (India) page.
:param prop: the property to check
:param claim: the claim the property should contain
:param qualifiers: qualifiers to check or None
:param valid: true if the page should be yielded by the generator,
false otherwise
:param negate: true to swap the filters' behavior
"""
item = pywikibot.ItemPage(self.get_repo(), 'Q668')
gen = pagegenerators.ItemClaimFilterPageGenerator([item], prop, claim,
qualifiers, negate)
pages = set(gen)
if valid:
self.assertLength(pages, 1)
else:
self.assertIsEmpty(pages)
def _get_council_page(self):
"""Return United Nations Security Council Wikidata page."""
site = self.get_site()
return pywikibot.Page(site, 'Q37470')
def test_valid_qualifiers(self):
"""Test ItemClaimFilterPageGenerator using valid qualifiers."""
qualifiers = {
'P580': pywikibot.WbTime(1950, 1, 1, precision=9,
site=self.get_site()),
'P582': '1951',
}
self._simple_claim_test('P463', self._get_council_page(), qualifiers,
True)
def test_invalid_qualifiers(self):
"""Test ItemClaimFilterPageGenerator with invalid qualifiers."""
qualifiers = {
'P580': 1950,
'P582': pywikibot.WbTime(1960, 1, 1, precision=9,
site=self.site),
}
self._simple_claim_test('P463', self._get_council_page(), qualifiers,
False)
def test_nonexisting_qualifiers(self):
"""
Test ItemClaimFilterPageGenerator on sample page.
The item does not have the searched qualifiers.
"""
qualifiers = {
'P370': pywikibot.WbTime(1950, 1, 1, precision=9,
site=self.get_site()),
'P232': pywikibot.WbTime(1960, 1, 1, precision=9,
site=self.get_site()),
}
self._simple_claim_test('P463', self._get_council_page(), qualifiers,
False)
def test_no_qualifiers(self):
"""Test ItemClaimFilterPageGenerator without qualifiers."""
self._simple_claim_test('P474', '+91', None, True)
self._simple_claim_test('P463', 'Q37470', None, True)
self._simple_claim_test('P1334', '28,97.4,0.1', None, True)
self._simple_claim_test('P1334', '28,96,0.01', None, False)
def test_negative_filter(self):
"""Test negative ItemClaimFilterPageGenerator."""
self._simple_claim_test('P463', 'Q37470', None, False, True)
self._simple_claim_test('P463', 'Q37471', None, True, True)
def test_item_from_page(self):
"""Test ItemPage can be obtained form Page."""
site = pywikibot.Site('en', 'wikipedia')
page = pywikibot.Page(site, 'India')
gen = pagegenerators.ItemClaimFilterPageGenerator(
[page], 'P463', self._get_council_page())
pages = set(gen)
self.assertEqual(pages.pop(), page)
class TestFactoryGenerator(DefaultSiteTestCase):
"""Test pagegenerators.GeneratorFactory."""
def test_combined_generator(self):
"""Test getCombinedGenerator with generator parameter."""
gf = pagegenerators.GeneratorFactory()
gen = gf.getCombinedGenerator(gen='ABC')
self.assertEqual(tuple(gen), ('A', 'B', 'C'))
def test_intersect_generator(self):
"""Test getCombinedGenerator with -intersect option."""
gf = pagegenerators.GeneratorFactory()
gf.handle_arg('-intersect')
# check wether the generator works for both directions
patterns = ['Python 3.7-dev', 'Pywikibot 7.0.dev']
for index in range(2):
with self.subTest(index=index):
gf.gens = [patterns[index]]
gen = gf.getCombinedGenerator(gen=patterns[index - 1])
self.assertEqual(''.join(gen), 'Pyot 7.dev')
# check wether the generator works for a very long text
patterns.append('PWB 7+ unittest developed with a very long text.')
with self.subTest(patterns=patterns):
gf.gens = patterns
gen = gf.getCombinedGenerator()
self.assertEqual(''.join(gen), 'P 7tedvoy.')
# check whether an early stop fits
with self.subTest(comment='Early stop'):
gf.gens = 'ABC', 'A Big City'
gen = gf.getCombinedGenerator()
self.assertEqual(''.join(gen), 'ABC')
with self.subTest(comment='Commutative'):
gf.gens = 'ABB', 'BB'
gen1 = gf.getCombinedGenerator()
gf2 = pagegenerators.GeneratorFactory()
gf2.handle_arg('-intersect')
gf2.gens = 'BB', 'ABB'
gen2 = gf2.getCombinedGenerator()
self.assertEqual(list(gen1), list(gen2))
def test_ns(self):
"""Test namespace option."""
gf = pagegenerators.GeneratorFactory()
gf.handle_arg('-ns:1')
gen = gf.getCombinedGenerator()
self.assertIsNone(gen)
def test_allpages_default(self):
"""Test allpages generator."""
gf = pagegenerators.GeneratorFactory()
self.assertTrue(gf.handle_arg('-start:!'))
gf.handle_arg('-limit:10')
gen = gf.getCombinedGenerator()
self.assertIsNotNone(gen)
pages = set(gen)
self.assertLessEqual(len(pages), 10)
for page in pages:
self.assertIsInstance(page, pywikibot.Page)
self.assertEqual(page.namespace(), 0)
def test_allpages_ns(self):
"""Test allpages generator with namespace argument."""
gf = pagegenerators.GeneratorFactory()
self.assertTrue(gf.handle_arg('-start:!'))
gf.handle_arg('-limit:10')
gf.handle_arg('-ns:1')
gen = gf.getCombinedGenerator()
self.assertIsNotNone(gen)
pages = set(gen)
self.assertLessEqual(len(pages), 10)
self.assertPagesInNamespaces(gen, 1)
def test_regexfilter_default(self):
"""Test allpages generator with titleregex filter."""
gf = pagegenerators.GeneratorFactory()
# Matches titles with the same two or more continuous characters
self.assertTrue(gf.handle_arg('-start'))
self.assertTrue(gf.handle_arg('-titleregex:(.)\\1+'))
gf.handle_arg('-limit:10')
gen = gf.getCombinedGenerator()
self.assertIsNotNone(gen)
pages = list(gen)
self.assertLessEqual(len(pages), 10)
for page in pages:
self.assertIsInstance(page, pywikibot.Page)
self.assertRegex(page.title().lower(), '(.)\\1+')
def test_regexfilter_ns_after(self):
"""Test allpages generator with titleregex and namespace filter."""
gf = pagegenerators.GeneratorFactory()
self.assertTrue(gf.handle_arg('-start'))
self.assertTrue(gf.handle_arg('-titleregex:.*'))
gf.handle_arg('-ns:1')
gf.handle_arg('-limit:10')
gen = gf.getCombinedGenerator()
pages = list(gen)
self.assertLessEqual(len(pages), 10)
self.assertPagesInNamespaces(pages, 1)
def test_regexfilter_ns_before(self):
"""Test allpages generator with namespace and titleregex filter."""
gf = pagegenerators.GeneratorFactory()
self.assertTrue(gf.handle_arg('-start'))
gf.handle_arg('-ns:1')
self.assertTrue(gf.handle_arg('-titleregex:.*'))
gf.handle_arg('-limit:10')
gen = gf.getCombinedGenerator()
self.assertIsNotNone(gen)