2

I'm trying to mock the below code snippet out, but have been hitting a wall.

with open(file_path, 'wb') as f:
    f.write(b''.join(byte_data))

In the test where I'm trying to mock this out, I don't actually want a file to be written too. I actually don't even care if the file is opened. There are multiple calls to open with arbitrary file_path. Ideally, this whole chuck would be mocked out.

I have tried using the mock_open helper, but not getting it to work.

In general I would like to just patch builtins.open and also whatever needs to be patched to patch the f.write(b''.join(byte_data)) portion of the code.

James
  • 1,158
  • 4
  • 13
  • 23
  • 1
    Just mocking `builtins.open` should be sufficient, `f` would also be a mock, so there is no need to mock `write` separately . What did you try? – MrBean Bremen Nov 11 '21 at 19:34

1 Answers1

0

You have to patch open() in the module where it's used, not where it's defined.

Module foo.py with the implementation:

def bar(file_path, byte_data):
    with open(file_path, "wb") as f:
        f.write(b''.join(byte_data))

Tests in test_foo.py, using the mocker fixture from the pytest-mock plugin:

import foo

def test_foo(mocker):
    mocker.patch("foo.open")
    foo.bar("somefilepath", [b"a", b"b", b"c"])

After patching open(), open is a unittest.mock.MagicMock object.