[英]How to use mock_open() with patch.object() in test annotation
I'm trying to mock read from file. 我正在尝试模拟从文件读取。 Using examples it can be done with a construction like:
使用示例可以使用如下结构:
with patch('__builtin__.open', mock_open(read_data='1'), create=True) as m:
with open('foo') as h:
result = h.read()
I wonder, is there a way to mock open function using my testcase annotation. 我想知道,有没有办法使用我的testcase注释来模拟open函数。 Like:
喜欢:
@patch.object(__builtin__, 'open')
def test_check_status_running(self, m_open):
I don't find the correct way, because for me it works for int and doesn't work for strings: 我没有找到正确的方法,因为对我来说它适用于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'>
You can patch the open
method in many ways. 您可以通过多种方式修补
open
方法。 I prefer to patch the builtins.open
and to pass the mocked object to the test method like this: 我更喜欢修补
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')
Note that we are passing the mock_open function without calling it! 请注意,我们正在传递mock_open函数而不调用它!
But because you are patching the builtin method, you can also do: 但是因为你正在修补内置方法,你也可以这样做:
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')
This two examples are basically equivalent: in the first one we are giving to the patch method a factory function that he will invoke to create the mock object, in the second one we are using an already created object as argument. 这两个例子基本上是等价的:在第一个例子中,我们给patch方法一个工厂函数,他将调用它来创建模拟对象,在第二个我们使用已经创建的对象作为参数。
Assign a mock_open instance to the new_callable parameter: 将mock_open实例分配给new_callable参数:
class TestClass(unittest.TestCase):
@mock.patch('file_tested.open', new_callable=mock.mock_open())
def test_function(self, mock_open):
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.