Pytest имитирует два экземпляра pathlibPython

Программы на Python
Ответить
Anonymous
 Pytest имитирует два экземпляра pathlib

Сообщение Anonymous »

У меня есть следующая функция, которую я хочу протестировать. Я не хочу использовать tmp_path, поэтому пытаюсь все имитировать с помощью pytest-mock.

Код: Выделить всё

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__'
И много других вариантов, но все сводится к ошибке только для чтения. Множество примеров в Интернете показывают, как установить для функции класса значение true, но я хотел бы посмеяться над этим на экземпляре класса pathlib.Path.

Подробнее здесь: https://stackoverflow.com/questions/793 ... of-pathlib
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»