14.2 在�元测试中给对象打补�¶

问题¶

你写的�元测试中需�给指定的对象打补�, 用�断言它们在测试中的期望行为(比如,断言被调用时的�数个数,访问指定的属性等)。

解决方案¶

unittest.mock.patch() 函数�被用�解决这个问题。 patch() 还�被用作一个装饰器�上下文管�器或�独使用,尽管并�常�。 例如,下�是一个将它当�装饰器使用的例�:

from unittest.mock import patch
import example

@patch('example.func')
def test1(x, mock_func):
    example.func(x)       # Uses patched example.func
    mock_func.assert_called_with(x)

它还�以被当�一个上下文管�器:

with patch('example.func') as mock_func:
    example.func(x)      # Uses patched example.func
    mock_func.assert_called_with(x)

最�,你还�以手动的使用它打补�:

p = patch('example.func')
mock_func = p.start()
example.func(x)
mock_func.assert_called_with(x)
p.stop()

如果�能的�,你能够�加装饰器和上下文管�器�给多个对象打补�。例如:

@patch('example.func1')
@patch('example.func2')
@patch('example.func3')
def test1(mock1, mock2, mock3):
    ...

def test2():
    with patch('example.patch1') as mock1, \
         patch('example.patch2') as mock2, \
         patch('example.patch3') as mock3:
    ...

讨论¶

patch() 接�一个已存在对象的全路径�,将其替�为一个新的值。 原�的值会在装饰器函数或上下文管�器完��自动��回�。 默认情况下,所有值会被 MagicMock 实例替代。例如:

>>> x = 42
>>> with patch('__main__.x'):
...     print(x)
...
<MagicMock name='x' id='4314230032'>
>>> x
42
>>>

�过,你�以通过给 patch() �供第二个�数�将值替��任何你想�的:

>>> x
42
>>> with patch('__main__.x', 'patched_value'):
...     print(x)
...
patched_value
>>> x
42
>>>

被用�作为替�值的 MagicMock 实例能够模拟�调用对象和实例。 他们记录对象的使用信�并�许你执行断言检查,例如:

>>> from unittest.mock import MagicMock
>>> m = MagicMock(return_value = 10)
>>> m(1, 2, debug=True)
10
>>> m.assert_called_with(1, 2, debug=True)
>>> m.assert_called_with(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../unittest/mock.py", line 726, in assert_called_with
    raise AssertionError(msg)
AssertionError: Expected call: mock(1, 2)
Actual call: mock(1, 2, debug=True)
>>>

>>> m.upper.return_value = 'HELLO'
>>> m.upper('hello')
'HELLO'
>>> assert m.upper.called

>>> m.split.return_value = ['hello', 'world']
>>> m.split('hello world')
['hello', 'world']
>>> m.split.assert_called_with('hello world')
>>>

>>> m['blah']
<MagicMock name='mock.__getitem__()' id='4314412048'>
>>> m.__getitem__.called
True
>>> m.__getitem__.assert_called_with('blah')
>>>

一般�讲,这些�作会在一个�元测试中完�。例如,�设你已�有了�下�这样的函数:

# example.py
from urllib.request import urlopen
import csv

def dowprices():
    u = urlopen('http://finance.yahoo.com/d/quotes.csv?s=@^DJI&f=sl1')
    lines = (line.decode('utf-8') for line in u)
    rows = (row for row in csv.reader(lines) if len(row) == 2)
    prices = { name:float(price) for name, price in rows }
    return prices

正常�讲,这个函数会使用 urlopen() 从Web上�获�数�并解�它。 在�元测试中,你�以给它一个预先定义好的数�集。下�是使用补��作的例�:

import unittest
from unittest.mock import patch
import io
import example

sample_data = io.BytesIO(b'''\
"IBM",91.1\r
"AA",13.25\r
"MSFT",27.72\r
\r
''')

class Tests(unittest.TestCase):
    @patch('example.urlopen', return_value=sample_data)
    def test_dowprices(self, mock_urlopen):
        p = example.dowprices()
        self.assertTrue(mock_urlopen.called)
        self.assertEqual(p,
                         {'IBM': 91.1,
                          'AA': 13.25,
                          'MSFT' : 27.72})

if __name__ == '__main__':
    unittest.main()

本例中,�于 example 模�中的 urlopen() 函数被一个模拟对象替代, 该对象会返回一个包�测试数�的 ByteIO().

还有一点,在打补�时我们使用了 example.urlopen �代替 urllib.request.urlopen 。 当你创建补�的时候,你必须使用它们在测试代�中的�称。 由于测试代�使用了 from urllib.request import urlopen ,那么 dowprices() 函数 中使用的 urlopen() 函数实际上就�于 example 模�了。

本节实际上�是对 unittest.mock 模�的一次浅�辄止。 更多更高级的特性,请�考 官方文档