使用 unittest.mock.create autospec 模拟函数

模拟函数的一种方法是使用 create_autospec 函数,该函数将根据其规范模拟对象。使用函数,我们可以使用它来确保它们被适当地调用。

custom_math.py 中使用 multiply

def multiply(a, b):
    return a * b

process_math.py 中的函数 multiples_of

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

我们可以通过嘲笑 multiply 来单独测试 multiples_of。下面的示例使用 Python 标准库 unittest,但这也可以与其他测试框架一起使用,例如 pytest 或 nose:

from unittest.mock import create_autospec
import unittest

# we import the entire module so we can mock out multiply
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) # this should raise a TypeError