Skip to content

Commit 8b22aab

Browse files
Test: Fix
1 parent 88c9494 commit 8b22aab

File tree

4 files changed

+164
-24
lines changed

4 files changed

+164
-24
lines changed

dir_content_diff/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ def export_formatted_file(file, formatted_file, comparator, **kwargs):
224224
),
225225
)
226226
else:
227-
LOGGER.info(
227+
LOGGER.debug(
228228
"Skip formatting for '%s' because the comparator has no saving capability.",
229229
file,
230230
)

dir_content_diff/base_comparators.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -619,7 +619,7 @@ def diff(self, ref, comp, *args, **kwargs):
619619
620620
Keyword Args:
621621
threshold (int): The threshold used to compare the images.
622-
tempdir (pathlib.Path): Directory in which a new ``dir-diff` directory will be created
622+
tempdir (pathlib.Path): Directory in which a new ``dir-diff`` directory will be created
623623
to export the debug images.
624624
dpi (int): The resolution used to convert the PDF files into images.
625625
verbosity (int): The log verbosity.
@@ -668,12 +668,14 @@ def __call__(self, ref_file, comp_file, *args, **kwargs):
668668

669669
try:
670670
# Update default verbosity
671-
if "verbosity" not in kwargs:
671+
if "verbosity" not in kwargs: # pragma: no branch
672672
current_default_verbosity = int(
673673
diff_pdf_visually.constants.DEFAULT_VERBOSITY
674674
)
675675
try:
676-
if diff_pdf_visually.diff.pdfdiff_pages.__defaults__[1] is None:
676+
if (
677+
diff_pdf_visually.diff.pdfdiff_pages.__defaults__[1] is None
678+
): # pragma: no cover
677679
diff_pdf_visually.constants.DEFAULT_VERBOSITY = 0
678680
else:
679681
kwargs["verbosity"] = 0
@@ -701,12 +703,11 @@ def report(
701703
**kwargs,
702704
): # pylint: disable=too-many-arguments
703705
"""Add specific information before calling the default method."""
704-
if formatted_differences:
705-
if isinstance(formatted_differences, str):
706-
formatted_differences = (
707-
"The following pages are the most different: "
708-
+ formatted_differences.replace("\n", ", ")
709-
)
706+
if formatted_differences and isinstance(formatted_differences, str):
707+
formatted_differences = (
708+
"The following pages are the most different: "
709+
+ formatted_differences.replace("\n", ", ")
710+
)
710711
if "tempdir" in diff_kwargs:
711712
formatted_differences += (
712713
"\nThe visual differences can be found here: "

dir_content_diff/cli/__init__.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,25 +140,29 @@ def input_diff(ref, comp, config, export_formatted_files=False, sort_diffs=False
140140
specific_args=config,
141141
export_formatted_files=export_formatted_files,
142142
)
143-
if sort_diffs:
144-
res = sorted(res.items(), key=lambda x: x[0])
145143
else:
146144
comparator_name = config.pop("comparator", None)
147145
comparator = pick_comparator(
148146
comparator=comparator_name,
149147
suffix=ref.suffix,
150148
)
151-
res = {str(ref): compare_files(ref, comp, comparator, **config)}
149+
diff = compare_files(ref, comp, comparator, **config)
150+
res = {str(ref): diff} if diff is not False else {}
152151
if export_formatted_files:
153152
export_formatted_file(ref, **config)
154153
export_formatted_file(comp, **config)
155154

156155
if res:
156+
if sort_diffs:
157+
res_list = sorted(res.items(), key=lambda x: x[0])
158+
else:
159+
res_list = res.items()
160+
157161
LOGGER.info(
158162
"Differences found between '%s' and '%s':\n\n\n%s",
159163
ref,
160164
comp,
161-
("\n\n\n".join([i[1] for i in res.items()])),
165+
("\n\n\n".join([i[1] for i in res_list])),
162166
)
163167
else:
164168
LOGGER.info("No difference found between '%s' and '%s'", ref, comp)

tests/test_cli.py

Lines changed: 145 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,38 @@ def config(self, tmp_path):
2626
return {"file.pdf": {"tempdir": str(tmp_path)}}
2727

2828
@pytest.fixture
29-
def config_json(self, config):
29+
def config_tree_json(self, config):
3030
"""The config as a JSON string."""
3131
return json.dumps(config)
3232

3333
@pytest.fixture
34-
def config_yaml(self, config, tmp_path):
34+
def config_file_json(self, config):
35+
"""The config as a JSON string."""
36+
return json.dumps(config["file.pdf"])
37+
38+
@pytest.fixture
39+
def config_tree_yaml(self, config, tmp_path):
3540
"""The config as a YAML file."""
36-
filepath = tmp_path / "config.yaml"
41+
filepath = tmp_path / "config_tree.yaml"
3742
with filepath.open("w", encoding="utf-8") as f:
3843
yaml.dump(config, f)
3944
return filepath
4045

4146
@pytest.fixture
42-
def config_str(self, request):
47+
def config_file_yaml(self, config, tmp_path):
48+
"""The config as a YAML file."""
49+
filepath = tmp_path / "config_file.yaml"
50+
with filepath.open("w", encoding="utf-8") as f:
51+
yaml.dump(config["file.pdf"], f)
52+
return filepath
53+
54+
@pytest.fixture
55+
def config_tree_str(self, request):
56+
"""The string given to the CLI to pass the config."""
57+
return request.getfixturevalue(request.param)
58+
59+
@pytest.fixture
60+
def config_file_str(self, request):
4361
"""The string given to the CLI to pass the config."""
4462
return request.getfixturevalue(request.param)
4563

@@ -49,34 +67,85 @@ def test_help(self, cli_runner):
4967
assert "A command line tool for directory or file comparison." in result.stdout
5068

5169
@pytest.mark.parametrize(
52-
"config_str", ["config_json", "config_yaml"], indirect=True
70+
"config_tree_str,config_file_str",
71+
[
72+
["config_tree_json", "config_file_json"],
73+
["config_tree_yaml", "config_file_yaml"],
74+
],
75+
indirect=True,
5376
)
5477
def test_equal_tree(
55-
self, tmp_path, ref_tree, res_tree_equal, config_str, cli_runner, caplog
78+
self,
79+
tmp_path,
80+
ref_tree,
81+
res_tree_equal,
82+
config_tree_str,
83+
config_file_str,
84+
cli_runner,
85+
caplog,
5686
):
5787
"""Test with equal trees."""
5888
caplog.set_level(logging.INFO, logger="dir-content-diff")
89+
90+
# Test with trees
5991
result = cli_runner.invoke(
6092
dir_content_diff.cli.main,
61-
[str(ref_tree), str(res_tree_equal), "--config", config_str],
93+
[str(ref_tree), str(res_tree_equal), "--config", config_tree_str],
94+
catch_exceptions=False,
6295
)
6396
assert result.stdout == ""
6497
assert caplog.messages == [
6598
f"No difference found between '{ref_tree}' and '{res_tree_equal}'"
6699
]
67100
assert (tmp_path / "diff-pdf" / "file.pdf" / "diff-1.png").exists()
68101

102+
# Test with files
103+
caplog.clear()
104+
ref_file = ref_tree / "file.pdf"
105+
res_file = res_tree_equal / "file.pdf"
106+
result = cli_runner.invoke(
107+
dir_content_diff.cli.main,
108+
[str(ref_file), str(res_file), "--config", config_file_str],
109+
catch_exceptions=False,
110+
)
111+
assert result.stdout == ""
112+
assert caplog.messages == [
113+
f"No difference found between '{ref_file}' and '{res_file}'"
114+
]
115+
assert (tmp_path / "diff-pdf" / "file.pdf" / "diff-1.png").exists()
116+
69117
@pytest.mark.parametrize(
70-
"config_str", ["config_json", "config_yaml"], indirect=True
118+
"config_tree_str,config_file_str",
119+
[
120+
["config_tree_json", "config_file_json"],
121+
["config_tree_yaml", "config_file_yaml"],
122+
],
123+
indirect=True,
71124
)
72125
def test_diff_tree(
73-
self, tmp_path, ref_tree, res_tree_diff, config_str, cli_runner, caplog
126+
self,
127+
tmp_path,
128+
ref_tree,
129+
res_tree_diff,
130+
config_tree_str,
131+
config_file_str,
132+
cli_runner,
133+
caplog,
74134
):
75135
"""Test with different trees."""
76136
caplog.set_level(logging.INFO, logger="dir-content-diff")
137+
138+
# Test with trees
77139
result = cli_runner.invoke(
78140
dir_content_diff.cli.main,
79-
[str(ref_tree), str(res_tree_diff), "--config", config_str],
141+
[
142+
str(ref_tree),
143+
str(res_tree_diff),
144+
"--config",
145+
config_tree_str,
146+
"--sort-diffs",
147+
"--export-formatted-files",
148+
],
80149
)
81150
assert result.stdout == ""
82151
assert len(caplog.messages) == 1
@@ -93,6 +162,72 @@ def test_diff_tree(
93162
)
94163
assert (tmp_path / "diff-pdf" / "file.pdf" / "diff-1.png").exists()
95164

165+
# Test with files
166+
caplog.clear()
167+
ref_file = ref_tree / "file.pdf"
168+
res_file = res_tree_diff / "file.pdf"
169+
result = cli_runner.invoke(
170+
dir_content_diff.cli.main,
171+
[str(ref_file), str(res_file), "--config", config_file_str],
172+
catch_exceptions=False,
173+
)
174+
assert result.stdout == ""
175+
assert len(caplog.messages) == 1
176+
assert (
177+
f"Differences found between '{ref_file}' and '{res_file}':"
178+
in caplog.messages[0]
179+
)
180+
assert (tmp_path / "diff-pdf" / "file.pdf" / "diff-1.png").exists()
181+
182+
class TestFailures:
183+
def test_dir_file(self, cli_runner, caplog, ref_tree, res_tree_diff):
184+
"""Test exception when comparing a directory with a file."""
185+
ref_file = ref_tree / "file.pdf"
186+
res_file = res_tree_diff / "file.pdf"
187+
with pytest.raises(
188+
ValueError,
189+
match=r"The reference and compared inputs must both be either two directories or two files\.",
190+
):
191+
result = cli_runner.invoke(
192+
dir_content_diff.cli.main,
193+
[str(ref_tree), str(res_file)],
194+
catch_exceptions=False,
195+
)
196+
with pytest.raises(
197+
ValueError,
198+
match=r"The reference and compared inputs must both be either two directories or two files\.",
199+
):
200+
result = cli_runner.invoke(
201+
dir_content_diff.cli.main,
202+
[str(ref_file), str(res_tree_diff)],
203+
catch_exceptions=False,
204+
)
205+
206+
def test_not_existing_config(self, cli_runner, caplog):
207+
"""Test exception when the config file does not exist."""
208+
with pytest.raises(
209+
FileNotFoundError,
210+
match=r"The file '/NOT/EXISTING/FILE' does not exist\.",
211+
):
212+
result = cli_runner.invoke(
213+
dir_content_diff.cli.main,
214+
["/A/FILE", "/ANOTHER/FILE", "--config", "/NOT/EXISTING/FILE"],
215+
catch_exceptions=False,
216+
)
217+
218+
def test_bad_yaml_config(self, tmp_path, cli_runner, caplog):
219+
"""Test exception when the config file does not exist."""
220+
filepath = tmp_path / "config_file.yaml"
221+
with filepath.open("w", encoding="utf-8") as f:
222+
f.write("entry: &A !!!")
223+
224+
with pytest.raises(yaml.constructor.ConstructorError):
225+
result = cli_runner.invoke(
226+
dir_content_diff.cli.main,
227+
["/A/FILE", "/ANOTHER/FILE", "--config", str(filepath)],
228+
catch_exceptions=False,
229+
)
230+
96231

97232
def test_entry_point(script_runner):
98233
"""Test the entry point."""

0 commit comments

Comments
 (0)