gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:42:51 24 4
gpt4 key购买 nike

我正在玩弄 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/

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