gpt4 book ai didi

python - 使用 Pytest 在函数中模拟引发异常

转载 作者:行者123 更新时间:2023-12-03 08:19:29 27 4
gpt4 key购买 nike

我有以下函数 get_postgres_connection。我正在尝试使用 test_get_postgres_connection_unsuccess 运行单元测试来命中异常。

def get_postgres_connection():

try:
conn = psycopg2.connect(dbname = POSTGRES_DATABASE,
user = POSTGRES_USER,
password = POSGRES_PASSWORD,
host = POSTGRES_HOST,
port = POSTGRES_PORT)
conn.autocommit = True

return conn

except Exception as err:
logging.error('Unable to connect to postgres db: %s', err)


def test_get_postgres_connection_unsuccess(monkeypatch):
""" tests an exception is hit if the connection to postgres is unsuccesful"""

# setup
class mock_conn:
def __init__(self, dbname, user, password, host, port):
raise ConnectionError('This fake connection did not work')

autocommit = False

monkeypatch.setattr(psycopg2, 'connect', mock_conn)

我无法在模拟函数中成功引发异常。有人知道我在这里做错了什么吗?

编辑:稍微清理一下代码

最佳答案

无需创建自己的模拟类 - 使用 unittest.mock.MagicMock 代替。

您可以使用 MagicMock 实例来模拟任何内容,包括第三方函数。如果添加 side_effect=Exception() 参数,则调用模拟时会引发异常。

Python 甚至允许您在上下文管理器中执行此操作(with ... 语句),以便一旦上下文管理器 block 结束,模拟函数就会“取消模拟”。

最小示例:

def some_external_lib():  # this is psycopg2.connect in your example
pass

def my_func(): # this is get_postgres_connection in your example
try:
some_external_lib()
except Exception as e:
print(f"Error found: {e}")


import unittest
from unittest import mock

class TestMyFunc(unittest.TestCase):
def test_my_func_external_lib_raises_exception(self):
with mock.patch('__main__.some_external_lib', side_effect=Exception("ERROR")):
my_func()


# Running example - prints the error message
t = TestMyFunc()
t.test_my_func_external_lib_raises_exception()

请注意,正如所编写的那样,测试现在实际上并没有测试任何内容。查看 get_postgres_connection 函数的主体,您可能想测试它是否返回 None,以及是否将某些内容写入日志文件,因为外部库引发了异常(exception)。

关于python - 使用 Pytest 在函数中模拟引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68309192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com