1

I am having trouble patching the open method of my module with mock_open as suggested in the docs.

import my_module
import mock

def test_foo():
    m = mock.mock_open()
    with patch('my_module.open', m, create=True):
        my_module.io_func()

>>> test_foo()
IOError: [Errno 2] No such file or directory: 'foofile'

Any idea why the patch isn't working?

Alternatively, the following executes as expected:

import my_module
import mock

def test_foo():
    m = mock.mock_open()
    my_module.__builtins__['open'] = m
    my_module.io_func()

However, this feels like a hack.

bfb
  • 447
  • 4
  • 12
  • I cannot reproduce your issue: `patch('my_module.open', m, create=True)` work on my side. Can you post `my_module` code? I guess that you don't use `open()` but something like `os.open()` in `my_module`. – Michele d'Amico Feb 24 '15 at 13:13
  • I don't think this is the case or my_module.__builtins__['open'] = m would not work. – bfb Feb 24 '15 at 18:41
  • 1
    Anyway, cut and paste your code and create a module that use open work like a charm – Michele d'Amico Feb 24 '15 at 19:00
  • Is it possible that there is a place where you copy open method and then use the copy (for instance a decorarator)? – Michele d'Amico Feb 24 '15 at 19:04
  • @Michele No, nothing fancy going on. Also, I found the 2.7 backport of unittest.mock to be insufficient. mock_open was patched in 3.4 https://bugs.python.org/issue17467 to use readline(s), and this patch has not made it downstream to 2.7 yet. I opted instead to make a file, write to it, close it, read it in from the function I am testing, and remove it. – bfb Feb 24 '15 at 20:01
  • 1
    @Michele, you're right.. the toy code works. The only difference between the code I'm testing and the toy code, as far as I can tell, is the import is more extravagant. from my_lib.my_sub_lib import my_module as mm rather than... import my_module (Meta, newlines don't stick in comment boxes?) – bfb Feb 24 '15 at 20:10
  • Ok I found it: when you use `from a import b as c` you create a new reference of `b` and patch `b` have no effect on `c`. [Take a look to that answer](http://stackoverflow.com/questions/28546137/python-mock-with-from-x-import-y/28570892#28570892) and let me know if that is the case. – Michele d'Amico Feb 24 '15 at 20:31

0 Answers0