-
Notifications
You must be signed in to change notification settings - Fork 26
/
test_nocasedict.py
executable file
·990 lines (863 loc) · 28.8 KB
/
test_nocasedict.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
"""
Test the _nocasedict module.
"""
from __future__ import absolute_import
import unittest
import warnings
import six
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import pytest
import pytest_extensions
from pywbem._nocasedict import NocaseDict
class NonCompare(object):
# pylint: disable=too-few-public-methods
"""
Class that raises TypeError when comparing for equality or hashing.
"""
def __eq__(self, other):
raise TypeError("Cannot compare %s to %s" % (type(self), type(other)))
def __ne__(self, other):
raise TypeError("Cannot compare %s to %s" % (type(self), type(other)))
def __hash__(self):
raise TypeError("Cannot hash %s" % type(self))
TESTCASES_NOCASEDICT_INIT = [
# Testcases for NocaseDict.__init__().
#
# Each list item is a testcase tuple with these items:
# * desc: Short testcase description.
# * kwargs: Keyword arguments for the test function:
# * init_args: Tuple of positional arguments to NocaseDict().
# * init_kwargs: Dict of keyword arguments to NocaseDict().
# * exp_dict: Expected resulting dictionary, as OrderedDict.
# * exp_exc_types: Expected exception type(s), or None.
# * exp_warn_types: Expected warning type(s), or None.
# * condition: Boolean condition for testcase to run, or 'pdb' for debugger
# Empty NocaseDict
(
"Empty dict from no args",
dict(
init_args=(),
init_kwargs={},
exp_dict=OrderedDict(),
verify_order=True,
),
None, None, True
),
(
"Empty dict from None as positional arg",
dict(
init_args=(None,),
init_kwargs={},
exp_dict=OrderedDict(),
verify_order=True,
),
None, None, True
),
(
"Empty dict from empty list as positional arg",
dict(
init_args=(list(),),
init_kwargs={},
exp_dict=OrderedDict(),
verify_order=True,
),
None, None, True
),
(
"Empty dict from empty tuple as positional arg",
dict(
init_args=(tuple(),),
init_kwargs={},
exp_dict=OrderedDict(),
verify_order=True,
),
None, None, True
),
(
"Empty dict from empty dict as positional arg",
dict(
init_args=(dict(),),
init_kwargs={},
exp_dict=OrderedDict(),
verify_order=True,
),
None, None, True
),
(
"Empty dict from empty NocaseDict as positional arg",
dict(
init_args=(NocaseDict(),),
init_kwargs={},
exp_dict=OrderedDict(),
verify_order=True,
),
None, None, True
),
# Non-empty NocaseDict
(
"Dict from list as positional arg",
dict(
init_args=([('Dog', 'Cat'), ('Budgie', 'Fish')],),
init_kwargs={},
exp_dict=OrderedDict([('Dog', 'Cat'), ('Budgie', 'Fish')]),
verify_order=True,
),
None, None, True
),
(
"Dict from tuple as positional arg",
dict(
init_args=((('Dog', 'Cat'), ('Budgie', 'Fish')),),
init_kwargs={},
exp_dict=OrderedDict([('Dog', 'Cat'), ('Budgie', 'Fish')]),
verify_order=True,
),
None, None, True
),
(
"Dict from dict as positional arg",
dict(
init_args=({'Dog': 'Cat', 'Budgie': 'Fish'},),
init_kwargs={},
exp_dict=OrderedDict([('Dog', 'Cat'), ('Budgie', 'Fish')]),
verify_order=False,
),
None, UserWarning, True
),
(
"Dict from keyword args",
dict(
init_args=(),
init_kwargs={'Dog': 'Cat', 'Budgie': 'Fish'},
exp_dict=OrderedDict([('Dog', 'Cat'), ('Budgie', 'Fish')]),
verify_order=False,
),
None, UserWarning, True
),
(
"Dict from list as positional arg and keyword args",
dict(
init_args=([('Dog', 'Cat')],),
init_kwargs={'Budgie': 'Fish'},
exp_dict=OrderedDict([('Dog', 'Cat'), ('Budgie', 'Fish')]),
verify_order=True,
),
None, None, True
),
(
"Dict from tuple as positional arg and keyword args",
dict(
init_args=((('Dog', 'Cat'),),),
init_kwargs={'Budgie': 'Fish'},
exp_dict=OrderedDict([('Dog', 'Cat'), ('Budgie', 'Fish')]),
verify_order=True,
),
None, None, True
),
(
"Dict from dict as positional arg and keyword args",
dict(
init_args=({'Dog': 'Cat'},),
init_kwargs={'Budgie': 'Fish'},
exp_dict=OrderedDict([('Dog', 'Cat'), ('Budgie', 'Fish')]),
verify_order=True,
),
None, None, True
),
# Error cases
(
"String type as positional arg",
dict(
init_args=('illegal',),
init_kwargs={},
exp_dict=None,
verify_order=None,
),
TypeError, None, True
),
(
"Two positional args",
dict(
init_args=(list(), list()),
init_kwargs={},
exp_dict=None,
verify_order=None,
),
TypeError, None, True
),
]
@pytest.mark.parametrize(
"desc, kwargs, exp_exc_types, exp_warn_types, condition",
TESTCASES_NOCASEDICT_INIT)
@pytest_extensions.test_function
def test_NocaseDict_init(testcase,
init_args, init_kwargs, exp_dict, verify_order):
"""
Test function for NocaseDict.__init__().
"""
# The code to be tested
act_dict = NocaseDict(*init_args, **init_kwargs)
# Verify that an exception raised in this function is not mistaken
# to be the expected exception
assert testcase.exp_exc_types is None
# The verification below also uses some NocaseDict features, but that is
# unavoidable if we want to work through the public interface:
act_items = []
# Next line uses NocaseDict iteration:
for key in act_dict:
# Next line uses NocaseDict access by key:
act_value = act_dict[key]
assert key in exp_dict, "Unexpected extra key %r" % key
exp_value = exp_dict[key]
assert act_value == exp_value, "Unexpected value at key %r" % key
act_items.append((key, act_value))
exp_items = []
for key in exp_dict:
exp_value = exp_dict[key]
# Next line uses NocaseDict containment test:
assert key in act_dict, "Unexpected missing key %r" % key
# Next line uses NocaseDict access by key:
act_value = act_dict[key]
assert act_value == exp_value, "Unexpected value at key %r" % key
exp_items.append((key, exp_value))
if verify_order:
assert act_items == exp_items, "Unexpected order of items"
class BaseTest(unittest.TestCase):
"""Base class for following unit test. Does common setup which
creates a NoCaseDict.
"""
def setUp(self):
"""unittest setUp creates NoCaseDict"""
self.dic = NocaseDict()
self.dic['Dog'] = 'Cat'
self.dic['Budgie'] = 'Fish'
self.order_tuples = (
('Dog', 'Cat'),
('Budgie', 'Fish'),
('Ham', 'Jam'),
('Sofi', 'Blue'),
('Gabi', 'Red'),
)
class TestGetitem(BaseTest):
"""Tests for getitem"""
def test_all(self):
"""All tests"""
self.assertTrue(self.dic['dog'] == 'Cat')
self.assertTrue(self.dic['DOG'] == 'Cat')
try:
self.dic['notfound']
except KeyError:
pass
else:
self.fail("KeyError was unexpectedly not thrown.")
class TestLen(BaseTest):
"""Tests for len of dict"""
def test_all(self):
"""Test method"""
self.assertTrue(len(self.dic) == 2)
class TestSetitem(BaseTest):
"""Test setting items"""
def test_all(self):
"""All setitem tests"""
self.dic['DOG'] = 'Kitten'
self.assertTrue(self.dic['DOG'] == 'Kitten')
self.assertTrue(self.dic['Dog'] == 'Kitten')
self.assertTrue(self.dic['dog'] == 'Kitten')
# Check that using a non-string key raises an exception
try:
self.dic[1234] = '1234'
except TypeError:
pass
else:
self.fail('TypeError expected')
class TestDelitem(BaseTest):
"""Class for del items from dictionary"""
def test_all(self):
"""All tests"""
del self.dic['DOG']
del self.dic['budgie']
self.assertTrue(self.dic.keys() == [])
try:
del self.dic['notfound']
except KeyError:
pass
else:
self.fail("KeyError was unexpectedly not thrown.")
class TestHasKey(BaseTest):
"""Class to test haskey on dict"""
def test_all(self):
"""Method to test haskey"""
self.assertTrue('DOG' in self.dic)
self.assertTrue('budgie' in self.dic)
try:
1234 in self.dic
except TypeError:
pass
else:
self.fail('TypeError expected')
class TestKeys(BaseTest):
"""Class for TestKeys method"""
def test_all(self):
"""All tests in single method"""
keys = self.dic.keys()
animals = ['Budgie', 'Dog']
for ani in animals:
self.assertTrue(ani in keys)
keys.remove(ani)
self.assertTrue(keys == [])
class TestValues(BaseTest):
"""Class for values tests"""
def test_all(self):
"""Test all for TestValues"""
values = self.dic.values()
animals = ['Cat', 'Fish']
for ani in animals:
self.assertTrue(ani in values)
values.remove(ani)
self.assertTrue(values == [])
class TestItems(BaseTest):
"""Class for Test items"""
def test_all(self):
"""All tests for item"""
items = self.dic.items()
animals = [('Dog', 'Cat'), ('Budgie', 'Fish')]
for ani in animals:
self.assertTrue(ani in items)
items.remove(ani)
self.assertTrue(items == [])
class TestClear(BaseTest):
"""Class for dict clear method"""
def test_all(self):
"""All clear method tests"""
self.dic.clear()
self.assertTrue(len(self.dic) == 0)
class TestUpdate(BaseTest):
"""Class for test update method"""
def test_all(self):
"""All methods for TestUpdate"""
self.dic.clear()
self.dic.update({'Chicken': 'Ham'})
self.assertTrue(self.dic.keys() == ['Chicken'])
self.assertTrue(self.dic.values() == ['Ham'])
self.dic.clear()
self.dic.update({'Chicken': 'Ham'}, {'Dog': 'Cat'})
keys = self.dic.keys()
vals = self.dic.values()
keys = list(keys)
vals = list(vals)
keys.sort()
vals.sort()
self.assertTrue(keys == ['Chicken', 'Dog'])
self.assertTrue(vals == ['Cat', 'Ham'])
self.dic.update([('Chicken', 'Egg')], {'Fish': 'Eel'})
self.assertTrue(self.dic['chicken'] == 'Egg')
self.assertTrue(self.dic['fish'] == 'Eel')
self.dic.update({'Fish': 'Salmon'}, Cow='Beef')
self.assertTrue(self.dic['fish'] == 'Salmon')
self.assertTrue(self.dic['Cow'] == 'Beef')
self.assertTrue(self.dic['COW'] == 'Beef')
self.assertTrue(self.dic['cow'] == 'Beef')
class TestCopy(BaseTest):
"""Class to test dict copy"""
def test_all(self):
"""All tests for dict copy"""
cp = self.dic.copy()
self.assertEqual(cp, self.dic)
self.assertTrue(isinstance(cp, NocaseDict))
cp['Dog'] = 'Kitten'
self.assertTrue(self.dic['Dog'] == 'Cat')
self.assertTrue(cp['Dog'] == 'Kitten')
class TestGet(BaseTest):
"""Class to test get method"""
def test_all(self):
"""Test get method"""
self.assertTrue(self.dic.get('Dog', 'Chicken') == 'Cat')
self.assertTrue(self.dic.get('Ningaui') is None)
self.assertTrue(self.dic.get('Ningaui', 'Chicken') == 'Chicken')
class TestSetDefault(BaseTest):
"""Class for setdefault test methods"""
def test_all(self):
"""All tests for setdefault of dict"""
self.dic.setdefault('Dog', 'Kitten')
self.assertTrue(self.dic['Dog'] == 'Cat')
self.dic.setdefault('Ningaui', 'Chicken')
self.assertTrue(self.dic['Ningaui'] == 'Chicken')
class TestPopItem(BaseTest):
"""Class for PopItem"""
def test_all(self):
"""This test does nothing"""
pass
TESTCASES_NOCASEDICT_EQUAL_HASH = [
# Testcases for NocaseDict.__eq__(), __ne__(), __hash__().
# Each list item is a testcase tuple with these items:
# * desc: Short testcase description.
# * kwargs: Keyword arguments for the test function:
# * obj1: CIMInstanceName object #1 to use.
# * obj2: CIMInstanceName object #2 to use.
# * exp_obj_equal: Expected equality of the objects.
# * exp_exc_types: Expected exception type(s), or None.
# * exp_warn_types: Expected warning type(s), or None.
# * condition: Boolean condition for testcase to run, or 'pdb' for debugger
(
"Empty dictionary",
dict(
obj1=NocaseDict([]),
obj2=NocaseDict([]),
exp_obj_equal=True,
),
None, None, True
),
(
"One item, keys and values equal",
dict(
obj1=NocaseDict([('k1', 'v1')]),
obj2=NocaseDict([('k1', 'v1')]),
exp_obj_equal=True,
),
None, None, True
),
(
"One item, keys equal, values different",
dict(
obj1=NocaseDict([('k1', 'v1')]),
obj2=NocaseDict([('k1', 'v1_x')]),
exp_obj_equal=False,
),
None, None, True
),
(
"One item, keys different, values equal",
dict(
obj1=NocaseDict([('k1', 'v1')]),
obj2=NocaseDict([('k2', 'v1')]),
exp_obj_equal=False,
),
None, None, True
),
(
"One item, keys equal, values both None",
dict(
obj1=NocaseDict([('k1', None)]),
obj2=NocaseDict([('k1', None)]),
exp_obj_equal=True,
),
None, None, True
),
(
"One item, keys different lexical case, values equal",
dict(
obj1=NocaseDict([('K1', 'v1')]),
obj2=NocaseDict([('k1', 'v1')]),
exp_obj_equal=True,
),
None, None, True
),
(
"Two equal items, in same order",
dict(
obj1=NocaseDict([('k1', 'v1'), ('k2', 'v2')]),
obj2=NocaseDict([('k1', 'v1'), ('k2', 'v2')]),
exp_obj_equal=True,
),
None, None, True
),
(
"Two items, keys different lexical case, in same order",
dict(
obj1=NocaseDict([('K1', 'v1'), ('k2', 'v2')]),
obj2=NocaseDict([('k1', 'v1'), ('K2', 'v2')]),
exp_obj_equal=True,
),
None, None, True
),
(
"Two equal items, in different order",
dict(
obj1=NocaseDict([('k1', 'v1'), ('k2', 'v2')]),
obj2=NocaseDict([('k2', 'v2'), ('k1', 'v1')]),
exp_obj_equal=True,
),
None, None, True
),
(
"Two items, keys different lexical case, in different order",
dict(
obj1=NocaseDict([('k1', 'v1'), ('K2', 'v2')]),
obj2=NocaseDict([('k2', 'v2'), ('K1', 'v1')]),
exp_obj_equal=True,
),
None, None, True
),
(
"Comparing unicode value with binary value",
dict(
obj1=NocaseDict([('k1', b'v1')]),
obj2=NocaseDict([('k2', u'v2')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Matching unicode key with string key",
dict(
obj1=NocaseDict([('k1', 'v1')]),
obj2=NocaseDict([(u'k2', 'v2')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Higher key missing",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Budgie', 'Fish')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Lower key missing",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Dog', 'Cat')]),
exp_obj_equal=False,
),
None, None, True
),
(
"First non-matching key is less. But longer size!",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Budgie', 'Fish'), ('Curly', 'Snake'),
('Cozy', 'Dog')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Only non-matching keys that are less. But longer size!",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Alf', 'F'), ('Anton', 'S'), ('Aussie', 'D')]),
exp_obj_equal=False,
),
None, None, True
),
(
"First non-matching key is greater. But shorter size!",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Budgio', 'Fish')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Only non-matching keys that are greater. But shorter size!",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Zoe', 'F')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size. First non-matching key is less",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Budgie', 'Fish'), ('Curly', 'Snake')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size. Only non-matching keys that are less",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Alf', 'F'), ('Anton', 'S')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size. Only non-matching keys that are greater",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Zoe', 'F'), ('Zulu', 'S')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size, only matching keys. First non-matching value is less",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Car')]),
exp_obj_equal=False,
),
None, None, True
),
(
"Same size, only matching keys. First non-matching value is greater",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Caz')]),
exp_obj_equal=False,
),
None, None, True
),
]
TESTCASES_NOCASEDICT_EQUAL = [
# Testcases for NocaseDict.__eq__(), __ne__().
# Each list item is a testcase tuple with these items:
# * desc: Short testcase description.
# * kwargs: Keyword arguments for the test function:
# * obj1: CIMInstanceName object #1 to use.
# * obj2: CIMInstanceName object #2 to use.
# * exp_obj_equal: Expected equality of the objects.
# * exp_exc_types: Expected exception type(s), or None.
# * exp_warn_types: Expected warning type(s), or None.
# * condition: Boolean condition for testcase to run, or 'pdb' for debugger
(
"A value raises TypeError when compared (and equal still succeeds)",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Budgie', NonCompare()), ('Dog', 'Cat')]),
exp_obj_equal=False,
),
None, None, True
),
]
TESTCASES_NOCASEDICT_HASH = [
# Testcases for NocaseDict.__hash__().
# Each list item is a testcase tuple with these items:
# * desc: Short testcase description.
# * kwargs: Keyword arguments for the test function:
# * obj1: CIMInstanceName object #1 to use.
# * obj2: CIMInstanceName object #2 to use.
# * exp_obj_equal: Expected equality of the objects.
# * exp_exc_types: Expected exception type(s), or None.
# * exp_warn_types: Expected warning type(s), or None.
# * condition: Boolean condition for testcase to run, or 'pdb' for debugger
(
"A value raises TypeError when compared (and hash fails)",
dict(
obj1=NocaseDict([('Budgie', 'Fish'), ('Dog', 'Cat')]),
obj2=NocaseDict([('Budgie', NonCompare()), ('Dog', 'Cat')]),
exp_obj_equal=False,
),
TypeError, None, True
),
]
@pytest.mark.parametrize(
"desc, kwargs, exp_exc_types, exp_warn_types, condition",
TESTCASES_NOCASEDICT_EQUAL_HASH + TESTCASES_NOCASEDICT_EQUAL)
@pytest_extensions.test_function
def test_NocaseDict_eq(testcase,
obj1, obj2, exp_obj_equal):
"""
Test function for NocaseDict.__eq__().
"""
# Double check they are different objects
assert id(obj1) != id(obj2)
# The code to be tested
eq1 = (obj1 == obj2)
eq2 = (obj2 == obj1)
# Verify that an exception raised in this function is not mistaken
# to be the expected exception
assert testcase.exp_exc_types is None
assert eq1 == exp_obj_equal
assert eq2 == exp_obj_equal
@pytest.mark.parametrize(
"desc, kwargs, exp_exc_types, exp_warn_types, condition",
TESTCASES_NOCASEDICT_EQUAL_HASH + TESTCASES_NOCASEDICT_EQUAL)
@pytest_extensions.test_function
def test_NocaseDict_ne(testcase,
obj1, obj2, exp_obj_equal):
"""
Test function for NocaseDict.__ne__().
"""
# Double check they are different objects
assert id(obj1) != id(obj2)
# The code to be tested
ne1 = (obj1 != obj2)
ne2 = (obj2 != obj1)
# Verify that an exception raised in this function is not mistaken
# to be the expected exception
assert testcase.exp_exc_types is None
assert ne1 != exp_obj_equal
assert ne2 != exp_obj_equal
@pytest.mark.parametrize(
"desc, kwargs, exp_exc_types, exp_warn_types, condition",
TESTCASES_NOCASEDICT_EQUAL_HASH + TESTCASES_NOCASEDICT_HASH)
@pytest_extensions.test_function
def test_NocaseDict_hash(testcase,
obj1, obj2, exp_obj_equal):
"""
Test function for NocaseDict.__hash__().
"""
# Double check they are different objects
assert id(obj1) != id(obj2)
# The code to be tested
hash1 = hash(obj1)
hash2 = hash(obj2)
# Verify that an exception raised in this function is not mistaken
# to be the expected exception
assert testcase.exp_exc_types is None
if exp_obj_equal:
assert hash1 == hash2
else:
assert hash1 != hash2
class TestOrdering(BaseTest):
"""Verify that ordering comparisons between NocaseDict instances
issue a deprecation warning, and for Python 3, in addition raise
TypeError."""
def assertWarning(self, comp_str):
"""Common function for assert warning"""
with warnings.catch_warnings(record=True) as wlist:
warnings.simplefilter("always")
if six.PY2:
eval(comp_str) # pylint: disable=eval-used
else:
try:
eval(comp_str) # pylint: disable=eval-used
except TypeError as exc:
msg = str(exc)
if "not supported between instances" not in msg and \
"unorderable types" not in msg:
self.fail("Applying ordering to a dictionary in "
"Python 3 did raise TypeError but with an "
"unexpected message: %s" % msg)
except Exception as exc: # pylint: disable=broad-except
msg = str(exc)
self.fail("Applying ordering to a dictionary in Python 3 "
"did not raise TypeError, but %s: %s" %
(exc.__class__.__name__, msg))
else:
self.fail("Applying ordering to a dictionary in Python 3 "
"succeeded (should not happen)")
assert len(wlist) >= 1
assert issubclass(wlist[-1].category, DeprecationWarning)
assert "deprecated" in str(wlist[-1].message)
def test_all(self):
"""Test for the compare options that should generate assertWarning"""
self.assertWarning("self.dic < self.dic")
self.assertWarning("self.dic <= self.dic")
self.assertWarning("self.dic > self.dic")
self.assertWarning("self.dic >= self.dic")
class TestContains(BaseTest):
"""Class for dict contains functionality"""
def test_all(self):
"""Method for test dict contains functionality"""
self.assertTrue('dog' in self.dic)
self.assertTrue('Dog' in self.dic)
self.assertTrue('Cat' not in self.dic)
class TestForLoop(BaseTest):
"""Class for test for loop with dictionary"""
def test_all(self):
"""Test method for TestForLoop"""
keys = set()
for key in self.dic:
keys.add(key)
self.assertEqual(keys, set(['Budgie', 'Dog']))
def test_order_preservation(self):
"""Test order preservation of for loop on dict"""
dic = NocaseDict()
for key, value in self.order_tuples:
dic[key] = value
i = 0
for key in dic:
item = (key, dic[key])
exp_item = self.order_tuples[i]
self.assertEqual(item, exp_item)
i += 1
class TestIterkeys(BaseTest):
"""Class for iterkeys test"""
def test_all(self):
"""iterkeys test method"""
keys = set()
for key in self.dic.iterkeys():
keys.add(key)
self.assertEqual(keys, set(['Budgie', 'Dog']))
def test_order_preservation(self):
"""Test order preservation of iterkeys()"""
dic = NocaseDict()
for key, value in self.order_tuples:
dic[key] = value
i = 0
for key in dic.iterkeys():
item = (key, dic[key])
exp_item = self.order_tuples[i]
self.assertEqual(item, exp_item)
i += 1
class TestItervalues(BaseTest):
"""Class for test itervalues test"""
def test_all(self):
"""itervalues test method"""
vals = set()
for val in self.dic.itervalues():
vals.add(val)
self.assertEqual(vals, set(['Cat', 'Fish']))
def test_order_preservation(self):
"""Test order preservation of itervalues()"""
dic = NocaseDict()
for key, value in self.order_tuples:
dic[key] = value
i = 0
for value in dic.itervalues():
exp_value = self.order_tuples[i][1]
self.assertEqual(value, exp_value)
i += 1
class TestIteritems(BaseTest):
"""Class to test iteritems for dict"""
def test_all(self):
"""Method for test iteritems for dict"""
items = set()
for item in self.dic.iteritems():
items.add(item)
self.assertEqual(items, set([('Budgie', 'Fish'), ('Dog', 'Cat')]))
def test_order_preservation(self):
"""Test order preservation of iteritems()"""
dic = NocaseDict()
for key, value in self.order_tuples:
dic[key] = value
i = 0
for item in dic.iteritems():
exp_item = self.order_tuples[i]
self.assertEqual(item, exp_item)
i += 1
class TestRepr(unittest.TestCase):
"""Class to test repr functionality for NocaseDict"""
def test_reliable_order(self):
"""Test that repr() has a reliable result for two dicts with the same
insertion order."""
dic1 = NocaseDict()
dic1['Budgie'] = 'Fish'
dic1['Foo'] = 'Bla'
dic1['Dog'] = 'Cat'
dic2 = NocaseDict()
dic2['Budgie'] = 'Fish'
dic2['Foo'] = 'Bla'
dic2['Dog'] = 'Cat'
self.assertEqual(repr(dic1), repr(dic2))
class Test_unnamed_keys(object):
# pylint: disable=too-few-public-methods
"""Class to test unnamed keys (key is None) for NocaseDict"""
def test_unnamed_keys(self):
# pylint: disable=no-self-use
"""Test unnamed keys."""
dic = NocaseDict()
dic.allow_unnamed_keys = True
dic[None] = 'a'
assert None in dic
assert len(dic) == 1
a_val = dic[None]
assert a_val == 'a'
del dic[None]
assert None not in dic
assert not dic
if __name__ == '__main__':
unittest.main()