You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_file_utils.py 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from pathlib import Path
  2. import pytest
  3. from libs.file_utils import search_file_upwards
  4. def test_search_file_upwards_found_in_parent(tmp_path: Path):
  5. base = tmp_path / "a" / "b" / "c"
  6. base.mkdir(parents=True)
  7. target = tmp_path / "a" / "target.txt"
  8. target.write_text("ok", encoding="utf-8")
  9. found = search_file_upwards(base, "target.txt", max_search_parent_depth=5)
  10. assert found == target
  11. def test_search_file_upwards_found_in_current(tmp_path: Path):
  12. base = tmp_path / "x"
  13. base.mkdir()
  14. target = base / "here.txt"
  15. target.write_text("x", encoding="utf-8")
  16. found = search_file_upwards(base, "here.txt", max_search_parent_depth=1)
  17. assert found == target
  18. def test_search_file_upwards_not_found_raises(tmp_path: Path):
  19. base = tmp_path / "m" / "n"
  20. base.mkdir(parents=True)
  21. with pytest.raises(ValueError) as exc:
  22. search_file_upwards(base, "missing.txt", max_search_parent_depth=3)
  23. # error message should contain file name and base path
  24. msg = str(exc.value)
  25. assert "missing.txt" in msg
  26. assert str(base) in msg
  27. def test_search_file_upwards_root_breaks_and_raises():
  28. # Using filesystem root triggers the 'break' branch (parent == current)
  29. with pytest.raises(ValueError):
  30. search_file_upwards(Path("/"), "__definitely_not_exists__.txt", max_search_parent_depth=1)
  31. def test_search_file_upwards_depth_limit_raises(tmp_path: Path):
  32. base = tmp_path / "a" / "b" / "c"
  33. base.mkdir(parents=True)
  34. target = tmp_path / "a" / "target.txt"
  35. target.write_text("ok", encoding="utf-8")
  36. # The file is 2 levels up from `c` (in `a`), but search depth is only 2.
  37. # The search path is `c` (depth 1) -> `b` (depth 2). The file is in `a` (would need depth 3).
  38. # So, this should not find the file and should raise an error.
  39. with pytest.raises(ValueError):
  40. search_file_upwards(base, "target.txt", max_search_parent_depth=2)