我正在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=True
和instance=False
时,测试通过了,那么这个参数到底做了什么呢?它的目的是什么?我看过多篇博客文章将其设置为True
(here和here),所以我觉得这很重要
文档中说了以下内容,但对我来说没有意义:
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.
考虑嘲笑^ {< CD1>}类。^。{}与大多数类一样是可调用的,因此
int
类的模拟也应该是可调用的另一方面,考虑嘲讽^ {< CD1>}实例。整数是不可调用的,因此整数的模拟也不应被调用
instance
参数允许您控制您获得的行为create_autospec(int, instance=False)
返回可调用的模拟,而create_autospec(int, instance=True)
返回不可调用的模拟。如果你这样做只有
m2()
行将引发异常相关问题 更多 >
编程相关推荐