Speeding up PyTest by removing big libraries

Posted by kesor@reddit | Python | View on Reddit | 24 comments

I've been working on a small project that uses "big" libraries, and it was extremely annoying to have pytest to take 15–20 seconds to run 6 test cases that were not even doing anything.

Armed with the excellent PyInstrument I went ahead to search for what was the reason.

Turns out that biggish libraries are taking a lot of time to load, maybe because of the importlib method used by my pytest, or whatever.

But I don't really need these libraries in the tests … so how about I remove them?

# tests/conftest.py
import sys
from unittest.mock import MagicMock

def pytest_sessionstart():
  sys.modules['networkx'] = MagicMock()
  sys.modules['transformers'] = MagicMock()

And yes, this worked wonders! Reduced the tests to less than 1 second from pytest command to results, usually less than half a second.

I would have loved to remove sqlalchemy as well, but unfortunately sqlmodel is coupled with it so much it is inseparable from the models based on SQLModel.

Would love to hear your reaction to this kind of heresy.