2

Something similar has been asked before, but I'm struggling to get this to work.

How do I mock an import module from another file

I have one file:
b.py (named to be consistent with the linked docs)

import cv2   # module 'a' in the linked docs

def get_video_frame(path):
    vidcap = cv2.VideoCapture(path)  # `a.SomeClass` in the linked docs
    vidcap.isOpened()
    ...

test_b.py

import b
import pytest # with pytest-mock installed

def test_get_frame(mocker):

    mock_vidcap = mocker.Mock()
    mock_vidcap.isOpened.side_effect = AssertionError

    mock_cv2 = mocker.patch('cv2.VideoCapture')
    mock_cv2.return_value = mock_vidcap

    b.get_video_frame('foo')    # Doesn't fail

    mock_vidcap.isOpened.assert_called()   # fails

I set the tests up like this because in where to patch it specifies that if

In this case the class we want to patch is being looked up on the a module and so we have to patch a.SomeClass instead:

@patch(‘a.SomeClass’)

I've tried a few other combinations of patching, but it exhibits the same behavior, which suggests I'm not successfully patching the module. If the patch were to be applied b.get_video_frame('foo') would fail due to the side_effect; having assert_called fail, supports this.

Edit in an effort to reduce the length of the question I left off the rest of get_video_frame. Unfortunitly, the parts left off we're the critical parts. The full function is:

def get_video_frame(path):
    vidcap = cv2.VideoCapture(path)  # `a.SomeClass` in the linked docs
    is_open = vidcap.isOpened()
    while True:
        is_open, frame = vidcap.read()
        if is_open:
            yield frame
        else:
            break
0

1 Answer 1

2

This line just creates a generator:

b.get_video_frame('foo')

The line is_open = vidcap.isOpened() is never reached, because in the test function the generator remains frozen at the start, therefore the side effect never raises.

You are otherwise using mocker and patch correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.