Код: Выделить всё
import pytest
import pathlib
class SecondFileError(Exception):
def __init__(self, message):
super().__init__(message)
def check_files(file: pathlib.Path) -> tuple[pathlib.Path, pathlib.Path]:
# check if file exists:
if not file.exists():
raise FileNotFoundError(f"File {file} does not exist")
# second file (these files should always be together)
second_file = file.parent / f"{file.stem}_second{file.suffix}"
if not second_file.exists():
raise SecondFileError(f"{second_file} not found")
return (file, second_file)
def test_check_file_correct(mocker):
file = pathlib.Path("test.txt")
second_file = pathlib.Path("test_second.txt")
mocker.patch("pathlib.Path.exists", return_value=True)
res = check_files(file)
assert res[0] == file
assert res[1] == second_file
def test_check_no_file(mocker):
file = pathlib.Path("test.txt")
mocker.patch("pathlib.Path.exists", return_value=False)
with pytest.raises(FileNotFoundError):
check_files(file)
Я попробовал следующее:
Код: Выделить всё
def test_with_file_without_second_file(mocker):
file = pathlib.Path("test.txt")
file.exists = mocker.MagicMock(exists=True)
with pytest.raises(SecondFileError):
check_files(file)
>>> AttributeError: 'WindowsPath' object attribute 'exists' is read-only
def test_with_file_without_second_file(mocker):
file = pathlib.Path("test.txt")
# file.exists = mocker.MagicMock(exists=True)
mock_exists = mocker.patch.object(file, "exists", return_value=True)
with pytest.raises(SecondFileError):
check_files(file)
>>> AttributeError: 'WindowsPath' object attribute 'exists' is read-only
def test_with_file_without_second_file(mocker):
file = pathlib.Path("test.txt")
mocker.patch.object(
file,
"__getattr__",
side_effect=lambda attr: True if attr == "exists" else AttributeError,
)
with pytest.raises(SecondFileError):
check_files(file)
>>> AttributeError: test.txt does not have the attribute '__getattr__'
Подробнее здесь: https://stackoverflow.com/questions/793 ... of-pathlib
Мобильная версия