我正在尝试模拟从文件中读取。使用示例可以通过以下结构完成:
with patch('__builtin__.open', mock_open(read_data='1'), create=True) as m:
with open('foo') as h:
result = h.read()
我想知道,有没有办法使用我的测试用例注释来模拟开放函数。喜欢:
@patch.object(__builtin__, 'open')
def test_check_status_running(self, m_open):
我找不到正确的方法,因为对我来说它适用于 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'>