使用 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