'Creating a unique mock for an import per unit test in python

We maintain a module that imports a third party library. This library is only available on a specific python installation on a production server. We need to write unit tests for our module, but also want these tests to run on a separate python install (e.g. in a CI pipeline).

We are considering mocking this library. In theory, we think that we can implement a combination of the solutions mentioned here and here. However, we have some reservations about this approach. Since a single mock instance is shared across all unit tests (per the sys['third_party_library'] = mock.MagicMock()), its behavior is likewise shared across all the tests. If we try to set side_effect on the mock in one test, another test could potentially use the wrong side_effect if it runs in parallel. Moreover, expectations can potentially break due to circumstances outside the bounds of an individual unit test that verifies this mock.

Is there a way to ensure that a mocked import is unique to each unit test?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source