python - Python 的 create_autospec 中的实例参数有什么作用?

标签 python unit-testing mocking

我正在玩弄 Python 中的模拟自动规范。这是一个基本测试用例,其中我使用 create_autospec 自动指定 Django User 类.

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 时,测试通过了,那么这个参数到底有什么作用呢?它的目的是什么?我看到多篇博客文章将其设置为 True(herehere),所以我觉得这很重要。

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

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.

最佳答案

考虑模拟 int 类。与大多数类一样,int 是可调用的,因此 int 类的模拟也应该是可调用的。

另一方面,考虑模拟一个 int 实例。整数不可调用,因此模拟的整数也不应该是可调用的。

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() 行会引发异常。

关于python - Python 的 create_autospec 中的实例参数有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67258566/

相关文章:

使用正则表达式解析python字符串

ios - 在 Xcode 单元测试中模拟网络连接? (可能与 AFNetworking 有关)

iOS 重复实现 --> 测试失败

java - 如何在类中模拟整数

java - Getmethod Mokito java 模拟

c++ - 是否可以在非托管代码中使用 Mock/Fake 框架?

python - If 语句始终打印 (Python)

python - 如何测试处理设置文件所有权而不是 root 的函数

Python:我怎么知道我正在导入哪个包?

c# - 具有属性但没有逻辑单元可测试的类吗?