Python的create_autospec中的实例参数做什么?

2024-06-07 03:17:23 发布

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

我正在Python中玩模拟自动规范。这里是一个基本的测试用例,我使用create_autospec自动检测DjangoUser

from unittest.mock import create_autospec
from django.contrib.auth.models import User

def test_mock_spec():
    user = create_autospec(User, spec_set=True, instance=True, username="batman")
    assert user.username == "batman"
    with pytest.raises(AttributeError):
        create_autospec(User, spec_set=True, x1=1)
    with pytest.raises(AttributeError):
        assert user.x2

当我同时设置instance=Trueinstance=False时,测试通过了,那么这个参数到底做了什么呢?它的目的是什么?我看过多篇博客文章将其设置为Trueherehere),所以我觉得这很重要

文档中说了以下内容,但对我来说没有意义:

If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing instance=True. The returned mock will only be callable if instances of the mock are callable.


Tags: oftheinstancefromimporttruecreateusername
1条回答
网友
1楼 · 发布于 2024-06-07 03:17:23

考虑嘲笑^ {< CD1>}类。^。{}与大多数类一样是可调用的,因此int类的模拟也应该是可调用的

另一方面,考虑嘲讽^ {< CD1>}实例。整数是可调用的,因此整数的模拟也不应被调用

instance参数允许您控制您获得的行为create_autospec(int, instance=False)返回可调用的模拟,而create_autospec(int, instance=True)返回不可调用的模拟。如果你这样做

m1 = create_autospec(int, instance=False)
m2 = create_autospec(int, instance=True)

m1()
m2()

只有m2()行将引发异常

相关问题 更多 >