如何从另一个函数返回的实例模拟方法

2024-03-28 17:43:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何模拟create_bucket函数中的verify_token方法,从而引发异常

other_module.py

# ...

def get_connection(backend=None, **kwargs):
    klass = import_string(backend or settings.BACKEND)
    return klass(**kwargs)

module.py

from other_module import get_connection


def create_bucket():
    conn = get_connection()

    # ...

    try:
        conn.verify_token()
    except VerificationFailed:
        #...

tests.py

测试生成错误消息

AttributeError: module.create_bucket.get_connection does not have the attribute 'verify_token'
def test_create_bucket_with_failed_verification(mocker):
    mocker.patch.object(
        "module.get_connection",
        "verify_token",
        side_effect=VerificationFailed
    )

Tags: pyimporttokenbackendgetbucketdefcreate
1条回答
网友
1楼 · 发布于 2024-03-28 17:43:34

我通过模拟整个get_connection函数解决了这个问题:

mocker.patch(
    "module.get_connection",
    return_value=mocker.Mock(verify_token=mocker.Mock(side_effect=VerificationFailed)),
)

相关问题 更多 >