Mocking with h5py returning dictionary in Python

Viewed 65

I have the following in a function:

import h5py

with h5py.File(path, 'r') as f:
    big = f['big']
    box = f['box']

I'm currently writing a test for the function where I try to mock it by something like:

def test_function(mocker):
    mocker.patch("h5py.File", new=mocker.mock_open())
    ...

Where mocker comes from: https://pypi.org/project/pytest-mock/

What I want to achieve is for the mock to return me a dict by the name of f so I'm able to interact with it such as in the function above.

Is this possible, I'm prepared to use whatever brute force solution possible out there...

br. KJ

1 Answers

As described here, you need to ensure the result of h5py.File().__enter__() returns an appropriate dictionary:

from unittest import mock
import h5py
import pytest


def foo():
    with h5py.File('.', 'r') as f:
        big = f['big']
        box = f['box']

    return big, box


def test_foo(mocker):
    d = {'big': 1, 'box': 2}

    m = mocker.MagicMock()
    m.__enter__.return_value = d

    mocker.patch("h5py.File",
                 return_value=m)

    assert foo() == (1,2)
Related