-
Notifications
You must be signed in to change notification settings - Fork 9
/
test_cleverdict.py
1470 lines (1297 loc) · 53.9 KB
/
test_cleverdict.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
import json
import os
from collections import UserDict
from itertools import permutations
from pathlib import Path
from textwrap import dedent
import keyring
import pytest
from cleverdict import CleverDict, Expand, all_aliases
def example_save_function(self, name=None, value=None):
"""
Example of a custom function which can be called by self._save()
whenever the value of a CleverDict instance is created or changed.
Required arguments are: self, name: any and value: any
Specify this (or any other) function as the default 'save' function as follows:
CleverDict.save = example_save_function
"""
if name != "_aliases":
output = f"Notional save to database: .{name} = {value} {type(value)}"
with open("example.log", "a") as file:
file.write(output + "\n")
def invalid_save_function(self, key, value):
pass
def example_delete_function(self, name=None):
"""Example"""
output = f"Notional DELETE to database: .{name}"
with open("example.log", "a") as file:
file.write(output + "\n")
def invalid_delete_function(self, name, value):
pass
def get_data(path):
with open(path, "r") as file:
data = file.read()
return data
def delete_log():
try:
os.remove("example.log")
return True
except FileNotFoundError:
return False
class Test_Initialisation:
def test_creation_using_existing_dict(self):
"""CleverDicts can be creates from existing dictionaries"""
x = CleverDict({"total": 6, "usergroup": "Knights of Ni"})
assert x.total == 6
assert x["total"] == 6
assert x.usergroup == "Knights of Ni"
assert x["usergroup"] == "Knights of Ni"
def test_creation_using_existing_UserDict(self):
"""CleverDicts can be creates from existing UserDict objects"""
u = UserDict({"total": 6, "usergroup": "Knights of Ni"})
x = CleverDict(u)
assert x.total == 6
assert x["total"] == 6
assert x.usergroup == "Knights of Ni"
assert x["usergroup"] == "Knights of Ni"
def test_creation_using_keyword_arguments(self):
"""CleverDicts can be created using keyword assignment"""
x = CleverDict(created="today", review="tomorrow")
assert x.created == "today"
assert x["created"] == "today"
assert x.review == "tomorrow"
assert x["review"] == "tomorrow"
def test_creation_using_vars(self):
"""Works for 'simple' data objects i.e. no methods just data"""
class My_class:
pass
m = My_class()
m.subject = "Python"
x = CleverDict(vars(m))
assert x.subject == "Python"
assert x["subject"] == "Python"
def test_creation_using_fromkeys(self):
"""Works for initiating >1 keys with the same value"""
x = CleverDict().fromkeys(["a", 1, "what?"], "val")
assert x.a == "val"
assert x._1 == "val"
assert x.what_ == "val"
def test_creation_using_list(self):
"""Works for initiating using a list of iterables"""
x = CleverDict([(1, "one"), [2, "two"], (3, "three")])
assert x._1 == "one"
assert x._2 == "two"
assert x._3 == "three"
def test_create_with_alias_as_key_name_is_not_possible_and_raises_a_runtime_warning(self):
data = {
"total": 6,
"usergroup": "Knights of Ni",
"_aliases": ["Kn8 of Ni", 'Knights Who Say "Ni!"'],
}
with pytest.raises(RuntimeWarning):
CleverDict(data)
with pytest.raises(RuntimeWarning):
CleverDict(**data)
with pytest.raises(RuntimeWarning):
CleverDict(data.items())
with pytest.raises(RuntimeWarning):
CleverDict().fromkeys(["total", "usergroup", "_aliases"], "val")
class Test_Core_Features:
def test_tolist(self):
"""
Create a list of (k,v) tuples e.g. for serialising dictionaries
with numeric keys (which isn't supported in json.dumps/.loads)
"""
x = CleverDict({1: "one", 2: "two"})
assert x.to_list() == [(1, "one"), (2, "two")]
def test_use_as_dict(self):
d = dict.fromkeys((0, 1, 23, "what?", "a"), "test")
x = CleverDict(d)
x.setattr_direct("b", 2)
assert dict(x) == d
def test_add_alias_delete_alias(self):
"""
Aliases are created automatically after expanding 1, True
for example. add_alias() and delete_alias() allow us to specify
additional attribute names as aliases, such that if the value of one
changes, the value changes for all.
It is not possible to delete a key.
"""
x = CleverDict({"red": "a lovely colour", "blue": "a cool colour"})
alias_list = ["crimson", "burgundy", "scarlet", "normalise~me"]
x.add_alias("red", alias_list[0])
x.add_alias("red", alias_list)
# setting an alias that is already defined for another key is not allowed
with pytest.raises(KeyError):
x.add_alias("blue", alias_list[0])
# setting via an alias is also valid
x.add_alias("scarlet", "rood")
assert x.rood == "a lovely colour"
for alias in alias_list[:-1]:
assert getattr(x, alias) == "a lovely colour"
assert x[alias] == "a lovely colour"
assert getattr(x, "normalise_me") == "a lovely colour"
assert x["normalise_me"] == "a lovely colour"
# Updating one alias (or primary Key) should update all:
x.burgundy = "A RICH COLOUR"
assert x.scarlet == "A RICH COLOUR"
x.delete_alias(["scarlet"])
with pytest.raises(AttributeError):
x.scarlet
assert x.crimson == "A RICH COLOUR"
x.crimson = "the best colour of all"
assert x.burgundy == "the best colour of all"
with pytest.raises(KeyError):
x.delete_alias(["scarlet"])
# can't delete the key element
with pytest.raises(KeyError):
x.delete_alias("red")
# test 'expansion' of alias
x.add_alias("red", True)
assert x._True is x[True] is x._1 is x[1] is x["red"]
x = CleverDict()
x["2"] = 1
x.add_alias("2", True)
assert x.get_aliases("2") == ["2", "_2", True, "_1", "_True"]
# removes True, '_1' and '_True'
x.delete_alias(True)
assert x.get_aliases("2") == ["2", "_2"]
x = CleverDict()
x["2"] = 1
x.add_alias("2", True)
assert x.get_aliases("2") == ["2", "_2", True, "_1", "_True"]
# only remove True,not '_1' and '_True'
with Expand(False):
x.delete_alias(True)
assert x.get_aliases("2") == ["2", "_2", "_1", "_True"]
def test_value_change(self):
"""New attribute values should update dictionary keys & vice versa"""
x = CleverDict()
x.life = 42
x["life"] = 43
assert x.life == 43
assert x["life"] == 43
x.life = 42
assert x.life == 42
assert x["life"] == 42
x["1"] = 10
assert x["1"] == 10
assert x["_1"] == 10
assert x._1 == 10
x["_1"] = 11
assert x["1"] == 11
assert x["_1"] == 11
assert x._1 == 11
x._1 = 12
assert x["1"] == 12
assert x["_1"] == 12
assert x._1 == 12
# can't double assign
with pytest.raises(KeyError):
x["+1"] = 1
x.setattr_direct("who", "Peter")
x.who = "Ruud"
assert x.who == "Ruud"
def test_info(self, capsys):
global c # globals are not 'seen' by info()
z = b = a = c = CleverDict.fromkeys((0, 1, 2, "a", "what?", "return"), 0)
c.add_alias(1, "one")
c.delete_alias("_True")
c.setattr_direct("b", "B")
c.info() # this prints to stdout
out, err = capsys.readouterr()
assert out == dedent(
"""\
CleverDict:
a is b is z
a[0] == a['_0'] == a['_False'] == a._0 == a._False == 0
a[1] == a['_1'] == a['one'] == a._1 == a.one == 0
a[2] == a['_2'] == a._2 == 0
a['a'] == a.a == 0
a['what?'] == a['what_'] == a.what_ == 0
a['return'] == a['_return'] == a._return == 0
a.b == 'B'
"""
)
z = b = a = c = CleverDict.fromkeys(["a"], "A")
assert c.info(as_str=True) == "CleverDict:\n a is b is z\n a['a'] == a.a == 'A'"
del a
assert c.info(as_str=True) == "CleverDict:\n b is z\n b['a'] == b.a == 'A'"
del b
assert c.info(as_str=True) == "CleverDict:\n z['a'] == z.a == 'A'"
del z
assert c.info(as_str=True) == "CleverDict:\n x['a'] == x.a == 'A'"
class Test_Misc:
def test_exclude(self):
"""exclude=(Marshmallow syntax) should act as an alias for ignore="""
x = CleverDict({"Yes": "include me", "No": "exclude/ignore me"})
for (
func
) in "__repr__() to_json() to_dict() to_list() to_lines() info(,as_str=True)".split():
ignore = eval("x." + func.replace("(", "(ignore=['No']"))
exclude = eval("x." + func.replace("(", "(exclude=['No']"))
assert ignore == exclude
def test_only(self):
"""only=[list] should return output ONLY matching the given keys"""
x = CleverDict({"Apples": "Green", "Bananas": "Yellow", "Oranges": "Purple"})
a_and_o = CleverDict({"Apples": "Green", "Oranges": "Purple"})
for func in "__repr__ to_json to_dict to_list to_lines info".split():
as_str = {"as_str": True} if func == "info" else {}
result1 = getattr(x, func)(only=["Apples", "Oranges"], **as_str)
result2 = getattr(a_and_o, func)(**({"as_str": True} if func == "info" else {}))
assert str(result1) == str(result2).replace("a_and_o", "x")
def test_only_edge_cases(self):
x = CleverDict({"Apples": "Green", "Bananas": "Yellow", "Oranges": "Purple"})
with pytest.raises(TypeError):
x.to_list(exclude=[], only=[])
x.to_list(ignore=[], only=[])
x.to_list(exclude=[], ignore=[])
x.to_list(exclude=[], ignore=[], only=[])
x.to_list(
ignore=CleverDict.ignore_internals,
exclude=CleverDict.ignore_internals,
only=CleverDict.ignore_internals,
)
x = CleverDict({0: "Zero", 1: "One"})
assert x.to_list(only=[1]) == [(1, "One")]
assert x.to_list(ignore=[0]) == [(1, "One")]
assert x.to_list(exclude=[0]) == [(1, "One")]
assert x.to_list(only=1) == [(1, "One")]
assert x.to_list(ignore=0) == [(1, "One")]
assert x.to_list(exclude=0) == [(1, "One")]
def test_permissive(self):
"""
only= exclude= ignore= should accept iterables AND single items strings.
"""
x = CleverDict({"Apples": "Green", "Bananas": "Yellow", "Oranges": "Purple"})
assert x.__repr__(only="Apples") == x.__repr__(only=["Apples"])
assert x.__repr__(ignore="Apples") == x.__repr__(ignore=["Apples"])
assert x.to_json(ignore="Apples") == x.to_json(ignore=["Apples"])
assert x.to_json(exclude="Apples") == x.to_json(exclude=["Apples"])
assert x.to_dict(exclude="Apples") == x.to_dict(exclude=["Apples"])
assert x.to_dict(ignore="Apples") == x.to_dict(ignore=["Apples"])
assert x.to_list(only="Apples") == x.to_list(only=["Apples"])
assert x.to_list(ignore="Apples") == x.to_list(ignore=["Apples"])
assert x.to_lines(only="Apples") == x.to_lines(only=["Apples"])
assert x.to_lines(ignore="Apples") == x.to_lines(ignore=["Apples"])
assert x.info(exclude="Apples", as_str=True) == x.info(exclude=["Apples"], as_str=True)
assert x.info(ignore="Apples", as_str=True) == x.info(ignore=["Apples"], as_str=True)
def test_fullcopy_plus_filter(self):
"""
fullcopy= can be used with other arguments only= ignore= or exclude=.
Error must be handled gracefully.
"""
x = CleverDict({"Apples": "Green", "Bananas": "Yellow", "Oranges": "Purple"})
assert "Apples" not in x.to_json(fullcopy=True, ignore="Apples")
assert "Apples" not in x.to_json(fullcopy=True, exclude="Apples")
assert "Oranges" not in x.to_json(fullcopy=True, only="Apples")
assert "Bananas" not in x.to_json(fullcopy=True, only="Apples")
def test_only_OR_ignore_OR_exclude_as_args(self):
"""
Only one of only=, ignore=, or exclude= can be given as an argument
for supported functions. Error must be handled gracefully.
"""
x = CleverDict({"Yes": "include me", "No": "exclude/ignore me"})
for func in "__repr__() to_json() to_dict() to_list() to_lines() info(as_str=True)".split():
perms = list(permutations(["only=", "ignore=", "exclude="]))
perms += list(permutations(["only=", "ignore=", "exclude="], 2))
perms = ["".join(list(x)).replace("=", "=['Yes'],") for x in perms]
for args in perms:
with pytest.raises(TypeError):
eval("x." + func.replace("(", "(" + args))
def test_filters_with_init(self):
"""
only= exclude= ignore= should work as part of object instantiation.
"""
# dict
x = CleverDict({"Apples": "Green", "Bananas": "Yellow", "Oranges": "Purple"}, only="Apples")
assert list(x.keys()) == ["Apples"]
x = CleverDict(
{"Apples": "Green", "Bananas": "Yellow", "Oranges": "Purple"},
only=["Apples", "Bananas"],
)
assert list(x.keys()) == ["Apples", "Bananas"]
x = CleverDict(
{"Apples": "Green", "Bananas": "Yellow", "Oranges": "Purple"},
ignore="Apples",
)
assert list(x.keys()) == ["Bananas", "Oranges"]
x = CleverDict(
{"Apples": "Green", "Bananas": "Yellow", "Oranges": "Purple"},
exclude=["Apples", "Bananas"],
)
assert list(x.keys()) == ["Oranges"]
# CleverDict
x = CleverDict({"Apples": "Green", "Bananas": "Yellow", "Oranges": "Purple"})
y = CleverDict(x, only="Apples")
assert list(y.keys()) == ["Apples"]
y = CleverDict(x, exclude="Apples")
assert list(y.keys()) == ["Bananas", "Oranges"]
# list of tuples/lists
x = CleverDict(
[("value1", "one"), ["value2", "two"], ("value3", "three")],
ignore=["value1", "value2"],
)
assert list(x.keys()) == ["value3"]
x = CleverDict([("value1", "one"), ["value2", "two"], ("value3", "three")], only=["value1"])
assert list(x.keys()) == ["value1"]
# fromkeys
x = CleverDict.fromkeys(["Abigail", "Tino", "Isaac"], "Year 9", only="Abigail")
assert list(x.keys()) == ["Abigail"]
x = CleverDict.fromkeys(["Abigail", "Tino", "Isaac"], "Year 9", exclude="Abigail")
assert list(x.keys()) == ["Tino", "Isaac"]
# from_json
json_data = '{"None": null, "data": "123xyz"}'
x = CleverDict.from_json(json_data, exclude="data")
assert list(x.keys()) == ["None"]
json_data = '{"None": null, "data": "123xyz"}'
x = CleverDict.from_json(json_data, only="data")
assert list(x.keys()) == ["data"]
# from_lines
lines = "Green\nYellow\nPurple"
x = CleverDict.from_lines(lines, exclude="Yellow")
assert list(x.values()) == ["Green", "Purple"]
x = CleverDict.from_lines(lines, only="Purple")
assert list(x.values()) == ["Purple"]
# Refactor bool block into be_permissive
def test_too_many_filters_with_init(self):
"""
__init__ can only take one of only= exclude= ignore=.
Otherwise should fail gracefully.
"""
perms = list(permutations(["only=[1],", "ignore=[2],", "exclude=[3],"]))
perms += list(permutations(["only=[1],", "ignore=[2],", "exclude=[3],"], 2))
perms = ["".join(list(x)) for x in perms]
for args in perms:
with pytest.raises(TypeError):
eval(f"CleverDict({{1:1, 2:2, 3:3}}, {args})")
def test_to_lines(self, tmpdir):
d = CleverDict()
d[1] = "een"
d[2] = "twee"
d[3] = "drie"
d[4] = "vier"
d[5] = "vijf"
d[6] = "zes"
d[7] = "zeven"
d.add_alias(1, "one")
d.add_alias(2, "two")
d.add_alias(3, "three")
d.add_alias(4, "four")
d.add_alias(5, "five")
d.add_alias(6, "six")
d.add_alias(7, "7")
# default start_from_key == first alias
assert d.to_lines() == "een\ntwee\ndrie\nvier\nvijf\nzes\nzeven"
assert d.to_lines(start_from_key=4) == "vier\nvijf\nzes\nzeven"
assert d.to_lines(start_from_key="7") == "zeven"
d_nul = CleverDict({0: "nul"})
d_nul.update(d)
d_nul.add_alias(0, "zero")
assert d_nul.to_lines() == "nul\neen\ntwee\ndrie\nvier\nvijf\nzes\nzeven"
with pytest.raises(KeyError):
assert d.to_lines(start_from_key=999)
file_path = Path(tmpdir) / "tmp.txt"
d.to_lines(file_path=file_path)
with open(file_path, "r") as f:
assert f.read() == d.to_lines()
os.remove(file_path)
def test_to_json(self, tmpdir):
d = CleverDict()
d["zero"] = "nul"
d["one"] = "een"
d["two"] = "twee"
d["three"] = "drie"
d["four"] = "vier"
d["five"] = "vijf"
d["six"] = "zes"
d[7] = "zeven"
result = CleverDict(d)
del result[7]
result["7"] = "zeven"
assert CleverDict.from_json(d.to_json()) == result
assert CleverDict.from_json(d.to_json(ignore=["one"])) == eval(
result.__repr__(ignore=["one"])
)
assert CleverDict.from_json(d.to_json(ignore=["one", "two"])) == eval(
result.__repr__(ignore=["one", "two"])
)
assert CleverDict.from_json(d.to_json(ignore=["one", 7])) == eval(
result.__repr__(ignore=["one", "7"])
)
def test_from_lines(self, tmpdir):
d0 = CleverDict()
d0[0] = "alpha"
d0[1] = "beta"
d0[2] = "gamma"
d0[3] = "delta"
d0[4] = "epsilon"
lines = d0.to_lines(start_from_key=0)
assert d0 == CleverDict.from_lines(lines, start_from_key=0)
# Values should remain intact with different start_from_key
assert list(d0.to_dict().values()) == list(
CleverDict.from_lines(lines, start_from_key=1).to_dict().values()
)
assert d0.keys() != CleverDict.from_lines(lines, start_from_key=1).keys()
file_path = Path(tmpdir) / "tmp.txt"
d0.to_lines(file_path=file_path, start_from_key=0)
d = CleverDict.from_lines(file_path=file_path, start_from_key=0)
assert d.to_dict() == {
0: "alpha",
1: "beta",
2: "gamma",
3: "delta",
4: "epsilon",
}
d = CleverDict.from_lines(file_path=file_path, start_from_key=10)
assert d.to_dict() == {
10: "alpha",
11: "beta",
12: "gamma",
13: "delta",
14: "epsilon",
}
with pytest.raises(TypeError):
d = CleverDict.from_lines(file_path=file_path, start_from_key="10")
with pytest.raises(ValueError):
CleverDict.from_lines()
with pytest.raises(ValueError):
CleverDict.from_lines(lines=lines, file_path=file_path)
os.remove(file_path)
def test_from_json(self, tmpdir):
d = CleverDict()
d["zero"] = "nul"
d["one"] = "een"
d["two"] = "twee"
d["three"] = "drie"
d["four"] = "vier"
d["five"] = "vijf"
d["six"] = "zes"
d["7"] = "zeven"
json_data = d.to_json()
result = CleverDict.from_json(json_data)
assert result == d
file_path = Path(tmpdir) / "tmp.txt"
d.to_json(file_path=file_path)
result = CleverDict.from_json(file_path=file_path)
assert d == result
with pytest.raises(ValueError):
CleverDict.from_json()
with pytest.raises(ValueError):
CleverDict.from_json(json_data=json_data, file_path=file_path)
def test_ignore(self):
"""CleverDict.ignore lists aliases and keys which should never be
converted to json or saved including:
password
save_path
_aliases
"""
x = CleverDict({"password": "Top Secret", "userid": "Michael Palin"})
x.add_alias("password", "keyphrase")
x.autosave(silent=True)
path = x.save_path
ignore = "password Password PASSWORD".split()
lines = x.to_lines(ignore=ignore)
for output in [x.to_json(ignore=ignore), repr(x.to_list(ignore=ignore)), lines]:
assert "password" not in output
assert "Top Secret" not in output
assert "auto_save" not in output
assert "_aliases" not in output
if output != lines:
assert "userid" in output
x.autosave("off", silent=True)
def test_to_and_from_json_1(self):
"""It should be possible to completely reconstruct a CleverDict
object, excluding _vars (attributes set directly without updating
the dictionary) after .to_json followed by .from_json"""
d = CleverDict({"one": "een"})
d.add_alias("one", "ONE")
j = d.to_json(fullcopy=True)
new_d = CleverDict.from_json(j)
assert new_d == d
def test_to_and_from_json_2(self):
"""Automatically created aliases should be presevered after .to_json
followed by .from_json"""
d = CleverDict({"#1": 1})
j = d.to_json()
new_d = CleverDict.from_json(j)
assert d._1 is d["#1"]
assert new_d._1 is new_d["#1"]
new_d._1 += 1
assert new_d._1 == new_d["#1"]
def test_to_and_from_json_3(self):
def example_user_code(clever_dict):
"""Typical use of CleverDict is aliases to provide interchangeable
attributes. In this case .number and .Number. Quite subtle and easy
to overlook when debugging"""
clever_dict.number += 1
return clever_dict.Number
""" example_user_code should work equally well after .to_json followed
by .from_json """
d = CleverDict({"number": 1})
d.add_alias("number", "Number")
j = d.to_json(fullcopy=True)
new_d = CleverDict.from_json(j)
assert d.number == d.Number == new_d.number == new_d.Number
assert example_user_code(d) == 2
assert example_user_code(new_d) == 2
def test_to_and_from_json_4(self):
"""
Attributes created with setattr_direct are saved with fullcopy=True
"""
d = CleverDict({1: 2, 3: 4, 0: 5, "string": 6})
d.setattr_direct("extra", 42)
j = d.to_json(fullcopy=True)
new_d = CleverDict.from_json(j)
assert new_d.extra == 42
def test_to_and_from_json_5(self):
"""
Aliases created with add_alias are saved with fullcopy=True
"""
d = CleverDict({1: 2, 3: 4, 0: 5, "string": 6})
d.add_alias(3, "nul")
j = d.to_json(fullcopy=True)
new_d = CleverDict.from_json(j)
assert new_d.nul == 4
def test_default_to_from_json(self):
"""Only data dictionary should be copied with .to_json() by default"""
d = CleverDict({"1": 2, "3": 4, "0": 5, "string": 6})
d.setattr_direct("extra", 42)
d.add_alias("3", "nul")
j = d.to_json()
new_d = CleverDict.from_json(j)
assert new_d.items() == d.items()
with pytest.raises(AttributeError):
new_d.nul
with pytest.raises(KeyError):
new_d["extra"]
def test_get_default_settings_path(self):
path = CleverDict.get_new_save_path()
info = "test"
with open(path, "w") as file:
file.write(info)
with open(path, "r") as file:
assert file.read() == info
path.unlink()
# when called a second time, should be different:
assert CleverDict.get_new_save_path() != path
def test_get_app_dir(self):
"""
tests whether the cleverdict implementation of get_app_dir is ok
(can only be tested if click is installed)
it will test only the right output on the OS the test is running on
"""
try:
import click
from cleverdict import get_app_dir
assert click.get_app_dir("x") == get_app_dir("x")
except ModuleNotFoundError:
pytest.skip("could not import click or cleverdict")
def test_import_existing_cleverdict(test):
x = CleverDict({"name": "Peter", "nationality": "British"})
x.add_alias("name", "nom")
x.setattr_direct("private", "parts")
x.autosave(silent=True)
y = CleverDict(x)
assert y.nom == "Peter"
assert y.private == "parts"
assert list(y.keys()) == ["name", "nationality"]
y = CleverDict(x, only="name")
assert list(y.keys()) == ["name"]
y = CleverDict(x, exclude="name")
assert list(y.keys()) == ["nationality"]
def test_internal_save_was_overwritten(self):
x = CleverDict()
x["save"] = "What a great save!"
assert x["save"] == "What a great save!"
assert repr(x) == "CleverDict({'save': 'What a great save!'}, _aliases={}, _vars={})"
def test_internal_delete_was_overwritten(self):
x = CleverDict()
x["delete"] = "Jon Doe deleted XYZ"
assert x["delete"] == "Jon Doe deleted XYZ"
assert repr(x) == "CleverDict({'delete': 'Jon Doe deleted XYZ'}, _aliases={}, _vars={})"
def test_ignore_internal_save_explicit(self):
x = CleverDict()
x["save"] = "What a great save!"
assert x["save"] == "What a great save!"
assert x.__repr__(ignore=["save"]) == "CleverDict({}, _aliases={}, _vars={})"
def test_ignore_internal_explicit(self):
x = CleverDict()
x["save"] = "What a great save!"
x["delete"] = "Jon Doe deleted XYZ"
assert x["save"] == "What a great save!"
assert x["delete"] == "Jon Doe deleted XYZ"
assert (
x.__repr__(ignore=["delete"])
== "CleverDict({'save': 'What a great save!'}, _aliases={}, _vars={})"
)
class Test_Internal_Logic:
def test_raises_error(self):
"""
Attribute and Key errors should be raised as with normal objects/dicts
"""
x = CleverDict()
with pytest.raises(AttributeError):
x.a
with pytest.raises(KeyError):
x["a"]
def test_conversions(self):
x = CleverDict({1: "First Entry", " ": "space", "??": "question"})
assert x._1 == "First Entry"
assert x["_1"] == "First Entry"
assert x[1] == "First Entry"
with pytest.raises(KeyError):
x["1"] = 5
with pytest.raises(KeyError):
x = CleverDict({1: "First Entry", "1": "space", "??": "question"})
x["else"] = "is else"
assert x["else"] == "is else"
assert x["_else"] == "is else"
assert x._else == "is else"
with pytest.raises(KeyError):
x["?else"] = "other"
x._4 = "abc"
with pytest.raises(KeyError):
x["4"] = "def"
x[12345.0] = "klm"
assert x._12345 == "klm"
x[2.0] = "two-point-0"
assert x._2 == "two-point-0"
x["11a23bccà~£#@q123b/=€впВМвапрй"] = "abc"
assert x._11a23bccà____q123b___впВМвапрй == "abc"
assert x["11a23bccà~£#@q123b/=€впВМвапрй"] == "abc"
assert x["_11a23bccà____q123b___впВМвапрй"] == "abc"
def test_data_attribute(self):
x = CleverDict()
x["data"] = "data"
assert x["data"] == "data"
assert x.data == "data"
def test_normalise_unicode(self):
"""
Most unicode letters are valid in attribute names
"""
x = CleverDict({"ветчина_и_яйца$a": "ham and eggs"})
x.ве = "ve"
x["1ве"] = "1ve"
assert x.ветчина_и_яйца_a == "ham and eggs"
assert x.ве == "ve"
assert x._1ве == "1ve"
def test_True_False_None_functionality(self):
"""
When setting dictionary keys in Python:
d[0] is d[0.0] is d[False]
d[1] is d[1.0] is d[True]
d[1234.0] is d[1234]
If the same key is set in different ways e.g.
d = {0: "Zero", False: "Untrue"}
the last (rightmost) value overwrites any previous values, so
d[0] == "Untrue"
Furthermore, keywords like True and False can't be used as attributes.
"""
x = CleverDict()
x[0] = 0
x[False] = 1
x[1] = 2
x[True] = 3
x[None] = "nothing"
assert x[0] == 1
assert x[False] == 1
assert x["_0"] == 1
assert x["_False"] == 1
assert x._0 == 1
assert x._False == 1
assert x[1] == 3
assert x[True] == 3
assert x["_1"] == 3
assert x["_True"] == 3
assert x._1 == 3
assert x._True == 3
assert x[None] == "nothing"
assert x["_None"] == "nothing"
with pytest.raises(KeyError):
x["None"]
def test_repr_and_eq(self):
"""
Tests that the output from __repr__ can be used to reconstruct the
CleverDict object, and __eq__ can be used to compare CleverDict objects."""
x = CleverDict()
x[0] = 0
x[False] = 1
x[1] = 2
x[True] = 3
x.a = 4
x["what?"] = 5
x.add_alias("a", "c")
y = eval(repr(x))
assert x == y
y.b = 6
assert x != y
x = CleverDict()
assert eval(repr(x)) == x
with Expand(False):
x = CleverDict({True: 1})
assert len(x.get_aliases()) == 1
assert CleverDict(eval(repr(x))) == x
# check whether _expand has been properly reset
x = CleverDict({True: 1})
assert len(x.get_aliases()) == 1
# empty dict with one variable
x = CleverDict()
x.setattr_direct("a", 1)
assert len(x.get_aliases()) == 0
assert eval(repr(x)) == x
def testupdate(self):
x = CleverDict.fromkeys((0, 1, 2, "a", "what?", "return"), 0)
y = CleverDict({0: 2, "c": 3})
x.update(y)
assert x == CleverDict({0: 2, 1: 0, 2: 0, "a": 0, "what?": 0, "return": 0, "c": 3})
def test_del(self):
"""__delattr__ should delete dict items regardless of alias"""
x = CleverDict()
x[1] = 1
del x[1]
with pytest.raises(KeyError):
x[1]
x[1] = 1
del x["_1"]
with pytest.raises(KeyError):
x[1]
x[1] = 1
del x._1
with pytest.raises(KeyError):
x[1]
with pytest.raises(KeyError):
del x[1]
with pytest.raises(AttributeError):
del x._1
def test_del_with_setattr_direct(self):
"""__delattr__ should delete attributes created with setattr_direct"""
x = CleverDict()
x.setattr_direct("direct_variable", "direct_value")
assert hasattr(x, "direct_variable")
del x.direct_variable
assert not hasattr(x, "direct_variable")
def testget_key(self):
x = CleverDict.fromkeys(("a", 0, 1, "what?"), 1)
x.add_alias(0, "zero")
for key in x.keys():
for name in x.get_aliases(key):
assert x.get_key(name) == key
assert x.get_key(True) == 1
assert x.get_key("_True") == 1
assert x.get_key("zero") == 0
def test_Expand(self):
with Expand(False):
x = CleverDict.fromkeys(("a", 0, 1, "what?"), 1)
x.add_alias(0, 2)
assert x.get_aliases("a") == ["a"]
assert x.get_aliases(0) == [0, 2]
assert x.get_aliases(1) == [1]
x = CleverDict.fromkeys(("a", 0, 1, "what?"), 1)
x.add_alias(0, 2)
assert x.get_aliases("a") == ["a"]
assert x.get_aliases(0) == [0, "_0", "_False", 2, "_2"]
assert x.get_aliases(1) == [1, "_1", "_True"]
with Expand(True):
x = CleverDict.fromkeys(("a", 0, 1, "what?"), 1)
x.add_alias(0, 2)
assert x.get_aliases("a") == ["a"]
assert x.get_aliases(0) == [0, "_0", "_False", 2, "_2"]
assert x.get_aliases(1) == [1, "_1", "_True"]
CleverDict.expand = False
x = CleverDict({1: 1})
with pytest.raises(AttributeError):
x._1
CleverDict.expand = True
x = CleverDict({1: 1})
x._1
def test_expand_context_manager(self):
with Expand(False):
assert not CleverDict.expand
assert CleverDict.expand
with Expand(True):
assert CleverDict.expand
assert CleverDict.expand
CleverDict.expand = False
with Expand(False):
assert not CleverDict.expand
assert not CleverDict.expand
with Expand(True):
assert CleverDict.expand
assert not CleverDict.expand
CleverDict.expand = True
def test_all_aliases(self):
assert all_aliases("a") == ["a"]
assert all_aliases(True) == [True, "_1", "_True"]
assert all_aliases("3test test") == ["3test test", "_3test_test"]
with Expand(False):
assert all_aliases("a") == ["a"]
assert all_aliases(True) == [True]
assert all_aliases("3test test") == ["3test test"]
def test_setattr_direct(self):
"""
Sets an attribute directly, i.e. without making it into an item.
Attributes set via setattr_direct will expressly not appear in the result of repr().
They will appear in the result of str() however.
"""
x = CleverDict()
x.setattr_direct("a", "A")
assert x.a == "A"
with pytest.raises(KeyError):
x["a"]
x.get_key("a")
assert x.get_aliases() == []
class Test_Save_Functionality:
def test_save_on_creation1(self):
"""Once set, CleverDict.save should be called on creation"""
delete_log()
CleverDict.save = example_save_function
x = CleverDict({"total": 6, "usergroup": "Knights of Ni"})
assert x.save.__name__ == "example_save_function"
log = get_data("example.log")
assert (
log
== """Notional save to database: .total = 6 <class 'int'>\nNotional save to database: .usergroup = Knights of Ni <class 'str'>\n"""
)
assert delete_log()
CleverDict.save = CleverDict.original_save
assert x.save.__name__ == "save"
assert not delete_log()
def test_save_on_creation2(self):
"""Overwrites (inactive) original save method using __init__"""
delete_log()
x = CleverDict({"total": 6, "usergroup": "Knights of Ni"}, save=example_save_function)
assert x.save.__name__ == "example_save_function"
log = get_data("example.log")
assert (
log
== """Notional save to database: .total = 6 <class 'int'>\nNotional save to database: .usergroup = Knights of Ni <class 'str'>\n"""
)
assert delete_log()
x.set_autosave()
assert not delete_log()
assert x.save.__name__ == "save"
def test_save_on_creation3(self):
delete_log()
x = CleverDict()
with pytest.raises(TypeError):
x.set_autosave(invalid_save_function)
assert not delete_log()
with pytest.raises(TypeError):
x.set_autodelete(invalid_save_function)
assert not delete_log()
def test_save_on_creation4(self):
delete_log()
x = CleverDict()
x.set_autosave(example_save_function)