"Nice, the test works without needing to create a file in our home directory! One day your test suite fails with an error like: What happened!? Coverage.py code runs during your tests, invoked by the Python interpreter. The mock in the test changed the builtin open, so any use of it anywhere during the test is affected. In some cases, coverage.py needs to read your source code to record the execution properly. When that happens, coverage.py unknowingly uses the mocked open, and bad things happen."
"When you use a mock, patch it where it's used, not where it's defined. In this case, the patch would be: With a mock like this, the coverage.py code would be unaffected. Keep in mind: it's not just coverage.py that could trip over this mock. There could be other libraries used by your code, or you might use open yourself in another part of your product. Mocking the definition means anything using the object will be affected. Your intent is to only mock in one place, so target that place."
Overly aggressive mocking of widely used objects like builtins.open can make a test pass locally but cause failures later when other code relies on the original behavior. Patching the definition of an object affects every use during the test run, including tools such as coverage.py that may open files while measuring execution. Unintended interactions can surface in other libraries or different parts of the product. Tests should mock at the usage site to restrict scope and preserve isolation. Defensive changes in tooling can help, but narrowly scoped mocking remains the recommended practice.
Read at Nedbatchelder
Unable to calculate read time
Collection
[
|
...
]