How to mock a module import in Python

When writing tests, it is quite common to mock a module. One way to do this is by injecting a custom module in sys.modules : import sys from testcontainers.localstack import LocalStackContainer def mock_module(localstack_container: LocalStackContainer): mocked_module = type(sys)('clients') mocked_module.s3 = localstack_container.get_client('s3') sys.modules['clients'] = mocked_module Note In this…