'Error Reading a NamedTemporaryFile from a Mock in Pytest

A toy example below:

# FIRST FILE
import tempfile
import second_file

def a():
   ntf = tempfile.NamedTemporaryFile()
   with open(ntf.name, 'w') as f:
       f.write('1234\n')
   return second_file.b(f)
# SECOND FILE
def b(f):
   with open(f, 'r') as g:
       data = g.read()
   return data

This code works fine. But in my case, I am using pytest to run tests, and I have mocked b. This is where I get some errors.

@pytest.fixture
def mocked_b(monkeypatch: Any) -> mock.Mock:
    mock_b = mock.Mock(return_value="1234\n")
    monkeypatch.setattr('second_file.b', mock_b)
    return mock_b

def test():
    a()
    temp_fileobj = mocked_b.call_args[0][0]
    with open(temp_fileobj.name, 'r') as f:
        pass

But that doesn't work! The with open(temp_fileobj errors, and I'm always getting:

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/[filename]'

What's going on here? Why is this happening in pytest but not in production? How do I fix this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source