Mocking File Objects Or Iterables In Python
Which way is proper for mocking and testing code that iters object returned by open(), using mock library? whitelist_data.py: WHITELIST_FILE = 'testdata.txt' format_str = lambda s
Solution 1:
You're looking for a MagicMock
. This supports iteration.
In mock 0.80beta4, patch
returns a MagicMock
. So this simple example works:
import mock
deffoo():
for line inopen('myfile'):
print line
@mock.patch('__builtin__.open')deftest_foo(open_mock):
foo()
assert open_mock.called
If you're running mock 0.7.x (It looks like you are), I don't think you can accomplish this with patch alone. You'll need to create the mock separately, then pass it into patch:
import mock
deffoo():
for line inopen('myfile'):
print line
deftest_foo():
open_mock = mock.MagicMock()
with mock.patch('__builtin__.open', open_mock):
foo()
assert open_mock.called
Note - I've run these with py.test, however, these same approaches will work with unittest as well.
Post a Comment for "Mocking File Objects Or Iterables In Python"