类型安全模拟
typemock的Python项目详细描述
输入mock
python 3的类型安全模拟。
注意:此库仍在alpha中。它的api和实现可能会改变。
动机
Python中的嘲讽工具是强大的、灵活的,对于构建不同级别的独立测试是有用的。
这种灵活性是Python语言的一部分,也可能是任何动态类型语言的一部分。
然而,这种灵活性是有代价的。可以构建与它们所模拟的事物定义的实际行为或契约不一致的模拟。或者,让他们最初正确,然后与实际行为不同步,让测试保持绿色。
我们没有编译时保护来处理与他们定义的合同和那些合同的客户期望不一致的事情。
但是,现在我们有了类型提示。因此,我们可以显式地定义对象的契约,如果我们已经这样做了,我们也可以用类型安全的方式模拟它们。这就是这个图书馆的目标。类型安全模拟。
与mypy结合使用,这将导致更高保真的独立测试。
安装
pip install typemock
快速示例用法
给定某个类(其方法的实现不相关)
classMyThing:defmultiple_arg(self,prefix:str,number:int)->str:pass
模拟并验证
我们模拟行为并验证以下交互:
fromtypemockimporttmock,when,verifyexpected_result="a string"withtmock(MyThing)asmy_thing_mock:when(my_thing_mock.multiple_arg("p",1)).then_return(expected_result)actual=my_thing_mock.multiple_arg(number=1,prefix="p")assertexpected_result==actualverify(my_thing_mock).multiple_arg("p",1)
类型安全
当我们试图指定不符合对象契约的行为时,我们是在嘲笑
expected_result="a string"withtmock(MyThing)asmy_thing_mock:when(my_thing_mock.multiple_arg(prefix="p",number="should be an int")).then_return(expected_result)
我们得到一个信息错误,如
typemock.safety.MockTypeSafetyError: Method: multiple_arg Arg: number must be of type:<class 'int'>