Skip to content

Commit 0c2e838

Browse files
Fix: Coverage and lint
1 parent 8b22aab commit 0c2e838

File tree

3 files changed

+81
-23
lines changed

3 files changed

+81
-23
lines changed

dir_content_diff/base_comparators.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -631,8 +631,7 @@ def diff(self, ref, comp, *args, **kwargs):
631631
res = pdfdiff_pages(ref, comp, *args, **kwargs)
632632
if not res:
633633
return False
634-
else:
635-
return res
634+
return res
636635

637636
def __call__(self, ref_file, comp_file, *args, **kwargs):
638637
"""Process arguments before calling the diff method."""

dir_content_diff/cli/__init__.py

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import click
1818
from yaml import safe_load
1919

20+
from dir_content_diff import _DEFAULT_EXPORT_SUFFIX
2021
from dir_content_diff import compare_files
2122
from dir_content_diff import compare_trees
2223
from dir_content_diff import export_formatted_file
@@ -42,22 +43,27 @@ def setup_logger(level: str = "info"):
4243
)
4344

4445

45-
def load_config(ctx, param, value):
46+
def load_config(ctx, param, value): # pylint: disable=unused-argument
4647
"""Load configuration from the given path."""
48+
# pylint: disable=raise-missing-from
4749
ctx.config = {}
4850
if value is not None:
4951
try:
5052
ctx.config = json.loads(value)
51-
except Exception as json_exc:
53+
except Exception: # pylint: disable=broad-exception-caught
54+
path = Path(value)
55+
if not path.exists():
56+
msg = f"The file '{path}' does not exist."
57+
raise FileNotFoundError(msg)
5258
try:
53-
path = Path(value)
54-
if not path.exists():
55-
msg = f"The file '{path}' does not exist."
56-
raise FileNotFoundError(msg)
57-
with path.open() as f:
59+
with path.open(encoding="utf-8") as f:
5860
ctx.config = safe_load(f.read())
59-
except Exception as path_exc:
60-
raise path_exc from json_exc
61+
except Exception: # pylint: disable=broad-exception-caught
62+
msg = (
63+
"Could not load the configuration because it could not be parsed as a JSON "
64+
"string nor as a YAML file."
65+
)
66+
raise SyntaxError(msg)
6167

6268

6369
@click.command(
@@ -149,8 +155,22 @@ def input_diff(ref, comp, config, export_formatted_files=False, sort_diffs=False
149155
diff = compare_files(ref, comp, comparator, **config)
150156
res = {str(ref): diff} if diff is not False else {}
151157
if export_formatted_files:
152-
export_formatted_file(ref, **config)
153-
export_formatted_file(comp, **config)
158+
export_formatted_file(
159+
ref,
160+
ref.with_name(ref.stem + _DEFAULT_EXPORT_SUFFIX).with_suffix(
161+
ref.suffix
162+
),
163+
comparator,
164+
**config,
165+
)
166+
export_formatted_file(
167+
comp,
168+
comp.with_name(comp.stem + _DEFAULT_EXPORT_SUFFIX).with_suffix(
169+
comp.suffix
170+
),
171+
comparator,
172+
**config,
173+
)
154174

155175
if res:
156176
if sort_diffs:

tests/test_cli.py

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import json
1313
import logging
14+
import re
1415

1516
import pytest
1617
import yaml
@@ -20,6 +21,8 @@
2021

2122

2223
class TestCli:
24+
"""Tests of the CLI."""
25+
2326
@pytest.fixture
2427
def config(self, tmp_path):
2528
"""The config as a dict."""
@@ -179,50 +182,86 @@ def test_diff_tree(
179182
)
180183
assert (tmp_path / "diff-pdf" / "file.pdf" / "diff-1.png").exists()
181184

185+
# Test with files and formatted files
186+
caplog.set_level(logging.DEBUG, logger="dir-content-diff")
187+
caplog.clear()
188+
ref_file = ref_tree / "file.json"
189+
res_file = res_tree_diff / "file.json"
190+
result = cli_runner.invoke(
191+
dir_content_diff.cli.main,
192+
[str(ref_file), str(res_file), "--config", config_file_str, "-f"],
193+
catch_exceptions=False,
194+
)
195+
assert result.stdout == ""
196+
nb_format_msg = 0
197+
for i in caplog.messages:
198+
if not i.startswith("Format:"):
199+
continue
200+
match = re.match(r"Format: \S+ into \S+", i)
201+
assert match is not None
202+
nb_format_msg += 1
203+
assert nb_format_msg == 2
204+
assert (tmp_path / "ref" / "file_FORMATTED.json").exists()
205+
assert (tmp_path / "res" / "file_FORMATTED.json").exists()
206+
182207
class TestFailures:
183-
def test_dir_file(self, cli_runner, caplog, ref_tree, res_tree_diff):
208+
"""Test that the proper exceptions are raised."""
209+
210+
def test_dir_file(self, cli_runner, ref_tree, res_tree_diff):
184211
"""Test exception when comparing a directory with a file."""
185212
ref_file = ref_tree / "file.pdf"
186213
res_file = res_tree_diff / "file.pdf"
187214
with pytest.raises(
188215
ValueError,
189-
match=r"The reference and compared inputs must both be either two directories or two files\.",
216+
match=(
217+
r"The reference and compared inputs must both be either two directories or two"
218+
r" files\."
219+
),
190220
):
191-
result = cli_runner.invoke(
221+
cli_runner.invoke(
192222
dir_content_diff.cli.main,
193223
[str(ref_tree), str(res_file)],
194224
catch_exceptions=False,
195225
)
196226
with pytest.raises(
197227
ValueError,
198-
match=r"The reference and compared inputs must both be either two directories or two files\.",
228+
match=(
229+
r"The reference and compared inputs must both be either two directories or two"
230+
r" files\."
231+
),
199232
):
200-
result = cli_runner.invoke(
233+
cli_runner.invoke(
201234
dir_content_diff.cli.main,
202235
[str(ref_file), str(res_tree_diff)],
203236
catch_exceptions=False,
204237
)
205238

206-
def test_not_existing_config(self, cli_runner, caplog):
239+
def test_not_existing_config(self, cli_runner):
207240
"""Test exception when the config file does not exist."""
208241
with pytest.raises(
209242
FileNotFoundError,
210243
match=r"The file '/NOT/EXISTING/FILE' does not exist\.",
211244
):
212-
result = cli_runner.invoke(
245+
cli_runner.invoke(
213246
dir_content_diff.cli.main,
214247
["/A/FILE", "/ANOTHER/FILE", "--config", "/NOT/EXISTING/FILE"],
215248
catch_exceptions=False,
216249
)
217250

218-
def test_bad_yaml_config(self, tmp_path, cli_runner, caplog):
251+
def test_bad_yaml_config(self, tmp_path, cli_runner):
219252
"""Test exception when the config file does not exist."""
220253
filepath = tmp_path / "config_file.yaml"
221254
with filepath.open("w", encoding="utf-8") as f:
222255
f.write("entry: &A !!!")
223256

224-
with pytest.raises(yaml.constructor.ConstructorError):
225-
result = cli_runner.invoke(
257+
with pytest.raises(
258+
SyntaxError,
259+
match=(
260+
r"Could not load the configuration because it could not be parsed as a JSON "
261+
r"string nor as a YAML file\."
262+
),
263+
):
264+
cli_runner.invoke(
226265
dir_content_diff.cli.main,
227266
["/A/FILE", "/ANOTHER/FILE", "--config", str(filepath)],
228267
catch_exceptions=False,

0 commit comments

Comments
 (0)