Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
eb85d97
test for copy_examples
cadenmyers13 Oct 13, 2025
918c559
news
cadenmyers13 Oct 13, 2025
6a26c9e
rm comment
cadenmyers13 Oct 13, 2025
3ab2efb
rm old tests
cadenmyers13 Oct 13, 2025
678d0b9
add user_input as param for copy_examples
cadenmyers13 Oct 14, 2025
15fd82a
add user inputs to test
cadenmyers13 Oct 14, 2025
d57e7fa
add cwd and user_target at same level as cases in tmp dir
cadenmyers13 Oct 14, 2025
79fa679
modify test for new tmp dir structure
cadenmyers13 Oct 14, 2025
a1fcf3b
fix testing matrix
cadenmyers13 Oct 14, 2025
fc1d0b0
add test for bad copy cases
cadenmyers13 Oct 14, 2025
a50c442
rm docstring
cadenmyers13 Oct 14, 2025
a04de5a
Add FileExistError test case
cadenmyers13 Oct 14, 2025
aa453b7
reverse logic for target_dir
cadenmyers13 Oct 14, 2025
e75a339
add additional dirs to tmp dir
cadenmyers13 Oct 15, 2025
f750453
move copy_examples inside PacksManager
cadenmyers13 Oct 15, 2025
49e745e
move copy_examples tests inside pm test
cadenmyers13 Oct 15, 2025
14fac59
rm tests from test_cli
cadenmyers13 Oct 15, 2025
909da70
add bad_target test
cadenmyers13 Oct 15, 2025
e66eb5f
rm duplicate copy_examples() in cli.py
cadenmyers13 Oct 16, 2025
42553c1
update docstring and param name
cadenmyers13 Oct 16, 2025
ef792d2
wrap str as list, add 4) to bad input test
cadenmyers13 Oct 16, 2025
4dc1538
rm param name from func signature
cadenmyers13 Oct 17, 2025
5820dd3
change scope from session to function
cadenmyers13 Oct 17, 2025
84e54a8
rglob examples after they are copied
cadenmyers13 Oct 17, 2025
6c38885
write text to the files and make check that the copied files have the…
cadenmyers13 Oct 17, 2025
3405e17
check exception message rather than the exception type
cadenmyers13 Oct 17, 2025
b8e4336
copy_examples returns None
cadenmyers13 Oct 17, 2025
1324185
sort list of paths, rm bad target test
cadenmyers13 Oct 17, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions news/copy-func2.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
**Added:**

* Add test for ``copy_examples`` function.

**Changed:**

* <news item>

**Deprecated:**

* <news item>

**Removed:**

* <news item>

**Fixed:**

* <news item>

**Security:**

* <news item>
6 changes: 5 additions & 1 deletion src/diffpy/cmi/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,18 @@


def copy_examples(
examples_dict: Dict[str, List[Tuple[str, Path]]], target_dir: Path = None
examples_dict: Dict[str, List[Tuple[str, Path]]],
user_input: List[str],
target_dir: Path = None,
) -> None:
"""Copy an example into the the target or current working directory.
Parameters
----------
examples_dict : dict
Dictionary mapping pack name -> list of (example, path) tuples.
user_input : list of str
List of user-specified pack(s) or example(s) to copy.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please review. Think this would be useful for parsing examples_dict

target_dir : pathlib.Path, optional
Target directory to copy examples into. Defaults to current
working directory.
Expand Down
182 changes: 130 additions & 52 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,65 +1,143 @@
import os
from pathlib import Path

import pytest

from diffpy.cmi import cli
from diffpy.cmi.packsmanager import PacksManager


def test_map_pack_to_examples_structure():
"""Test that map_pack_to_examples returns the right shape of
data."""
actual = cli.map_pack_to_examples()
assert isinstance(actual, dict)
for pack, exdirs in actual.items():
assert isinstance(pack, str)
assert isinstance(exdirs, list)
for ex in exdirs:
assert isinstance(ex, str)
# Check for known packs
assert "core" in actual.keys()
assert "pdf" in actual.keys()
# Check for known examples
assert ["linefit"] in actual.values()
def safe_get_examples(nonempty_packs, pack, n=None):
"""Return up to n examples if available."""
exs = nonempty_packs.get(pack, [])
if not exs:
return []
return exs if n is None else exs[:n]


@pytest.mark.parametrize(
"input_valid_str",
[
"core/linefit",
"pdf/ch03NiModelling",
],
)
def test_copy_example_success(tmp_path, input_valid_str):
"""Given a valid example format (<pack>/<ex>), test that its copied
to the temp dir."""
os.chdir(tmp_path)
actual = cli.copy_example(input_valid_str)
expected = tmp_path / Path(input_valid_str).name
assert expected.exists() and expected.is_dir()
assert actual == expected
def select_examples_subset(examples_dict, copy_type):
"""Select subset of examples depending on scenario.

Handles edge cases where some packs may be empty.
"""
subset = {}
if not examples_dict:
return {}
nonempty_packs = {k: v for k, v in examples_dict.items() if v}
if not nonempty_packs:
return {}
packs = list(nonempty_packs.keys())
if copy_type == "one_example":
pack = packs[0]
exs = safe_get_examples(nonempty_packs, pack, 1)
if exs:
subset[pack] = exs
elif copy_type == "multiple_examples_same_pack":
pack = packs[0]
exs = safe_get_examples(nonempty_packs, pack, 2)
if exs:
subset[pack] = exs
elif copy_type == "multiple_examples_diff_packs":
for pack in packs[:2]:
exs = safe_get_examples(nonempty_packs, pack, 1)
if exs:
subset[pack] = exs
elif copy_type == "pack_all_examples":
pack = packs[0]
exs = safe_get_examples(nonempty_packs, pack)
if exs:
subset[pack] = exs
elif copy_type == "multi_packs_all_examples":
for pack in packs[:2]:
exs = safe_get_examples(nonempty_packs, pack)
if exs:
subset[pack] = exs
elif copy_type == "combo_packs_and_examples":
first_pack = packs[0]
exs_first = safe_get_examples(nonempty_packs, first_pack, 1)
if exs_first:
subset[first_pack] = exs_first
if len(packs) > 1:
second_pack = packs[1]
exs_second = safe_get_examples(nonempty_packs, second_pack)
if exs_second:
subset[second_pack] = exs_second
elif copy_type == "all_packs_all_examples":
subset = nonempty_packs
else:
raise ValueError(f"Unknown copy_type: {copy_type}")
return subset


def verify_copied_files(subset, target_dir, case_dir):
"""Verify that all example files were copied correctly."""
if not subset:
if target_dir:
assert not any(target_dir.iterdir())
else:
pass
return
dest = target_dir or case_dir
assert dest.exists()
for pack, examples in subset.items():
for example_name, example_path in examples:
for ex_file in example_path.rglob("*.py"):
rel = ex_file.relative_to(example_path.parent.parent)
dest_file = dest / rel
assert dest_file.exists(), f"{dest_file} missing"

def test_copy_example_fnferror():
"""Test that FileNotFoundError is raised when the example does not
exist."""
with pytest.raises(FileNotFoundError):
cli.copy_example("pack/example1")

# Test copy_examples for various structural cases and copy scenarios.
# In total, 5 structural cases x 14 copy scenarios = 70 tests.
# The copy scenarios are:
# 1a) copy one example to cwd
# 1b) copy one example to a target dir
# 2a) copy multiple examples from same pack to cwd
# 2b) copy multiple examples from same pack to a target dir
# 3a) copy multiple examples from different packs to cwd
# 3b) copy multiple examples from different packs to a target dir
# 4a) copy all examples from a pack to cwd
# 4b) copy all examples from a pack to a target dir
# 5a) copy all examples from multiple packs to cwd
# 5b) copy all examples from multiple packs to target dir
# 6a) copy a combination of packs and examples to cwd
# 6b) copy a combination of packs and examples to target
# 7a) copy all examples from all packs to cwd
# 7b) copy all examples from all packs to a target dir

copy_scenarios = [
("one_example", "cwd"),
("one_example", "target"),
("multiple_examples_same_pack", "cwd"),
("multiple_examples_same_pack", "target"),
("multiple_examples_diff_packs", "cwd"),
("multiple_examples_diff_packs", "target"),
("pack_all_examples", "cwd"),
("pack_all_examples", "target"),
("multi_packs_all_examples", "cwd"),
("multi_packs_all_examples", "target"),
("combo_packs_and_examples", "cwd"),
("combo_packs_and_examples", "target"),
("all_packs_all_examples", "cwd"),
("all_packs_all_examples", "target"),
]


@pytest.mark.parametrize(
"case_name",
["case1", "case2", "case3", "case4", "case5"],
)
@pytest.mark.parametrize(
"input_bad_str",
[
"", # empty string
"/", # missing pack and example
"corelinefit", # missing slash
"linefit", # missing pack and slash
"core/", # missing example
"/linefit", # missing pack
"core/linefit/extra", # too many slashes
],
"copy_type, target_type",
copy_scenarios,
)
def test_copy_example_valueerror(input_bad_str):
"""Test that ValueError is raised when the format is invalid."""
with pytest.raises(ValueError):
cli.copy_example(input_bad_str)
def test_copy_examples(
case_name, copy_type, target_type, example_cases, tmp_path
):
"""Test copy_examples for all structural and copy scenarios."""
case_dir = example_cases / case_name
pm = PacksManager(root_path=case_dir)
examples_dict = pm.available_examples()
target_dir = None if target_type == "cwd" else tmp_path / "target"
if target_dir:
target_dir.mkdir(parents=True, exist_ok=True)
subset = select_examples_subset(examples_dict, copy_type)
cli.copy_examples(subset, target_dir=target_dir)
verify_copied_files(subset, target_dir, case_dir)
Loading