Skip to content

Commit

Permalink
Test: Fix
Browse files Browse the repository at this point in the history
  • Loading branch information
adrien-berchet committed Nov 15, 2024
1 parent 88c9494 commit 8b22aab
Show file tree
Hide file tree
Showing 4 changed files with 164 additions and 24 deletions.
2 changes: 1 addition & 1 deletion dir_content_diff/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def export_formatted_file(file, formatted_file, comparator, **kwargs):
),
)
else:
LOGGER.info(
LOGGER.debug(
"Skip formatting for '%s' because the comparator has no saving capability.",
file,
)
Expand Down
19 changes: 10 additions & 9 deletions dir_content_diff/base_comparators.py
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ def diff(self, ref, comp, *args, **kwargs):
Keyword Args:
threshold (int): The threshold used to compare the images.
tempdir (pathlib.Path): Directory in which a new ``dir-diff` directory will be created
tempdir (pathlib.Path): Directory in which a new ``dir-diff`` directory will be created
to export the debug images.
dpi (int): The resolution used to convert the PDF files into images.
verbosity (int): The log verbosity.
Expand Down Expand Up @@ -668,12 +668,14 @@ def __call__(self, ref_file, comp_file, *args, **kwargs):

try:
# Update default verbosity
if "verbosity" not in kwargs:
if "verbosity" not in kwargs: # pragma: no branch
current_default_verbosity = int(
diff_pdf_visually.constants.DEFAULT_VERBOSITY
)
try:
if diff_pdf_visually.diff.pdfdiff_pages.__defaults__[1] is None:
if (
diff_pdf_visually.diff.pdfdiff_pages.__defaults__[1] is None
): # pragma: no cover
diff_pdf_visually.constants.DEFAULT_VERBOSITY = 0
else:
kwargs["verbosity"] = 0
Expand Down Expand Up @@ -701,12 +703,11 @@ def report(
**kwargs,
): # pylint: disable=too-many-arguments
"""Add specific information before calling the default method."""
if formatted_differences:
if isinstance(formatted_differences, str):
formatted_differences = (
"The following pages are the most different: "
+ formatted_differences.replace("\n", ", ")
)
if formatted_differences and isinstance(formatted_differences, str):
formatted_differences = (
"The following pages are the most different: "
+ formatted_differences.replace("\n", ", ")
)
if "tempdir" in diff_kwargs:
formatted_differences += (
"\nThe visual differences can be found here: "
Expand Down
12 changes: 8 additions & 4 deletions dir_content_diff/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,25 +140,29 @@ def input_diff(ref, comp, config, export_formatted_files=False, sort_diffs=False
specific_args=config,
export_formatted_files=export_formatted_files,
)
if sort_diffs:
res = sorted(res.items(), key=lambda x: x[0])
else:
comparator_name = config.pop("comparator", None)
comparator = pick_comparator(
comparator=comparator_name,
suffix=ref.suffix,
)
res = {str(ref): compare_files(ref, comp, comparator, **config)}
diff = compare_files(ref, comp, comparator, **config)
res = {str(ref): diff} if diff is not False else {}
if export_formatted_files:
export_formatted_file(ref, **config)
export_formatted_file(comp, **config)

if res:
if sort_diffs:
res_list = sorted(res.items(), key=lambda x: x[0])
else:
res_list = res.items()

LOGGER.info(
"Differences found between '%s' and '%s':\n\n\n%s",
ref,
comp,
("\n\n\n".join([i[1] for i in res.items()])),
("\n\n\n".join([i[1] for i in res_list])),
)
else:
LOGGER.info("No difference found between '%s' and '%s'", ref, comp)
155 changes: 145 additions & 10 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,38 @@ def config(self, tmp_path):
return {"file.pdf": {"tempdir": str(tmp_path)}}

@pytest.fixture
def config_json(self, config):
def config_tree_json(self, config):
"""The config as a JSON string."""
return json.dumps(config)

@pytest.fixture
def config_yaml(self, config, tmp_path):
def config_file_json(self, config):
"""The config as a JSON string."""
return json.dumps(config["file.pdf"])

@pytest.fixture
def config_tree_yaml(self, config, tmp_path):
"""The config as a YAML file."""
filepath = tmp_path / "config.yaml"
filepath = tmp_path / "config_tree.yaml"
with filepath.open("w", encoding="utf-8") as f:
yaml.dump(config, f)
return filepath

@pytest.fixture
def config_str(self, request):
def config_file_yaml(self, config, tmp_path):
"""The config as a YAML file."""
filepath = tmp_path / "config_file.yaml"
with filepath.open("w", encoding="utf-8") as f:
yaml.dump(config["file.pdf"], f)
return filepath

@pytest.fixture
def config_tree_str(self, request):
"""The string given to the CLI to pass the config."""
return request.getfixturevalue(request.param)

@pytest.fixture
def config_file_str(self, request):
"""The string given to the CLI to pass the config."""
return request.getfixturevalue(request.param)

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

@pytest.mark.parametrize(
"config_str", ["config_json", "config_yaml"], indirect=True
"config_tree_str,config_file_str",
[
["config_tree_json", "config_file_json"],
["config_tree_yaml", "config_file_yaml"],
],
indirect=True,
)
def test_equal_tree(
self, tmp_path, ref_tree, res_tree_equal, config_str, cli_runner, caplog
self,
tmp_path,
ref_tree,
res_tree_equal,
config_tree_str,
config_file_str,
cli_runner,
caplog,
):
"""Test with equal trees."""
caplog.set_level(logging.INFO, logger="dir-content-diff")

# Test with trees
result = cli_runner.invoke(
dir_content_diff.cli.main,
[str(ref_tree), str(res_tree_equal), "--config", config_str],
[str(ref_tree), str(res_tree_equal), "--config", config_tree_str],
catch_exceptions=False,
)
assert result.stdout == ""
assert caplog.messages == [
f"No difference found between '{ref_tree}' and '{res_tree_equal}'"
]
assert (tmp_path / "diff-pdf" / "file.pdf" / "diff-1.png").exists()

# Test with files
caplog.clear()
ref_file = ref_tree / "file.pdf"
res_file = res_tree_equal / "file.pdf"
result = cli_runner.invoke(
dir_content_diff.cli.main,
[str(ref_file), str(res_file), "--config", config_file_str],
catch_exceptions=False,
)
assert result.stdout == ""
assert caplog.messages == [
f"No difference found between '{ref_file}' and '{res_file}'"
]
assert (tmp_path / "diff-pdf" / "file.pdf" / "diff-1.png").exists()

@pytest.mark.parametrize(
"config_str", ["config_json", "config_yaml"], indirect=True
"config_tree_str,config_file_str",
[
["config_tree_json", "config_file_json"],
["config_tree_yaml", "config_file_yaml"],
],
indirect=True,
)
def test_diff_tree(
self, tmp_path, ref_tree, res_tree_diff, config_str, cli_runner, caplog
self,
tmp_path,
ref_tree,
res_tree_diff,
config_tree_str,
config_file_str,
cli_runner,
caplog,
):
"""Test with different trees."""
caplog.set_level(logging.INFO, logger="dir-content-diff")

# Test with trees
result = cli_runner.invoke(
dir_content_diff.cli.main,
[str(ref_tree), str(res_tree_diff), "--config", config_str],
[
str(ref_tree),
str(res_tree_diff),
"--config",
config_tree_str,
"--sort-diffs",
"--export-formatted-files",
],
)
assert result.stdout == ""
assert len(caplog.messages) == 1
Expand All @@ -93,6 +162,72 @@ def test_diff_tree(
)
assert (tmp_path / "diff-pdf" / "file.pdf" / "diff-1.png").exists()

# Test with files
caplog.clear()
ref_file = ref_tree / "file.pdf"
res_file = res_tree_diff / "file.pdf"
result = cli_runner.invoke(
dir_content_diff.cli.main,
[str(ref_file), str(res_file), "--config", config_file_str],
catch_exceptions=False,
)
assert result.stdout == ""
assert len(caplog.messages) == 1
assert (
f"Differences found between '{ref_file}' and '{res_file}':"
in caplog.messages[0]
)
assert (tmp_path / "diff-pdf" / "file.pdf" / "diff-1.png").exists()

class TestFailures:
def test_dir_file(self, cli_runner, caplog, ref_tree, res_tree_diff):
"""Test exception when comparing a directory with a file."""
ref_file = ref_tree / "file.pdf"
res_file = res_tree_diff / "file.pdf"
with pytest.raises(
ValueError,
match=r"The reference and compared inputs must both be either two directories or two files\.",
):
result = cli_runner.invoke(
dir_content_diff.cli.main,
[str(ref_tree), str(res_file)],
catch_exceptions=False,
)
with pytest.raises(
ValueError,
match=r"The reference and compared inputs must both be either two directories or two files\.",
):
result = cli_runner.invoke(
dir_content_diff.cli.main,
[str(ref_file), str(res_tree_diff)],
catch_exceptions=False,
)

def test_not_existing_config(self, cli_runner, caplog):
"""Test exception when the config file does not exist."""
with pytest.raises(
FileNotFoundError,
match=r"The file '/NOT/EXISTING/FILE' does not exist\.",
):
result = cli_runner.invoke(
dir_content_diff.cli.main,
["/A/FILE", "/ANOTHER/FILE", "--config", "/NOT/EXISTING/FILE"],
catch_exceptions=False,
)

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

with pytest.raises(yaml.constructor.ConstructorError):
result = cli_runner.invoke(
dir_content_diff.cli.main,
["/A/FILE", "/ANOTHER/FILE", "--config", str(filepath)],
catch_exceptions=False,
)


def test_entry_point(script_runner):
"""Test the entry point."""
Expand Down

0 comments on commit 8b22aab

Please sign in to comment.