Skip to content
Advertisement

Pytest + mock: patch does not work without with clause

I’m testing complex logic that require joining of central fact table with 10-20 smaller dimensional tables. I want to mock that 10-20 smaller tables.

How to patch methods return values in a for loop? See code below.

tables.py:

JavaScript

test_logic.py

JavaScript

P.S. alternatively I can try to mock the BaseClass.load, but then I don’t know how to return the different data set for different table (class).

Advertisement

Answer

Under the assumption that do_join shall be called outside the loop, with all tables patched, you could write a fixture that uses contextlib.ExitStack to setup all mocks:

JavaScript

This means that all mocks are still active at yield time, and will only be removed after the test is finished.

If you have pytest-mock installed, you can use the mocker fixture instead:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement