使用pytest在函数中模拟引发异常

sf6xfgos  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(306)

我有以下函数get\u postgres\u connection。我正在尝试运行unittest,test\u get\u postgres\u connection\u未成功命中异常。

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)

我无法在模拟函数中成功引发异常。有人知道我做错了什么吗?
编辑:稍微整理一下代码

yvt65v4c

yvt65v4c1#

无需创建自己的模拟类-使用 unittest.mock.MagicMock 相反
你可以使用 MagicMock 示例来模拟任何东西,包括第三方函数。如果您添加 side_effect=Exception() 参数,则在调用模拟时引发异常。
python甚至允许您在上下文管理器中执行此操作( with ... 语句),以便在上下文管理器块结束后,mock函数得到“unmock”。
最简单的例子:

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 ,以及在外部库引发异常的情况下是否将某些内容写入日志文件。

gfttwv5a

gfttwv5a2#

下面是我如何使用mock修复测试函数的,如上所述

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

        # assert
        with mock.patch('psycopg2.connect', side_effect=Exception('ERROR')):
            self.pg_db.get_postgres_connection()

相关问题