Python使用unittest.mock.create_autospec模拟功能
示例
模拟功能的一种方法是使用create_autospec功能,该功能将根据其规格模拟对象。使用函数,我们可以使用它来确保正确调用它们。
与函数multiply中custom_math.py:
def multiply(a, b):
return a * b和一个函数multiples_of中process_math.py:
from custom_math import multiply
def multiples_of(integer, *args, num_multiples=0, **kwargs):
"""
:rtype: list
"""
multiples = []
for x in range(1, num_multiples + 1):
"""
Passing in args and kwargs here will only raise TypeError if values were
passed to multiples_of function, otherwise they are ignored. This way we can
test that multiples_of is used correctly. This is here for an illustration
of how create_autospec works. Not recommended for production code.
"""
multiple = multiply(integer,x, *args, **kwargs)
multiples.append(multiple)
return multiples我们可以multiples_of通过模拟单独测试multiply。下面的示例使用Python标准库unittest,但是它也可以与其他测试框架一起使用,例如pytest或鼻子:
fromunittest.mockimport create_autospec
import unittest
#我们导入整个模块,以便我们可以模拟出乘法
import custom_math
custom_math.multiply = create_autospec(custom_math.multiply)
from process_math import multiples_of
class TestCustomMath(unittest.TestCase):
def test_multiples_of(self):
multiples = multiples_of(3, num_multiples=1)
custom_math.multiply.assert_called_with(3, 1)
def test_multiples_of_with_bad_inputs(self):
with self.assertRaises(TypeError) as e:
multiples_of(1, "extra arg", num_multiples=1) #这应该引发TypeError