Gwe*_*wen 10 python unit-testing mocking
我正在尝试模拟从文件读取.使用示例可以使用如下结构:
with patch('__builtin__.open', mock_open(read_data='1'), create=True) as m:
with open('foo') as h:
result = h.read()
Run Code Online (Sandbox Code Playgroud)
我想知道,有没有办法使用我的testcase注释来模拟open函数.喜欢:
@patch.object(__builtin__, 'open')
def test_check_status_running(self, m_open):
Run Code Online (Sandbox Code Playgroud)
我没有找到正确的方法,因为对我来说它适用于int并且不适用于字符串:
@patch.object(__builtin__, 'open')
def test_check_status_running1(self, m_open):
m_open = mock_open(read_data='1')
pid = open('testfile').read().strip()
print type(pid) # <class 'mock.MagicMock'>
self.assertEqual(1, int(pid)) # Pass
self.assertEqual('1', pid) # Fails MismatchError: '1' != <MagicMock name='open().read()' id='39774928'>
Run Code Online (Sandbox Code Playgroud)
小智 14
您可以通过open多种方式修补方法.我更喜欢修补builtins.open并将模拟对象传递给测试方法,如下所示:
from unittest.mock import patch, mock_open
from mymodule import method_that_read_with_open
class TestPatch(unittest.TestCase):
@patch('builtins.open', new_callable=mock_open, read_data='1')
def test_open_file(self, m):
string_read = method_that_read_with_open()
self.assertEqual(string_read, '1')
m.assert_called_with('filename', 'r')
Run Code Online (Sandbox Code Playgroud)
请注意,我们正在传递mock_open函数而不调用它!
但是因为你正在修补内置方法,你也可以这样做:
class TestPatch(unittest.TestCase):
@patch('builtins.open', mock_open(read_data='1'))
def test_open_file(self):
string_read = method_that_read_with_open()
self.assertEqual(string_read, '1')
open.assert_called_with('filename', 'r')
Run Code Online (Sandbox Code Playgroud)
这两个例子基本上是等价的:在第一个例子中,我们给patch方法一个工厂函数,他将调用它来创建模拟对象,在第二个我们使用已经创建的对象作为参数.