Why your mock breaks later
6 days ago
- #mocking
- #testing
- #python
- Overly aggressive mocks can work initially but break later due to unintended side effects.
- Mocking should be done where the object is used, not where it's defined, to avoid affecting unrelated code.
- Example: Mocking `open()` globally can interfere with libraries like `coverage.py`, causing unexpected errors.
- Best practices include using `autospec=True`, making assertions about mock calls, and preferring dependency injection over mocks.
- A defensive fix in `coverage.py` saves the original `open` to avoid issues from global mocking.