Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyTest - Apply mock to all tests

I would like to apply a mock/patch that will apply to all tests, how can I do this?

I had tried putting it in a fixture, and using the fixture everywhere, but, the reapplication of the mock/patch on each test was leading to inconsistent id(my_mock) values.

like image 421
J. Doe Avatar asked Jun 14 '18 22:06

J. Doe


1 Answers

You can make a fixture applied only once for all the test suite execution by scoping the fixture to 'session', and using it in all your tests:

import pytest
from unittest import mock

@pytest.fixture(scope='session', autouse=True)
def my_thing_mock():
    with mock.patch.object(TheThingYouWantToMock, 'some_attribute') as _fixture:
        yield _fixture
like image 62
Samuel Dion-Girardeau Avatar answered Oct 19 '22 09:10

Samuel Dion-Girardeau