我在测试一个函数时遇到了一个问题,该函数读取文件的第一行,并在文件路径不存在时引发一个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)似乎在两个测试中都没有效果.

我怎么能嘲笑文件的存在呢?

推荐答案

出现错误是因为read_from_file直接从os.path导入exists并使用它,但mock目标是os.path.exists,这不影响直接导入.因此,真正的函数被执行,而不是mock.

read_from_file更改为:

import os.path

def read_from_file(file_path):
    if not os.path.exists(file_path):
        raise Exception("File does not exist!")
    with open(file_path, "r") as f:
        return f.read().splitlines()[0]

Python相关问答推荐

指示组内的rejected_time是否在creation_timestamp后5分钟内

如何计算列表列行之间的公共元素

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

处理带有间隙(空)的duckDB上的重复副本并有效填充它们

为什么sys.exit()不能与subproccess.run()或subprocess.call()一起使用

Python中的变量每次增加超过1

Python Pandas获取层次路径直到顶层管理

如何使用Numpy. stracards重新编写滚动和?

判断Python操作:如何从字面上得到所有decorator ?

如何过滤组s最大和最小行使用`transform`'

Python Mercury离线安装

如何将泛型类类型与函数返回类型结合使用?

在Django中重命名我的表后,旧表中的项目不会被移动或删除

如何使用大量常量优化代码?

如何编辑此代码,使其从多个EXCEL文件的特定工作表中提取数据以显示在单独的文件中

如何为需要初始化的具体类实现依赖反转和接口分离?

为什么我只用exec()函数运行了一次文件,而Python却运行了两次?

如何在Pandas中用迭代器求一个序列的平均值?

如何在Quarto中的标题页之前创建序言页

如果列包含空值,则PANAS查询不起作用