-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_base.py
More file actions
1331 lines (1128 loc) · 48.3 KB
/
Copy pathtest_base.py
File metadata and controls
1331 lines (1128 loc) · 48.3 KB
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
"""Test the base features of the ``dir-content-diff`` package."""
# LICENSE HEADER MANAGED BY add-license-header
# Copyright (c) 2023-2025 Blue Brain Project, EPFL.
#
# This file is part of dir-content-diff.
# See https://github.com/BlueBrain/dir-content-diff for further info.
#
# SPDX-License-Identifier: Apache-2.0
# LICENSE HEADER MANAGED BY add-license-header
# pylint: disable=missing-function-docstring
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
# pylint: disable=use-implicit-booleaness-not-comparison
import configparser
import copy
import json
import re
import shutil
import dictdiffer
import pytest
import dir_content_diff
from dir_content_diff import assert_equal_trees
from dir_content_diff import compare_trees
class TestBaseComparator:
"""Test the base comparator."""
def test_equal(self):
"""Test equal."""
assert dir_content_diff.JsonComparator() != dir_content_diff.PdfComparator()
assert dir_content_diff.JsonComparator() == dir_content_diff.JsonComparator()
class ComparatorWithAttributes(
dir_content_diff.base_comparators.BaseComparator
):
"""Compare data from two JSON files."""
def __init__(self, arg1, arg2):
super().__init__()
self.arg1 = arg1
if arg2:
self.arg2 = arg2
def diff(self, ref, comp, *args, **kwargs):
return False
assert ComparatorWithAttributes(1, 2) == ComparatorWithAttributes(1, 2)
assert ComparatorWithAttributes(1, 2) != ComparatorWithAttributes(3, 4)
assert ComparatorWithAttributes(1, 2) != ComparatorWithAttributes(1, None)
def test_load_kwargs(self, ref_tree, res_tree_diff):
"""Test the load_kwargs method."""
class ComparatorWithLoader(dir_content_diff.base_comparators.JsonComparator):
"""Compare data from two JSON files."""
def load(self, path, load_empty=False):
if load_empty:
return {}
return super().load(path)
ref_file = ref_tree / "file.json"
res_file = res_tree_diff / "file.json"
diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithLoader(),
)
no_load_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithLoader(),
load_kwargs={"load_empty": False},
)
no_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithLoader(),
load_kwargs={"load_empty": True},
)
no_diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithLoader(default_load_kwargs={"load_empty": True}),
)
diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithLoader(default_load_kwargs={"load_empty": True}),
load_kwargs={"load_empty": False},
)
kwargs_msg = "Kwargs used for loading data: {'load_empty': False}\n"
assert kwargs_msg in no_load_diff
assert diff == no_load_diff.replace(kwargs_msg, "")
assert diff is not False
assert no_diff is False
assert no_diff_default is False
assert kwargs_msg in diff_default
assert diff_default.replace(kwargs_msg, "") == diff
def test_filter_kwargs(self, ref_tree, res_tree_diff):
"""Test the filter_kwargs method."""
class ComparatorWithFilter(dir_content_diff.base_comparators.JsonComparator):
"""Compare data from two JSON files."""
def filter(self, differences, remove_all=False):
if remove_all:
return []
return differences
ref_file = ref_tree / "file.json"
res_file = res_tree_diff / "file.json"
diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFilter(),
)
no_filter_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFilter(),
filter_kwargs={"remove_all": False},
)
no_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFilter(),
filter_kwargs={"remove_all": True},
)
no_diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFilter(default_filter_kwargs={"remove_all": True}),
)
diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFilter(default_filter_kwargs={"remove_all": True}),
filter_kwargs={"remove_all": False},
)
kwargs_msg = "Kwargs used for filtering differences: {'remove_all': False}\n"
assert kwargs_msg in no_filter_diff
assert diff == no_filter_diff.replace(kwargs_msg, "")
assert diff is not False
assert no_diff is False
assert no_diff_default is False
assert kwargs_msg in diff_default
assert diff_default.replace(kwargs_msg, "") == diff
def test_format_kwargs(self, ref_tree, res_tree_diff):
"""Test the format_kwargs method."""
class ComparatorWithFormat(dir_content_diff.base_comparators.JsonComparator):
"""Compare data from two JSON files."""
def format_diff(self, difference, mark_formatted=False):
"""Format one element difference."""
difference = super().format_diff(difference)
if mark_formatted:
difference += "### FORMATTED"
return difference
ref_file = ref_tree / "file.json"
res_file = res_tree_diff / "file.json"
diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFormat(),
)
no_format_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFormat(),
format_diff_kwargs={"mark_formatted": False},
)
formatted_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFormat(),
format_diff_kwargs={"mark_formatted": True},
)
formatted_diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFormat(default_format_diff_kwargs={"mark_formatted": True}),
)
diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithFormat(default_format_diff_kwargs={"mark_formatted": True}),
format_diff_kwargs={"mark_formatted": False},
)
kwargs_msg = (
"Kwargs used for formatting differences: {'mark_formatted': False}\n"
)
assert kwargs_msg in no_format_diff
assert diff == no_format_diff.replace(kwargs_msg, "")
assert len(re.findall("### FORMATTED", diff)) == 0
assert len(re.findall("### FORMATTED", formatted_diff)) == 25
assert len(re.findall("### FORMATTED", formatted_diff_default)) == 25
assert kwargs_msg in diff_default
assert diff_default.replace(kwargs_msg, "") == diff
def test_sort_kwargs(self, ref_tree, res_tree_diff):
"""Test the sort_kwargs method."""
class ComparatorWithSort(dir_content_diff.base_comparators.JsonComparator):
"""Compare data from two JSON files."""
def sort(self, differences, reverse=False):
"""Sort the element differences."""
return sorted(differences, reverse=reverse)
ref_file = ref_tree / "file.json"
res_file = res_tree_diff / "file.json"
diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithSort(),
)
no_reversed_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithSort(),
sort_kwargs={"reverse": False},
)
reversed_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithSort(),
sort_kwargs={"reverse": True},
)
reversed_diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithSort(default_sort_kwargs={"reverse": True}),
)
no_reversed_diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithSort(default_sort_kwargs={"reverse": True}),
sort_kwargs={"reverse": False},
)
kwargs_msg = "Kwargs used for sorting differences: {'reverse': True}\n"
kwargs_msg_false = kwargs_msg.replace("True", "False")
expected_reversed_diff = "\n".join(
diff.split("\n")[:1] + sorted(diff.split("\n")[1:], reverse=True)
)
assert kwargs_msg not in diff
assert kwargs_msg_false not in diff
assert kwargs_msg_false in no_reversed_diff
assert kwargs_msg in reversed_diff
assert kwargs_msg in reversed_diff_default
assert kwargs_msg_false in no_reversed_diff_default
assert diff == no_reversed_diff.replace(kwargs_msg_false, "")
assert expected_reversed_diff == reversed_diff.replace(kwargs_msg, "")
assert expected_reversed_diff == reversed_diff_default.replace(kwargs_msg, "")
assert diff == no_reversed_diff_default.replace(kwargs_msg_false, "")
def test_concat_kwargs(self, ref_tree, res_tree_diff):
"""Test the concat_kwargs method."""
class ComparatorWithConcat(dir_content_diff.base_comparators.JsonComparator):
"""Compare data from two JSON files."""
def concatenate(self, differences, eol=None):
"""Concatenate the differences."""
if not eol:
eol = "\n"
return eol.join(differences)
ref_file = ref_tree / "file.json"
res_file = res_tree_diff / "file.json"
diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithConcat(),
)
concat_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithConcat(),
concat_kwargs={"eol": "\n"},
)
concat_eol_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithConcat(),
concat_kwargs={"eol": "#EOL#"},
)
concat_eol_diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithConcat(default_concat_kwargs={"eol": "#EOL#"}),
)
concat_diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithConcat(default_concat_kwargs={"eol": "#EOL#"}),
concat_kwargs={"eol": "\n"},
)
kwargs_msg_eol = (
"\nKwargs used for concatenating differences: {'eol': '#EOL#'}\n"
)
kwargs_msg_n = kwargs_msg_eol.replace("#EOL#", "\\n")
TEST_EOL = "__TEST_EOL__"
assert kwargs_msg_eol not in diff
assert kwargs_msg_n not in diff
assert kwargs_msg_n in concat_diff
assert kwargs_msg_eol in concat_eol_diff
assert kwargs_msg_eol in concat_eol_diff_default
assert kwargs_msg_n in concat_diff_default
assert diff == concat_diff.replace(kwargs_msg_n, "\n")
assert concat_diff.replace(kwargs_msg_n, "").replace(
"\n", TEST_EOL
) == concat_eol_diff.replace(kwargs_msg_eol, "").replace("#EOL#", TEST_EOL)
assert concat_eol_diff == concat_eol_diff_default
assert diff == concat_diff_default.replace(kwargs_msg_n, "\n")
def test_report_kwargs(self, ref_tree, res_tree_diff):
"""Test the report_kwargs method."""
class ComparatorWithReport(dir_content_diff.base_comparators.JsonComparator):
"""Compare data from two JSON files."""
def report(
self,
ref_file,
comp_file,
formatted_differences,
diff_args,
diff_kwargs,
mark_report=None,
**kwargs,
):
if mark_report is not None:
kwargs["mark_report"] = mark_report
report = super().report(
ref_file,
comp_file,
formatted_differences,
diff_args,
diff_kwargs,
**kwargs,
)
if mark_report:
report += "### REPORTED"
return report
ref_file = ref_tree / "file.json"
res_file = res_tree_diff / "file.json"
diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithReport(),
)
no_report_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithReport(),
report_kwargs={"mark_report": False},
)
reported_diff = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithReport(),
report_kwargs={"mark_report": True},
)
reported_diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithReport(default_report_kwargs={"mark_report": True}),
)
no_report_diff_default = dir_content_diff.compare_files(
ref_file,
res_file,
ComparatorWithReport(default_report_kwargs={"mark_report": True}),
report_kwargs={"mark_report": False},
)
kwargs_msg = "Kwargs used for reporting differences: {'mark_report': False}\n"
assert kwargs_msg in no_report_diff
assert diff == no_report_diff.replace(kwargs_msg, "")
assert len(re.findall("### REPORTED", diff)) == 0
assert len(re.findall("### REPORTED", reported_diff)) == 1
assert len(re.findall("### REPORTED", reported_diff_default)) == 1
assert kwargs_msg in no_report_diff_default
assert no_report_diff_default.replace(kwargs_msg, "") == diff
@staticmethod
def common_test_load_save(tmp_path, comparator):
"""Test load and save capabilities of the given comparator."""
initial_data = {
"a": {
"b": 1,
"c": [1, 2, 3],
"d": {
"test_str": "a str",
"test_int": 999,
},
}
}
initial_file = tmp_path / "initial_file.json"
comparator.save(initial_data, initial_file)
loaded_data = comparator.load(initial_file)
assert loaded_data == initial_data
class TestJsonComparator:
"""Test the JSON comparator."""
def test_load_save(self, tmp_path):
"""Test load and save capabilities of the comparator."""
comparator = dir_content_diff.JsonComparator()
TestBaseComparator.common_test_load_save(tmp_path, comparator)
def test_format_data(self):
"""Test data formatting."""
data = {
"a": 1,
"b": {
"c": "a string",
},
"d": [
{"d1": "the d1 string"},
{"d2": "the d2 string"},
],
"e": {
"nested_e": {
"nested_e_a": "the nested_e_a string",
"nested_e_b": "the nested_e_b string",
}
},
}
initial_data = copy.deepcopy(data)
expected_data = {
"a": 1,
"b": {
"c": "a NEW VALUE",
},
"d": [
{"d1": "the d1 NEW VALUE"},
{"d2": "the d2 NEW VALUE"},
],
"e": {
"nested_e": {
"nested_e_a": "the nested_e_a NEW VALUE",
"nested_e_b": "the nested_e_b NEW VALUE",
}
},
}
patterns = {
("string", "NEW VALUE"): [
"b.c",
"d[*].*",
"e.*.*",
]
}
comparator = dir_content_diff.JsonComparator()
comparator.format_data(data)
assert data == initial_data
data = copy.deepcopy(initial_data)
comparator = dir_content_diff.JsonComparator()
comparator.format_data(data, replace_pattern=patterns)
assert data == expected_data
# Missing key in ref
comparator = dir_content_diff.JsonComparator()
data = copy.deepcopy(initial_data)
ref = {"a": 1}
comparator.format_data(data, ref, replace_pattern=patterns)
assert data == initial_data
assert comparator.current_state["format_errors"] == [
("missing_ref_entry", i, None)
for i in patterns[("string", "NEW VALUE")]
]
# Missing key in data
comparator = dir_content_diff.JsonComparator()
ref = copy.deepcopy(initial_data)
data = {"a": 1}
comparator.format_data(data, ref, replace_pattern=patterns)
assert data == {"a": 1}
assert comparator.current_state["format_errors"] == [
("missing_comp_entry", i, None)
for i in patterns[("string", "NEW VALUE")]
]
class TestXmlComparator:
"""Test the XML comparator."""
def test_load_save(self, tmp_path):
"""Test load and save capabilities of the comparator."""
comparator = dir_content_diff.XmlComparator()
TestBaseComparator.common_test_load_save(tmp_path, comparator)
def test_xmltodict(self):
"""Test all types of the xmltodict auto cast feature."""
comparator = dir_content_diff.XmlComparator()
# Test empty root
res = comparator.xmltodict(
"""<?xml version="1.0" encoding="UTF-8" ?>
<root>
</root>
"""
)
assert res == {"root": {}}
# Test all types
res = comparator.xmltodict(
"""<?xml version="1.0" encoding="UTF-8" ?>"""
"""<root>"""
""" <str_value_no_type>a str value</str_value_no_type>"""
""" <str_value type="str">another str value</str_value>"""
""" <int_value type="int">1</int_value>"""
""" <float_value type="float">1.5</float_value>"""
""" <boolean_true type="bool">TrUe</boolean_true>"""
""" <boolean_false type="bool">FaLsE</boolean_false>"""
""" <simple_list type="list">"""
""" <item type="int">1</item>"""
""" <item type="float">2.5</item>"""
""" <item type="str">str_val</item>"""
""" </simple_list>"""
""" <simple_dict type="dict">"""
""" <key_1 type="int">1</key_1>"""
""" <key_2 type="float">2.5</key_2>"""
""" <key_3 type="str">str_val</key_3>"""
""" <key_4>another str val</key_4>"""
""" </simple_dict>"""
""" <none type="null">any thing here is not considered</none>"""
"""</root>"""
)
assert res["root"]["none"] is None
del res["root"]["none"]
assert res == {
"root": {
"str_value_no_type": "a str value",
"str_value": "another str value",
"int_value": 1,
"float_value": 1.5,
"boolean_true": True,
"boolean_false": False,
"simple_list": [1, 2.5, "str_val"],
"simple_dict": {
"key_1": 1,
"key_2": 2.5,
"key_3": "str_val",
"key_4": "another str val",
},
}
}
# Test unknown type
with pytest.raises(TypeError, match=r"Unsupported type.*"):
comparator.xmltodict(
"""<?xml version="1.0" encoding="UTF-8" ?>"""
"""<root>"""
""" <bad_type type="UNKNOWN TYPE">1</bad_type>"""
"""</root>"""
)
# Test bad value in boolean
with pytest.raises(
ValueError, match="Bool attributes expect 'true' or 'false'."
):
comparator.xmltodict(
"""<?xml version="1.0" encoding="UTF-8" ?>"""
"""<root>"""
""" <bad_bool type="bool">not a bool</bad_bool>"""
"""</root>"""
)
def test_add_to_output_with_none(self):
"""Test wrong type for add_to_output() method."""
comparator = dir_content_diff.XmlComparator()
comparator.add_to_output(None, None)
class TestIniComparator:
"""Test the INI comparator."""
def test_load_save(self, tmp_path):
"""Test load and save capabilities of the comparator."""
comparator = dir_content_diff.IniComparator()
TestBaseComparator.common_test_load_save(tmp_path, comparator)
def test_initodict(self, ref_tree):
"""Test conversion of INI files into dict."""
data = configparser.ConfigParser()
data.read(ref_tree / "file.ini")
comparator = dir_content_diff.IniComparator()
res = comparator.configparser_to_dict(data)
assert res == {
"section1": {"attr1": "val1", "attr2": 1},
"section2": {"attr3": [1, 2, "a", "b"], "attr4": {"a": 1, "b": [1, 2]}},
}
class TestPdfComparator:
"""Test the PDF comparator."""
def test_diff_tempfile(self, ref_tree, res_tree_equal):
"""Test the custom tempfile option."""
ref_file = ref_tree / "file.pdf"
res_file = res_tree_equal / "file.pdf"
# Copy the initial data into a nested directory
nested_ref = res_tree_equal / "nested" / "ref"
nested_res = res_tree_equal / "nested" / "res"
shutil.copytree(res_tree_equal, nested_res)
shutil.copytree(ref_tree, nested_ref)
# Compute difference on initial data
diff = dir_content_diff.compare_files(
ref_file,
res_file,
dir_content_diff.PdfComparator(),
tempdir=res_tree_equal,
)
assert not diff
assert (res_tree_equal / "diff-pdf" / "file.pdf" / "diff-1.png").exists()
# Compute difference on nested data
ref_file = nested_ref / "file.pdf"
res_file = nested_res / "file.pdf"
diff_nested = dir_content_diff.compare_files(
ref_file,
res_file,
dir_content_diff.PdfComparator(),
tempdir=nested_res.parent,
)
assert not diff_nested
assert (nested_res.parent / "diff-pdf" / "file.pdf" / "diff-1.png").exists()
# Compare files with different names and with existing tempdir
other_res_file = res_file.with_name("other_file.pdf")
shutil.copyfile(res_file, other_res_file)
(res_tree_equal / "diff-pdf" / "other_file.pdf").mkdir()
other_diff = dir_content_diff.compare_files(
ref_file,
other_res_file,
dir_content_diff.PdfComparator(),
tempdir=res_tree_equal,
)
assert not other_diff
assert (res_tree_equal / "diff-pdf" / "other_file.pdf").exists()
assert not list((res_tree_equal / "diff-pdf" / "other_file.pdf").iterdir())
assert (
res_tree_equal / "diff-pdf_1" / "other_file.pdf" / "diff-1.png"
).exists()
# Compute difference on same data so the root directory is in the common path
diff_nested = dir_content_diff.compare_files(
ref_file,
ref_file,
dir_content_diff.PdfComparator(),
tempdir=res_tree_equal,
)
assert not diff_nested
assert (res_tree_equal / "diff-pdf_2").exists()
all_pdf_files = list((res_tree_equal / "diff-pdf_2").rglob("*.pdf"))
all_png_files = list((res_tree_equal / "diff-pdf_2").rglob("*.png"))
assert len(all_pdf_files) == 1
assert len(all_png_files) == 3
class TestRegistry:
"""Test the internal registry."""
def test_init_register(self, registry_reseter):
"""Test the initial registry with the get_comparators() function."""
assert dir_content_diff.get_comparators() == {
None: dir_content_diff.DefaultComparator(),
".cfg": dir_content_diff.IniComparator(),
".conf": dir_content_diff.IniComparator(),
".ini": dir_content_diff.IniComparator(),
".json": dir_content_diff.JsonComparator(),
".pdf": dir_content_diff.PdfComparator(),
".yaml": dir_content_diff.YamlComparator(),
".yml": dir_content_diff.YamlComparator(),
".xml": dir_content_diff.XmlComparator(),
}
def test_update_register(self, registry_reseter):
"""Test the functions to update the registry."""
dir_content_diff.register_comparator(
".test_ext", dir_content_diff.JsonComparator()
)
assert dir_content_diff.get_comparators() == {
None: dir_content_diff.DefaultComparator(),
".cfg": dir_content_diff.IniComparator(),
".conf": dir_content_diff.IniComparator(),
".ini": dir_content_diff.IniComparator(),
".test_ext": dir_content_diff.JsonComparator(),
".json": dir_content_diff.JsonComparator(),
".pdf": dir_content_diff.PdfComparator(),
".yaml": dir_content_diff.YamlComparator(),
".yml": dir_content_diff.YamlComparator(),
".xml": dir_content_diff.XmlComparator(),
}
dir_content_diff.unregister_comparator(".yaml")
dir_content_diff.unregister_comparator("json") # Test suffix without dot
assert dir_content_diff.get_comparators() == {
None: dir_content_diff.DefaultComparator(),
".cfg": dir_content_diff.IniComparator(),
".conf": dir_content_diff.IniComparator(),
".ini": dir_content_diff.IniComparator(),
".test_ext": dir_content_diff.JsonComparator(),
".pdf": dir_content_diff.PdfComparator(),
".yml": dir_content_diff.YamlComparator(),
".xml": dir_content_diff.XmlComparator(),
}
dir_content_diff.reset_comparators()
assert dir_content_diff.get_comparators() == {
None: dir_content_diff.DefaultComparator(),
".cfg": dir_content_diff.IniComparator(),
".conf": dir_content_diff.IniComparator(),
".ini": dir_content_diff.IniComparator(),
".json": dir_content_diff.JsonComparator(),
".pdf": dir_content_diff.PdfComparator(),
".yaml": dir_content_diff.YamlComparator(),
".yml": dir_content_diff.YamlComparator(),
".xml": dir_content_diff.XmlComparator(),
}
with pytest.raises(
ValueError,
match=(
"The '.pdf' extension is already registered and must be unregistered before being "
"replaced."
),
):
dir_content_diff.register_comparator(
".pdf", dir_content_diff.JsonComparator()
)
with pytest.raises(
ValueError, match="The '.unknown_ext' extension is not registered."
):
dir_content_diff.unregister_comparator(".unknown_ext")
dir_content_diff.unregister_comparator(".unknown_ext", quiet=True)
dir_content_diff.register_comparator(
".new_ext", dir_content_diff.JsonComparator()
)
assert dir_content_diff.get_comparators() == {
None: dir_content_diff.DefaultComparator(),
".cfg": dir_content_diff.IniComparator(),
".conf": dir_content_diff.IniComparator(),
".ini": dir_content_diff.IniComparator(),
".json": dir_content_diff.JsonComparator(),
".pdf": dir_content_diff.PdfComparator(),
".yaml": dir_content_diff.YamlComparator(),
".yml": dir_content_diff.YamlComparator(),
".xml": dir_content_diff.XmlComparator(),
".new_ext": dir_content_diff.JsonComparator(),
}
dir_content_diff.register_comparator(
".new_ext", dir_content_diff.PdfComparator(), force=True
)
assert dir_content_diff.get_comparators() == {
None: dir_content_diff.DefaultComparator(),
".cfg": dir_content_diff.IniComparator(),
".conf": dir_content_diff.IniComparator(),
".ini": dir_content_diff.IniComparator(),
".json": dir_content_diff.JsonComparator(),
".pdf": dir_content_diff.PdfComparator(),
".yaml": dir_content_diff.YamlComparator(),
".yml": dir_content_diff.YamlComparator(),
".xml": dir_content_diff.XmlComparator(),
".new_ext": dir_content_diff.PdfComparator(),
}
@pytest.fixture
def ref_with_nested_file(ref_tree):
"""Update the ref tree to have nesteed files."""
ref_pdf_file = ref_tree / "file.pdf"
new_ref_pdf_file = ref_tree / "level1" / "level2" / "level3" / "file.pdf"
new_ref_pdf_file.parent.mkdir(parents=True)
ref_pdf_file.rename(new_ref_pdf_file)
return ref_tree
@pytest.fixture
def res_equal_with_nested_file(res_tree_equal):
"""Update the result tree to have nesteed files."""
res_pdf_file = res_tree_equal / "file.pdf"
new_res_pdf_file = res_tree_equal / "level1" / "level2" / "level3" / "file.pdf"
new_res_pdf_file.parent.mkdir(parents=True)
res_pdf_file.rename(new_res_pdf_file)
return res_tree_equal
@pytest.fixture
def res_diff_with_nested_file(res_tree_diff):
"""Update the result tree to have nesteed files."""
res_pdf_file = res_tree_diff / "file.pdf"
new_res_pdf_file = res_tree_diff / "level1" / "level2" / "level3" / "file.pdf"
new_res_pdf_file.parent.mkdir(parents=True)
res_pdf_file.rename(new_res_pdf_file)
return res_tree_diff
class TestEqualTrees:
"""Tests that should return no difference."""
def test_diff_tree(self, ref_tree, res_tree_equal):
"""Test that no difference is returned."""
res = compare_trees(ref_tree, res_tree_equal)
assert res == {}
def test_assert_equal_trees(self, ref_tree, res_tree_equal):
"""Test that no exception is raised."""
assert_equal_trees(ref_tree, res_tree_equal)
def test_assert_equal_trees_export(self, ref_tree, res_tree_equal):
"""Test that the formatted files are properly exported."""
assert_equal_trees(
ref_tree,
res_tree_equal,
export_formatted_files=True,
)
assert sorted(
res_tree_equal.with_name(res_tree_equal.name + "_FORMATTED").iterdir()
) == [
(
res_tree_equal.with_name(res_tree_equal.name + "_FORMATTED") / "file"
).with_suffix(suffix)
for suffix in [".ini", ".json", ".xml", ".yaml"]
]
def test_diff_empty(self, empty_ref_tree, empty_res_tree):
"""Test with empty trees."""
res = compare_trees(empty_ref_tree, empty_res_tree)
assert res == {}
def test_pass_register(self, empty_ref_tree, empty_res_tree):
"""Test with empty trees and with an explicit set of comparators."""
res = compare_trees(
empty_ref_tree,
empty_res_tree,
comparators=dir_content_diff.get_comparators(),
)
assert res == {}
def test_unknown_comparator(self, ref_tree, res_tree_equal, registry_reseter):
"""Test with an unknown extension."""
dir_content_diff.unregister_comparator(".yaml")
res = compare_trees(ref_tree, res_tree_equal)
assert res == {}
def test_nested_files(self, ref_with_nested_file, res_equal_with_nested_file):
"""Test with nested files."""
res = compare_trees(ref_with_nested_file, res_equal_with_nested_file)
assert res == {}
def test_specific_args(self, ref_tree, res_tree_equal):
"""Test specific args."""
specific_args = {
"file.yaml": {"args": [None, None, None, False, 0, False]},
"file.json": {"tolerance": 0},
}
res = compare_trees(ref_tree, res_tree_equal, specific_args=specific_args)
assert res == {}
def test_replace_pattern(self, ref_tree, res_tree_equal):
"""Test specific args."""
specific_args = {
"file.yaml": {"args": [None, None, None, False, 0, False]},
"file.json": {
"format_data_kwargs": {
"replace_pattern": {(".*val.*", "NEW_VAL"): ["*.[*]"]},
},
},
}
res = compare_trees(
ref_tree,
res_tree_equal,
specific_args=specific_args,
export_formatted_files=True,
)
pat = (
r"""The files '\S*/ref/file\.json' and '\S*/res/file\.json' are different:\n"""
r"""Kwargs used for formatting data: """
r"""{'replace_pattern': {\('\.\*val\.\*', 'NEW_VAL'\): \['\*\.\[\*\]'\]}}\n"""
r"""Changed the value of '\[nested_list\]\[2\]' from 'str_val' to 'NEW_VAL'\.\n"""
r"""Changed the value of '\[simple_list\]\[2\]' from 'str_val' to 'NEW_VAL'\."""
)
assert re.match(pat, res["file.json"]) is not None
def test_specific_comparator(self, ref_tree, res_tree_equal):
"""Test specific args."""
specific_args = {
"file.yaml": {"args": [None, None, None, False, 0, False]},
"file.json": {"comparator": dir_content_diff.DefaultComparator()},
}
res = compare_trees(ref_tree, res_tree_equal, specific_args=specific_args)
assert res == {}
def test_specific_patterns(self, ref_tree, res_tree_equal, base_diff):
"""Test specific args."""
specific_args = {
"all yaml files": {
"args": [None, None, None, False, 0, False],
"patterns": [r".*\.yaml"],
},
"all json files": {
"comparator": dir_content_diff.DefaultComparator(),
"patterns": [r".*\.json"],
},
}
res = compare_trees(ref_tree, res_tree_equal, specific_args=specific_args)
assert res == {}
# Test pattern override
specific_args["all json files"]["comparator"] = dir_content_diff.PdfComparator()
specific_args["file.json"] = {
"comparator": dir_content_diff.DefaultComparator()
}
res = compare_trees(ref_tree, res_tree_equal, specific_args=specific_args)
assert res == {}
# Test pattern multiple matches
specific_args = {
"all files": {
"comparator": dir_content_diff.DefaultComparator(),
"patterns": [r"file\..*"],
},
}
res = compare_trees(ref_tree, res_tree_equal, specific_args=specific_args)
assert list(res.keys()) == ["file.pdf"]
assert re.match(base_diff, res["file.pdf"]) is not None
class TestDiffTrees:
"""Tests that should return differences."""
def test_diff_tree(
self, ref_tree, res_tree_diff, pdf_diff, dict_diff, xml_diff, ini_diff