我在测试一个函数时遇到了一个问题,该函数读取文件的第一行,并在文件路径不存在时引发一个Exception
.
当前代码:
from unittest.mock import patch, mock_open
from pytest import raises
from os.path import exists
def read_from_file(file_path):
if not exists(file_path):
raise Exception("File does not exists!")
with open(file_path, "r") as f:
return f.read().splitlines()[0]
@patch("builtins.open", new_callable=mock_open, read_data="Correct string\nWrong string\nWrong string")
@patch("os.path.exists", return_value=True)
def test_read_file_and_returns_the_correct_string_with_multiple_lines(mock_os, mock_file):
result = read_from_file("xyz")
mock_file.assert_called_once_with("xyz", "r")
assert result == "Correct string"
@patch("builtins.open", new_callable=mock_open, read_data="Correct string")
@patch("os.path.exists", return_value=False)
def test_throws_exception_when_file_doesnt_exist(mock_os, mock_file):
with raises(Exception):
read_from_file("xyz")
decorator @patch("os.path.exists", return_value=True)
和@patch("os.path.exists", return_value=False)
似乎在两个测试中都没有效果.
我怎么能嘲笑文件的存在呢?