2

Is there a way to tell pytest to mock out any __init__.pys, or otherwise skip them?

I have a python module with a global dependency that gets introduced via a Docker container. Here's an example:

/mymodule
  /__init__.py
  mymodule.py
  mymodule_test.py

mymodule/__init__.py looks like:

from .mymodule import mymodule

And mymodule/mymodule.py looks like:

import globalpackage

def mymodule():
  pass

Finally, we have a Dockerfile that looks like:

FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8
COPY /some/path/to/globalpackage /app/globalpackage
COPY mymodule /app

So that, at runtime, globalpackage is available as an import. I can't change this structure as it's used across our codebase.

The issue I'm running into is in trying to write a test for this module. It seems that pytest hits the module __init__.py before it hits any tests. This means I'm unable to mock or patch globalpackage (which doesn't exist when running pytest at the command line).

I can't for the life of me figure out a way of skipping over __init__.py in this scenario. Ideally I'd like to avoid modifying the src code, as that will lead to a massive refactor.

K S
  • 21
  • 1
  • [this](https://stackoverflow.com/questions/47202355/pytest-cannot-mock-init-of-my-class) should answer your question – Relic16 Mar 18 '21 at 23:58
  • 2
    Your link refers to the `__init__ ` constructor on a class, doesn’t it? I’m asking about `__init__.py` which defines a module. – K S Mar 19 '21 at 02:49
  • 1
    Does this answer your question? [Mocking a module import in pytest](https://stackoverflow.com/q/43162722/8601760) – aaron Oct 03 '21 at 13:43

0 Answers0