forked from wikimedia/pywikibot
/
wikibase_tests.py
executable file
·2542 lines (2174 loc) · 102 KB
/
wikibase_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
"""Tests for the Wikidata parts of the page module."""
#
# (C) Pywikibot team, 2008-2024
#
# Distributed under the terms of the MIT license.
#
from __future__ import annotations
import copy
import datetime
import json
import operator
import unittest
from contextlib import suppress
from decimal import Decimal
from unittest import mock
import pywikibot
from pywikibot import pagegenerators
from pywikibot.exceptions import (
InvalidTitleError,
IsNotRedirectPageError,
IsRedirectPageError,
NoPageError,
UnknownExtensionError,
WikiBaseError,
)
from pywikibot.page import ItemPage, Page, PropertyPage, WikibasePage
from pywikibot.site import Namespace, NamespacesDict
from pywikibot.tools import MediaWikiVersion, suppress_warnings
from tests import WARN_SITE_CODE, join_pages_path
from tests.aspects import TestCase, WikidataTestCase
from tests.basepage import (
BasePageLoadRevisionsCachingTestBase,
BasePageMethodsTestBase,
)
# fetch a page which is very likely to be unconnected, which doesn't have
# a generator, and unit tests may be used to test old versions of pywikibot
def _get_test_unconnected_page(site):
"""Get unconnected page from site for tests."""
gen = pagegenerators.NewpagesPageGenerator(site=site, total=10,
namespaces=[1])
for page in gen:
if not page.properties().get('wikibase_item'):
return page
return None # pragma: no cover
class WbRepresentationTestCase(WikidataTestCase):
"""Test methods inherited or extended from _WbRepresentation."""
def _test_hashable(self, representation):
"""Test that the representation is hashable."""
list_of_dupes = [representation, representation]
self.assertLength(set(list_of_dupes), 1)
class TestLoadRevisionsCaching(BasePageLoadRevisionsCachingTestBase,
WikidataTestCase):
"""Test site.loadrevisions() caching."""
def setUp(self):
"""Setup test."""
self._page = ItemPage(self.get_repo(), 'Q15169668')
super().setUp()
def test_page_text(self):
"""Test site.loadrevisions() with Page.text."""
with suppress_warnings(WARN_SITE_CODE, category=UserWarning):
self._test_page_text()
class TestGeneral(WikidataTestCase):
"""General Wikibase tests."""
@classmethod
def setUpClass(cls):
"""Setup test class."""
super().setUpClass()
enwiki = pywikibot.Site('en', 'wikipedia')
cls.mainpage = pywikibot.Page(pywikibot.page.Link('Main Page', enwiki))
def testWikibase(self):
"""Wikibase tests."""
repo = self.get_repo()
item_namespace = repo.namespaces[0]
self.assertEqual(item_namespace.defaultcontentmodel, 'wikibase-item')
item = ItemPage.fromPage(self.mainpage)
self.assertIsInstance(item, ItemPage)
self.assertEqual(item.getID(), 'Q5296')
self.assertEqual(item.title(), 'Q5296')
self.assertIn('en', item.labels)
self.assertTrue(
item.labels['en'].lower().endswith('main page'),
msg=f"\nitem.labels['en'] of item Q5296 is {item.labels['en']!r}")
self.assertIn('en', item.aliases)
self.assertIn('home page', (a.lower() for a in item.aliases['en']))
self.assertEqual(item.namespace(), 0)
item2 = ItemPage(repo, 'q5296')
self.assertEqual(item2.getID(), 'Q5296')
item2.get()
self.assertTrue(item2.labels['en'].lower().endswith('main page'))
prop = PropertyPage(repo, 'Property:P21')
self.assertEqual(prop.type, 'wikibase-item')
self.assertEqual(prop.namespace(), 120)
claim = pywikibot.Claim(repo, 'p21')
regex = r' is not type .+\.$'
with self.assertRaisesRegex(ValueError, regex):
claim.setTarget(value='test')
claim.setTarget(ItemPage(repo, 'q1'))
self.assertEqual(claim._formatValue(), {'entity-type': 'item',
'numeric-id': 1})
def test_cmp(self):
"""Test WikibasePage comparison."""
self.assertEqual(ItemPage.fromPage(self.mainpage),
ItemPage(self.get_repo(), 'q5296'))
class TestWikibaseCoordinate(WbRepresentationTestCase):
"""Test Wikibase Coordinate data type."""
dry = True
def test_Coordinate_WbRepresentation_methods(self):
"""Test inherited or extended methods from _WbRepresentation."""
repo = self.get_repo()
coord = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0,
globe='moon')
self._test_hashable(coord)
def test_Coordinate_dim(self):
"""Test Coordinate dimension."""
repo = self.get_repo()
x = pywikibot.Coordinate(site=repo, lat=12.0, lon=13.0, precision=5.0)
self.assertEqual(x.precisionToDim(), 544434)
self.assertIsInstance(x.precisionToDim(), int)
y = pywikibot.Coordinate(site=repo, lat=12.0, lon=13.0, dim=54444)
self.assertEqual(y.precision, 0.500005084017101)
self.assertIsInstance(y.precision, float)
z = pywikibot.Coordinate(site=repo, lat=12.0, lon=13.0)
regex = r'^No values set for dim or precision$'
with self.assertRaisesRegex(ValueError, regex):
z.precisionToDim()
def test_Coordinate_plain_globe(self):
"""Test setting Coordinate globe from a plain-text value."""
repo = self.get_repo()
coord = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0,
globe='moon')
self.assertEqual(coord.toWikibase(),
{'latitude': 12.0, 'longitude': 13.0,
'altitude': None, 'precision': 0,
'globe': 'http://www.wikidata.org/entity/Q405'})
def test_Coordinate_entity_uri_globe(self):
"""Test setting Coordinate globe from an entity uri."""
repo = self.get_repo()
coord = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0,
globe_item='http://www.wikidata.org/entity/Q123')
self.assertEqual(coord.toWikibase(),
{'latitude': 12.0, 'longitude': 13.0,
'altitude': None, 'precision': 0,
'globe': 'http://www.wikidata.org/entity/Q123'})
class TestWikibaseCoordinateNonDry(WbRepresentationTestCase):
"""
Test Wikibase Coordinate data type (non-dry).
These can be moved to TestWikibaseCoordinate once DrySite has been bumped
to the appropriate version.
"""
def test_Coordinate_item_globe(self):
"""Test setting Coordinate globe from an ItemPage."""
repo = self.get_repo()
coord = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0,
globe_item=ItemPage(repo, 'Q123'))
self.assertEqual(coord.toWikibase(),
{'latitude': 12.0, 'longitude': 13.0,
'altitude': None, 'precision': 0,
'globe': 'http://www.wikidata.org/entity/Q123'})
def test_Coordinate_get_globe_item_from_uri(self):
"""Test getting globe item from Coordinate with entity uri globe."""
repo = self.get_repo()
q = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0,
globe_item='http://www.wikidata.org/entity/Q123')
self.assertEqual(q.get_globe_item(), ItemPage(repo, 'Q123'))
def test_Coordinate_get_globe_item_from_itempage(self):
"""Test getting globe item from Coordinate with ItemPage globe."""
repo = self.get_repo()
globe = ItemPage(repo, 'Q123')
q = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0, globe_item=globe)
self.assertEqual(q.get_globe_item(), ItemPage(repo, 'Q123'))
def test_Coordinate_get_globe_item_from_plain_globe(self):
"""Test getting globe item from Coordinate with plain text globe."""
repo = self.get_repo()
q = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0, globe='moon')
self.assertEqual(q.get_globe_item(), ItemPage(repo, 'Q405'))
def test_Coordinate_get_globe_item_provide_repo(self):
"""Test getting globe item from Coordinate, providing repo."""
repo = self.get_repo()
q = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0,
globe_item='http://www.wikidata.org/entity/Q123')
self.assertEqual(q.get_globe_item(repo), ItemPage(repo, 'Q123'))
def test_Coordinate_get_globe_item_different_repo(self):
"""Test getting globe item in different repo from Coordinate."""
repo = self.get_repo()
test_repo = pywikibot.Site('test', 'wikidata')
q = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0,
globe_item='http://test.wikidata.org/entity/Q123')
self.assertEqual(q.get_globe_item(test_repo),
ItemPage(test_repo, 'Q123'))
def test_Coordinate_equality(self):
"""Test Coordinate equality with different globe representations."""
repo = self.get_repo()
a = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0.1,
globe='moon')
b = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0.1,
globe_item='http://www.wikidata.org/entity/Q405')
c = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0.1,
globe_item=ItemPage(repo, 'Q405'))
d = pywikibot.Coordinate(
site=repo, lat=12.0, lon=13.0, precision=0.1,
globe_item='http://test.wikidata.org/entity/Q405')
self.assertEqual(a, b)
self.assertEqual(b, c)
self.assertEqual(c, a)
self.assertNotEqual(a, d)
self.assertNotEqual(b, d)
self.assertNotEqual(c, d)
class TestWbTime(WbRepresentationTestCase):
"""Test Wikibase WbTime data type."""
dry = True
def test_WbTime_WbRepresentation_methods(self):
"""Test inherited or extended methods from _WbRepresentation."""
repo = self.get_repo()
t = pywikibot.WbTime(site=repo, year=2010, month=0, day=0, hour=12,
minute=43)
self._test_hashable(t)
def test_WbTime_timestr(self):
"""Test timestr functions of WbTime."""
repo = self.get_repo()
t = pywikibot.WbTime(site=repo, year=2010, month=0, day=0, hour=12,
minute=43)
self.assertEqual(t.toTimestr(), '+00000002010-00-00T12:43:00Z')
self.assertEqual(t.toTimestr(force_iso=True), '+2010-01-01T12:43:00Z')
t = pywikibot.WbTime(site=repo, year=2010, hour=12, minute=43)
self.assertEqual(t.toTimestr(), '+00000002010-01-01T12:43:00Z')
self.assertEqual(t.toTimestr(force_iso=True), '+2010-01-01T12:43:00Z')
t = pywikibot.WbTime(site=repo, year=-2010, hour=12, minute=43)
self.assertEqual(t.toTimestr(), '-00000002010-01-01T12:43:00Z')
self.assertEqual(t.toTimestr(force_iso=True), '-2010-01-01T12:43:00Z')
def test_WbTime_fromTimestr(self):
"""Test WbTime creation from UTC date/time string."""
repo = self.get_repo()
t = pywikibot.WbTime.fromTimestr('+00000002010-01-01T12:43:00Z',
site=repo)
self.assertEqual(t, pywikibot.WbTime(site=repo, year=2010, hour=12,
minute=43, precision=14))
def test_WbTime_zero_month(self):
"""Test WbTime creation from date/time string with zero month."""
# ensures we support formats in T123888 / T107870
repo = self.get_repo()
t = pywikibot.WbTime.fromTimestr('+00000002010-00-00T12:43:00Z',
site=repo)
self.assertEqual(t, pywikibot.WbTime(site=repo, year=2010, month=0,
day=0, hour=12, minute=43,
precision=14))
def test_WbTime_skip_params_precision(self):
"""Test skipping units (such as day, month) when creating WbTimes."""
repo = self.get_repo()
t = pywikibot.WbTime(year=2020, day=2, site=repo)
self.assertEqual(t, pywikibot.WbTime(year=2020, month=1, day=2,
site=repo))
self.assertEqual(t.precision, pywikibot.WbTime.PRECISION['day'])
t2 = pywikibot.WbTime(year=2020, hour=5, site=repo)
self.assertEqual(t2, pywikibot.WbTime(year=2020, month=1, day=1,
hour=5, site=repo))
self.assertEqual(t2.precision, pywikibot.WbTime.PRECISION['hour'])
t3 = pywikibot.WbTime(year=2020, minute=5, site=repo)
self.assertEqual(t3, pywikibot.WbTime(year=2020, month=1, day=1,
hour=0, minute=5, site=repo))
self.assertEqual(t3.precision, pywikibot.WbTime.PRECISION['minute'])
t4 = pywikibot.WbTime(year=2020, second=5, site=repo)
self.assertEqual(t4, pywikibot.WbTime(year=2020, month=1, day=1,
hour=0, minute=0, second=5,
site=repo))
self.assertEqual(t4.precision, pywikibot.WbTime.PRECISION['second'])
t5 = pywikibot.WbTime(year=2020, month=2, hour=5, site=repo)
self.assertEqual(t5, pywikibot.WbTime(year=2020, month=2, day=1,
hour=5, site=repo))
self.assertEqual(t5.precision, pywikibot.WbTime.PRECISION['hour'])
t6 = pywikibot.WbTime(year=2020, month=2, minute=5, site=repo)
self.assertEqual(t6, pywikibot.WbTime(year=2020, month=2, day=1,
hour=0, minute=5, site=repo))
self.assertEqual(t6.precision, pywikibot.WbTime.PRECISION['minute'])
t7 = pywikibot.WbTime(year=2020, month=2, second=5, site=repo)
self.assertEqual(t7, pywikibot.WbTime(year=2020, month=2, day=1,
hour=0, minute=0, second=5,
site=repo))
self.assertEqual(t7.precision, pywikibot.WbTime.PRECISION['second'])
t8 = pywikibot.WbTime(year=2020, day=2, hour=5, site=repo)
self.assertEqual(t8, pywikibot.WbTime(year=2020, month=1, day=2,
hour=5, site=repo))
self.assertEqual(t8.precision, pywikibot.WbTime.PRECISION['hour'])
t9 = pywikibot.WbTime(year=2020, month=3, day=2, minute=5, site=repo)
self.assertEqual(t9, pywikibot.WbTime(year=2020, month=3, day=2,
hour=0, minute=5, site=repo))
self.assertEqual(t9.precision, pywikibot.WbTime.PRECISION['minute'])
def test_WbTime_normalization(self):
"""Test WbTime normalization."""
repo = self.get_repo()
# flake8 is being annoying, so to reduce line length, I'll make
# some aliases here
decade = pywikibot.WbTime.PRECISION['decade']
century = pywikibot.WbTime.PRECISION['century']
millenia = pywikibot.WbTime.PRECISION['millenia']
t = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12)
t2 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12,
precision=pywikibot.WbTime.PRECISION['second'])
t3 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12,
precision=pywikibot.WbTime.PRECISION['minute'])
t4 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12,
precision=pywikibot.WbTime.PRECISION['hour'])
t5 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12,
precision=pywikibot.WbTime.PRECISION['day'])
t6 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12,
precision=pywikibot.WbTime.PRECISION['month'])
t7 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12,
precision=pywikibot.WbTime.PRECISION['year'])
t8 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12,
precision=decade)
t9 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12,
precision=century)
t10 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12,
precision=millenia)
t11 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12, timezone=-300,
precision=pywikibot.WbTime.PRECISION['day'])
t12 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12, timezone=300,
precision=pywikibot.WbTime.PRECISION['day'])
t13 = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=12, timezone=-300,
precision=pywikibot.WbTime.PRECISION['hour'])
self.assertEqual(t.normalize(), t)
self.assertEqual(t2.normalize(), t.normalize())
self.assertEqual(t3.normalize(),
pywikibot.WbTime(site=repo, year=2010, month=1,
day=1, hour=12, minute=43))
self.assertEqual(t4.normalize(),
pywikibot.WbTime(site=repo, year=2010,
month=1, day=1, hour=12))
self.assertEqual(t5.normalize(),
pywikibot.WbTime(site=repo, year=2010,
month=1, day=1))
self.assertEqual(t6.normalize(),
pywikibot.WbTime(site=repo, year=2010,
month=1))
self.assertEqual(
t7.normalize(), pywikibot.WbTime(site=repo, year=2010))
self.assertEqual(t8.normalize(),
pywikibot.WbTime(site=repo, year=2010,
precision=decade))
self.assertEqual(t9.normalize(),
pywikibot.WbTime(site=repo, year=2100,
precision=century))
self.assertEqual(t9.normalize(),
pywikibot.WbTime(site=repo, year=2010,
precision=century).normalize())
self.assertEqual(t10.normalize(),
pywikibot.WbTime(site=repo, year=3000,
precision=millenia))
self.assertEqual(t10.normalize(),
pywikibot.WbTime(site=repo, year=2010,
precision=millenia).normalize())
t11_normalized = t11.normalize()
t12_normalized = t12.normalize()
self.assertEqual(t11_normalized.timezone, 0)
self.assertEqual(t12_normalized.timezone, 0)
self.assertNotEqual(t11, t12)
self.assertEqual(t11_normalized, t12_normalized)
self.assertEqual(t13.normalize().timezone, -300)
def test_WbTime_normalization_very_low_precision(self):
"""Test WbTime normalization with very low precision."""
repo = self.get_repo()
# flake8 is being annoying, so to reduce line length, I'll make
# some aliases here
year_10000 = pywikibot.WbTime.PRECISION['10000']
year_100000 = pywikibot.WbTime.PRECISION['100000']
year_1000000 = pywikibot.WbTime.PRECISION['1000000']
year_10000000 = pywikibot.WbTime.PRECISION['10000000']
year_100000000 = pywikibot.WbTime.PRECISION['100000000']
year_1000000000 = pywikibot.WbTime.PRECISION['1000000000']
t = pywikibot.WbTime(site=repo, year=-3124684989,
precision=year_10000)
t2 = pywikibot.WbTime(site=repo, year=-3124684989,
precision=year_100000)
t3 = pywikibot.WbTime(site=repo, year=-3124684989,
precision=year_1000000)
t4 = pywikibot.WbTime(site=repo, year=-3124684989,
precision=year_10000000)
t5 = pywikibot.WbTime(site=repo, year=-3124684989,
precision=year_100000000)
t6 = pywikibot.WbTime(site=repo, year=-3124684989,
precision=year_1000000000)
self.assertEqual(t.normalize(),
pywikibot.WbTime(site=repo, year=-3124680000,
precision=year_10000))
self.assertEqual(t2.normalize(),
pywikibot.WbTime(site=repo, year=-3124700000,
precision=year_100000))
self.assertEqual(t3.normalize(),
pywikibot.WbTime(site=repo, year=-3125000000,
precision=year_1000000))
self.assertEqual(t4.normalize(),
pywikibot.WbTime(site=repo, year=-3120000000,
precision=year_10000000))
self.assertEqual(t5.normalize(),
pywikibot.WbTime(site=repo, year=-3100000000,
precision=year_100000000))
self.assertEqual(t6.normalize(),
pywikibot.WbTime(site=repo, year=-3000000000,
precision=year_1000000000))
def test_WbTime_timestamp(self):
"""Test timestamp functions of WbTime."""
repo = self.get_repo()
timestamp = pywikibot.Timestamp.fromISOformat('2010-01-01T12:43:00Z')
t = pywikibot.WbTime(site=repo, year=2010, month=0, day=0, hour=12,
minute=43)
self.assertEqual(t.toTimestamp(), timestamp)
# Roundtrip fails as Timestamp and WbTime interpret month=0 differently
self.assertNotEqual(
t, pywikibot.WbTime.fromTimestamp(timestamp, site=repo))
t = pywikibot.WbTime(site=repo, year=2010, hour=12, minute=43)
self.assertEqual(t.toTimestamp(), timestamp)
t = pywikibot.WbTime(site=repo, year=-2010, hour=12, minute=43)
regex = r'^You cannot turn BC dates into a Timestamp$'
with self.assertRaisesRegex(ValueError, regex):
t.toTimestamp()
t = pywikibot.WbTime(site=repo, year=2010, month=1, day=1, hour=12,
minute=43, second=0)
self.assertEqual(t.toTimestamp(), timestamp)
self.assertEqual(
t, pywikibot.WbTime.fromTimestamp(timestamp, site=repo))
timezone = datetime.timezone(datetime.timedelta(hours=-5))
ts = pywikibot.Timestamp(2020, 1, 1, 12, 43, 0, tzinfo=timezone)
t = pywikibot.WbTime.fromTimestamp(ts, site=repo, copy_timezone=True)
self.assertEqual(t.timezone, -5 * 60)
t = pywikibot.WbTime.fromTimestamp(ts, site=repo, copy_timezone=True,
timezone=60)
self.assertEqual(t.timezone, 60)
ts1 = pywikibot.Timestamp(
year=2022, month=12, day=21, hour=13,
tzinfo=datetime.timezone(datetime.timedelta(hours=-5)))
t1 = pywikibot.WbTime.fromTimestamp(ts1, timezone=-300, site=repo)
self.assertIsNotNone(t1.toTimestamp(timezone_aware=True).tzinfo)
self.assertIsNone(t1.toTimestamp(timezone_aware=False).tzinfo)
self.assertEqual(t1.toTimestamp(timezone_aware=True), ts1)
self.assertNotEqual(t1.toTimestamp(timezone_aware=False), ts1)
def test_WbTime_errors(self):
"""Test WbTime precision errors."""
repo = self.get_repo()
regex = r'^no year given$'
with self.assertRaisesRegex(ValueError, regex):
pywikibot.WbTime(site=repo, precision=15)
with self.assertRaisesRegex(ValueError, regex):
pywikibot.WbTime(site=repo, precision='invalid_precision')
regex = r'^Invalid precision: "15"$'
with self.assertRaisesRegex(ValueError, regex):
pywikibot.WbTime(site=repo, year=2020, precision=15)
regex = r'^Invalid precision: "invalid_precision"$'
with self.assertRaisesRegex(ValueError, regex):
pywikibot.WbTime(site=repo, year=2020,
precision='invalid_precision')
def test_comparison(self):
"""Test WbTime comparison."""
repo = self.get_repo()
t1 = pywikibot.WbTime(site=repo, year=2010, hour=12, minute=43)
t2 = pywikibot.WbTime(site=repo, year=-2005, hour=16, minute=45)
self.assertEqual(t1.precision, pywikibot.WbTime.PRECISION['minute'])
self.assertEqual(t1, t1)
self.assertGreaterEqual(t1, t1)
self.assertGreaterEqual(t1, t2)
self.assertGreater(t1, t2)
self.assertEqual(t1.year, 2010)
self.assertEqual(t2.year, -2005)
self.assertEqual(t1.month, 1)
self.assertEqual(t2.month, 1)
self.assertEqual(t1.day, 1)
self.assertEqual(t2.day, 1)
self.assertEqual(t1.hour, 12)
self.assertEqual(t2.hour, 16)
self.assertEqual(t1.minute, 43)
self.assertEqual(t2.minute, 45)
self.assertEqual(t1.second, 0)
self.assertEqual(t2.second, 0)
self.assertEqual(t1.toTimestr(), '+00000002010-01-01T12:43:00Z')
self.assertEqual(t2.toTimestr(), '-00000002005-01-01T16:45:00Z')
self.assertRaises(ValueError, pywikibot.WbTime, site=repo,
precision=15)
self.assertRaises(ValueError, pywikibot.WbTime, site=repo,
precision='invalid_precision')
self.assertIsInstance(t1.toTimestamp(), pywikibot.Timestamp)
self.assertRaises(ValueError, t2.toTimestamp)
def test_comparison_types(self):
"""Test WbTime comparison with different types."""
repo = self.get_repo()
t1 = pywikibot.WbTime(site=repo, year=2010, hour=12, minute=43)
t2 = pywikibot.WbTime(site=repo, year=-2005, hour=16, minute=45)
self.assertGreater(t1, t2)
self.assertRaises(TypeError, operator.lt, t1, 5)
self.assertRaises(TypeError, operator.gt, t1, 5)
self.assertRaises(TypeError, operator.le, t1, 5)
self.assertRaises(TypeError, operator.ge, t1, 5)
def test_comparison_timezones(self):
"""Test comparisons with timezones."""
repo = self.get_repo()
ts1 = pywikibot.Timestamp(
year=2022, month=12, day=21, hour=13,
tzinfo=datetime.timezone(datetime.timedelta(hours=-5)))
ts2 = pywikibot.Timestamp(
year=2022, month=12, day=21, hour=17,
tzinfo=datetime.timezone.utc)
self.assertGreater(ts1.timestamp(), ts2.timestamp())
t1 = pywikibot.WbTime.fromTimestamp(ts1, timezone=-300, site=repo)
t2 = pywikibot.WbTime.fromTimestamp(ts2, timezone=0, site=repo)
self.assertGreater(t1, t2)
def test_comparison_timezones_equal(self):
"""Test when two WbTime's have equal instants but not the same tz."""
repo = self.get_repo()
ts1 = pywikibot.Timestamp(
year=2023, month=12, day=21, hour=13,
tzinfo=datetime.timezone(datetime.timedelta(hours=-5)))
ts2 = pywikibot.Timestamp(
year=2023, month=12, day=21, hour=18,
tzinfo=datetime.timezone.utc)
self.assertEqual(ts1.timestamp(), ts2.timestamp())
t1 = pywikibot.WbTime.fromTimestamp(ts1, timezone=-300, site=repo)
t2 = pywikibot.WbTime.fromTimestamp(ts2, timezone=0, site=repo)
self.assertGreaterEqual(t1, t2)
self.assertGreaterEqual(t2, t1)
self.assertNotEqual(t1, t2)
self.assertNotEqual(t2, t1)
# Ignore H205: We specifically want to test the operator
self.assertFalse(t1 > t2) # noqa: H205
self.assertFalse(t2 > t1) # noqa: H205
self.assertFalse(t1 < t2) # noqa: H205
self.assertFalse(t2 < t1) # noqa: H205
def test_comparison_equal_instant(self):
"""Test the equal_instant method."""
repo = self.get_repo()
ts1 = pywikibot.Timestamp(
year=2023, month=12, day=21, hour=13,
tzinfo=datetime.timezone(datetime.timedelta(hours=-5)))
ts2 = pywikibot.Timestamp(
year=2023, month=12, day=21, hour=18,
tzinfo=datetime.timezone.utc)
ts3 = pywikibot.Timestamp(
year=2023, month=12, day=21, hour=19,
tzinfo=datetime.timezone(datetime.timedelta(hours=1)))
ts4 = pywikibot.Timestamp(
year=2023, month=12, day=21, hour=13,
tzinfo=datetime.timezone(datetime.timedelta(hours=-6)))
self.assertEqual(ts1.timestamp(), ts2.timestamp())
self.assertEqual(ts1.timestamp(), ts3.timestamp())
self.assertEqual(ts2.timestamp(), ts3.timestamp())
self.assertNotEqual(ts1.timestamp(), ts4.timestamp())
self.assertNotEqual(ts2.timestamp(), ts4.timestamp())
self.assertNotEqual(ts3.timestamp(), ts4.timestamp())
t1 = pywikibot.WbTime.fromTimestamp(ts1, timezone=-300, site=repo)
t2 = pywikibot.WbTime.fromTimestamp(ts2, timezone=0, site=repo)
t3 = pywikibot.WbTime.fromTimestamp(ts3, timezone=60, site=repo)
t4 = pywikibot.WbTime.fromTimestamp(ts4, timezone=-360, site=repo)
self.assertTrue(t1.equal_instant(t2))
self.assertTrue(t1.equal_instant(t3))
self.assertTrue(t2.equal_instant(t3))
self.assertFalse(t1.equal_instant(t4))
self.assertFalse(t2.equal_instant(t4))
self.assertFalse(t3.equal_instant(t4))
class TestWbQuantity(WbRepresentationTestCase):
"""Test Wikibase WbQuantity data type."""
dry = True
def test_WbQuantity_WbRepresentation_methods(self):
"""Test inherited or extended methods from _WbRepresentation."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount=1234, error=1, site=repo)
self._test_hashable(q)
def test_WbQuantity_integer(self):
"""Test WbQuantity for integer value."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount=1234, error=1, site=repo)
self.assertEqual(q.toWikibase(),
{'amount': '+1234', 'lowerBound': '+1233',
'upperBound': '+1235', 'unit': '1'})
q = pywikibot.WbQuantity(amount=5, error=(2, 3), site=repo)
self.assertEqual(q.toWikibase(),
{'amount': '+5', 'lowerBound': '+2',
'upperBound': '+7', 'unit': '1'})
q = pywikibot.WbQuantity(amount=0, error=(0, 0), site=repo)
self.assertEqual(q.toWikibase(),
{'amount': '+0', 'lowerBound': '+0',
'upperBound': '+0', 'unit': '1'})
q = pywikibot.WbQuantity(amount=-5, error=(2, 3), site=repo)
self.assertEqual(q.toWikibase(),
{'amount': '-5', 'lowerBound': '-8',
'upperBound': '-3', 'unit': '1'})
def test_WbQuantity_float_27(self):
"""Test WbQuantity for float value."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount=0.044405586, error=0.0, site=repo)
q_dict = {'amount': '+0.044405586', 'lowerBound': '+0.044405586',
'upperBound': '+0.044405586', 'unit': '1'}
self.assertEqual(q.toWikibase(), q_dict)
def test_WbQuantity_scientific(self):
"""Test WbQuantity for scientific notation."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount='1.3e-13', error='1e-14', site=repo)
q_dict = {'amount': '+1.3e-13', 'lowerBound': '+1.2e-13',
'upperBound': '+1.4e-13', 'unit': '1'}
self.assertEqual(q.toWikibase(), q_dict)
def test_WbQuantity_decimal(self):
"""Test WbQuantity for decimal value."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount=Decimal('0.044405586'),
error=Decimal('0.0'), site=repo)
q_dict = {'amount': '+0.044405586', 'lowerBound': '+0.044405586',
'upperBound': '+0.044405586', 'unit': '1'}
self.assertEqual(q.toWikibase(), q_dict)
def test_WbQuantity_string(self):
"""Test WbQuantity for decimal notation."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount='0.044405586', error='0', site=repo)
q_dict = {'amount': '+0.044405586', 'lowerBound': '+0.044405586',
'upperBound': '+0.044405586', 'unit': '1'}
self.assertEqual(q.toWikibase(), q_dict)
def test_WbQuantity_formatting_bound(self):
"""Test WbQuantity formatting with bounds."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount='0.044405586', error='0', site=repo)
self.assertEqual(str(q),
'{{\n'
' "amount": "+{val}",\n'
' "lowerBound": "+{val}",\n'
' "unit": "1",\n'
' "upperBound": "+{val}"\n'
'}}'.format(val='0.044405586'))
self.assertEqual(repr(q),
'WbQuantity(amount={val}, '
'upperBound={val}, lowerBound={val}, '
'unit=1)'.format(val='0.044405586'))
def test_WbQuantity_self_equality(self):
"""Test WbQuantity equality."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount='0.044405586', error='0', site=repo)
self.assertEqual(q, q)
def test_WbQuantity_fromWikibase(self):
"""Test WbQuantity.fromWikibase() instantiating."""
repo = self.get_repo()
q = pywikibot.WbQuantity.fromWikibase({'amount': '+0.0229',
'lowerBound': '0',
'upperBound': '1',
'unit': '1'},
site=repo)
# note that the bounds are inputted as INT but are returned as FLOAT
self.assertEqual(q.toWikibase(),
{'amount': '+0.0229', 'lowerBound': '+0.0000',
'upperBound': '+1.0000', 'unit': '1'})
def test_WbQuantity_errors(self):
"""Test WbQuantity error handling."""
regex = r'^no amount given$'
with self.assertRaisesRegex(ValueError, regex):
pywikibot.WbQuantity(amount=None, error=1)
def test_WbQuantity_entity_unit(self):
"""Test WbQuantity with entity uri unit."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount=1234, error=1, site=repo,
unit='http://www.wikidata.org/entity/Q712226')
self.assertEqual(q.toWikibase(),
{'amount': '+1234', 'lowerBound': '+1233',
'upperBound': '+1235',
'unit': 'http://www.wikidata.org/entity/Q712226'})
def test_WbQuantity_unit_fromWikibase(self):
"""Test WbQuantity recognising unit from Wikibase output."""
repo = self.get_repo()
q = pywikibot.WbQuantity.fromWikibase({
'amount': '+1234', 'lowerBound': '+1233', 'upperBound': '+1235',
'unit': 'http://www.wikidata.org/entity/Q712226'},
site=repo)
self.assertEqual(q.toWikibase(),
{'amount': '+1234', 'lowerBound': '+1233',
'upperBound': '+1235',
'unit': 'http://www.wikidata.org/entity/Q712226'})
class TestWbQuantityNonDry(WbRepresentationTestCase):
"""
Test Wikibase WbQuantity data type (non-dry).
These can be moved to TestWbQuantity once DrySite has been bumped to
the appropriate version.
"""
def setUp(self):
"""Override setup to store repo and it's version."""
super().setUp()
self.repo = self.get_repo()
self.version = self.repo.mw_version
def test_WbQuantity_unbound(self):
"""Test WbQuantity for value without bounds."""
if self.version < MediaWikiVersion('1.29.0-wmf.2'):
self.skipTest('Wiki version must be 1.29.0-wmf.2 or newer to '
'support unbound uncertainties.')
q = pywikibot.WbQuantity(amount=1234.5, site=self.repo)
self.assertEqual(q.toWikibase(),
{'amount': '+1234.5', 'unit': '1',
'upperBound': None, 'lowerBound': None})
def test_WbQuantity_formatting_unbound(self):
"""Test WbQuantity formatting without bounds."""
if self.version < MediaWikiVersion('1.29.0-wmf.2'):
self.skipTest('Wiki version must be 1.29.0-wmf.2 or newer to '
'support unbound uncertainties.')
q = pywikibot.WbQuantity(amount='0.044405586', site=self.repo)
self.assertEqual(str(q),
'{{\n'
' "amount": "+{val}",\n'
' "lowerBound": null,\n'
' "unit": "1",\n'
' "upperBound": null\n'
'}}'.format(val='0.044405586'))
self.assertEqual(repr(q),
'WbQuantity(amount={val}, '
'upperBound=None, lowerBound=None, '
'unit=1)'.format(val='0.044405586'))
def test_WbQuantity_fromWikibase_unbound(self):
"""Test WbQuantity.fromWikibase() instantiating without bounds."""
if self.version < MediaWikiVersion('1.29.0-wmf.2'):
self.skipTest('Wiki version must be 1.29.0-wmf.2 or newer to '
'support unbound uncertainties.')
q = pywikibot.WbQuantity.fromWikibase({'amount': '+0.0229',
'unit': '1'},
site=self.repo)
self.assertEqual(q.toWikibase(),
{'amount': '+0.0229', 'lowerBound': None,
'upperBound': None, 'unit': '1'})
def test_WbQuantity_ItemPage_unit(self):
"""Test WbQuantity with ItemPage unit."""
if self.version < MediaWikiVersion('1.28-wmf.23'):
self.skipTest('Wiki version must be 1.28-wmf.23 or newer to '
'expose wikibase-conceptbaseuri.')
q = pywikibot.WbQuantity(amount=1234, error=1,
unit=pywikibot.ItemPage(self.repo, 'Q712226'))
self.assertEqual(q.toWikibase(),
{'amount': '+1234', 'lowerBound': '+1233',
'upperBound': '+1235',
'unit': 'http://www.wikidata.org/entity/Q712226'})
def test_WbQuantity_equality(self):
"""Test WbQuantity equality with different unit representations."""
if self.version < MediaWikiVersion('1.28-wmf.23'):
self.skipTest('Wiki version must be 1.28-wmf.23 or newer to '
'expose wikibase-conceptbaseuri.')
a = pywikibot.WbQuantity(
amount=1234, error=1,
unit=pywikibot.ItemPage(self.repo, 'Q712226'))
b = pywikibot.WbQuantity(
amount=1234, error=1,
unit='http://www.wikidata.org/entity/Q712226')
c = pywikibot.WbQuantity(
amount=1234, error=1,
unit='http://test.wikidata.org/entity/Q712226')
d = pywikibot.WbQuantity(
amount=1234, error=2,
unit='http://www.wikidata.org/entity/Q712226')
self.assertEqual(a, b)
self.assertNotEqual(a, c)
self.assertNotEqual(b, c)
self.assertNotEqual(b, d)
def test_WbQuantity_get_unit_item(self):
"""Test getting unit item from WbQuantity."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount=1234, error=1, site=repo,
unit='http://www.wikidata.org/entity/Q123')
self.assertEqual(q.get_unit_item(),
ItemPage(repo, 'Q123'))
def test_WbQuantity_get_unit_item_provide_repo(self):
"""Test getting unit item from WbQuantity, providing repo."""
repo = self.get_repo()
q = pywikibot.WbQuantity(amount=1234, error=1,
unit='http://www.wikidata.org/entity/Q123')
self.assertEqual(q.get_unit_item(repo),
ItemPage(repo, 'Q123'))
def test_WbQuantity_get_unit_item_different_repo(self):
"""Test getting unit item in different repo from WbQuantity."""
repo = self.get_repo()
test_repo = pywikibot.Site('test', 'wikidata')
q = pywikibot.WbQuantity(amount=1234, error=1, site=repo,
unit='http://test.wikidata.org/entity/Q123')
self.assertEqual(q.get_unit_item(test_repo),
ItemPage(test_repo, 'Q123'))
class TestWbMonolingualText(WbRepresentationTestCase):
"""Test Wikibase WbMonolingualText data type."""
dry = True
def test_WbMonolingualText_WbRepresentation_methods(self):
"""Test inherited or extended methods from _WbRepresentation."""
q = pywikibot.WbMonolingualText(
text='Test that basics work', language='en')
self._test_hashable(q)
def test_WbMonolingualText_string(self):
"""Test WbMonolingualText string."""
q = pywikibot.WbMonolingualText(text='Test that basics work',
language='en')
q_dict = {'text': 'Test that basics work', 'language': 'en'}
self.assertEqual(q.toWikibase(), q_dict)
def test_WbMonolingualText_unicode(self):
"""Test WbMonolingualText unicode."""
q = pywikibot.WbMonolingualText(text='Testa det här', language='sv')
q_dict = {'text': 'Testa det här', 'language': 'sv'}
self.assertEqual(q.toWikibase(), q_dict)
def test_WbMonolingualText_equality(self):
"""Test WbMonolingualText equality."""
q = pywikibot.WbMonolingualText(text='Thou shall test this!',
language='en-gb')
self.assertEqual(q, q)
def test_WbMonolingualText_fromWikibase(self):
"""Test WbMonolingualText.fromWikibase() instantiating."""
q = pywikibot.WbMonolingualText.fromWikibase({'text': 'Test this!',
'language': 'en'})
self.assertEqual(q.toWikibase(),
{'text': 'Test this!', 'language': 'en'})
def test_WbMonolingualText_errors(self):
"""Test WbMonolingualText error handling."""
regex = r'^text and language cannot be empty$'
with self.assertRaisesRegex(ValueError, regex):
pywikibot.WbMonolingualText(text='', language='sv')
with self.assertRaisesRegex(ValueError, regex):
pywikibot.WbMonolingualText(text='Test this!', language='')
with self.assertRaisesRegex(ValueError, regex):
pywikibot.WbMonolingualText(text=None, language='sv')
class TestWikibaseParser(WikidataTestCase):
"""Test passing various datatypes to wikibase parser."""
def test_wbparse_strings(self):
"""Test that strings return unchanged."""
test_list = ['test string', 'second test']
parsed_strings = self.site.parsevalue('string', test_list)
self.assertEqual(parsed_strings, test_list)
def test_wbparse_time(self):
"""Test parsing of a time value."""
parsed_date = self.site.parsevalue(
'time', ['1994-02-08'], {'precision': 9})[0]
self.assertEqual(parsed_date['time'], '+1994-02-08T00:00:00Z')
self.assertEqual(parsed_date['precision'], 9)
def test_wbparse_quantity(self):
"""Test parsing of quantity values."""
parsed_quantities = self.site.parsevalue(
'quantity',
['1.90e-9+-0.20e-9', '1000000.00000000054321+-0', '-123+-1',
'2.70e34+-1e32'])
self.assertEqual(parsed_quantities[0]['amount'], '+0.00000000190')
self.assertEqual(parsed_quantities[0]['upperBound'], '+0.00000000210')
self.assertEqual(parsed_quantities[0]['lowerBound'], '+0.00000000170')
self.assertEqual(parsed_quantities[1]['amount'],
'+1000000.00000000054321')
self.assertEqual(parsed_quantities[1]['upperBound'],
'+1000000.00000000054321')
self.assertEqual(parsed_quantities[1]['lowerBound'],
'+1000000.00000000054321')
self.assertEqual(parsed_quantities[2]['amount'], '-123')
self.assertEqual(parsed_quantities[2]['upperBound'], '-122')
self.assertEqual(parsed_quantities[2]['lowerBound'], '-124')
self.assertEqual(parsed_quantities[3]['amount'],
'+27000000000000000000000000000000000')
self.assertEqual(parsed_quantities[3]['upperBound'],
'+27100000000000000000000000000000000')
self.assertEqual(parsed_quantities[3]['lowerBound'],
'+26900000000000000000000000000000000')
def test_wbparse_raises_valueerror(self):
"""Test invalid value condition."""
with self.assertRaises(ValueError):
self.site.parsevalue('quantity', ['Not a quantity'])
class TestWbGeoShapeNonDry(WbRepresentationTestCase):
"""
Test Wikibase WbGeoShape data type (non-dry).
These require non dry tests due to the page.exists() call.
"""