icecream does not work with pytest (Failed to access the underlying source code for analysis)
This bug happens when using icecream + pytest and you have a multiline assertion on the test function. This will cause any ic() inside the test function containing the multiline assertion to fail, and also any ic() outside of any function will fail. See the example below.
How to reproduce the bug
Create a file test_icecream.py and paste this code:
from icecream import ic
print("\n\nFirst bug")
ic()
def test_icecream_fine():
print("No bug")
ic()
assert 1 + 1 == 2 if 1 == 1 else 2 + 2 == 4 or 3 + 3 == 6 or 4 + 4 == 8
def test_icecream_bug():
print("Second bug")
ic()
assert (
1 + 1 == 2 if 1 == 1 else 2 + 2 == 4 or 3 + 3 == 6 or 4 + 4 == 8 or 5 + 5 == 10
)
print(
"Bug happens when this print is executed and does not happen when it is not executed"
)
Run
pytest test_icecream.py -s
Results
First bug
ic| Error: Failed to access the underlying source code for analysis. Was ic() invoked in a REPL (e.g. from the command line), a frozen application (e.g. packaged with PyInstaller), or did the underlying source code change during execution?
collected 2 items
test_icecream.py No bug
ic| test_icecream.py:9 in test_icecream_fine() at 05:36:01.133
.Second bug
ic| Error: Failed to access the underlying source code for analysis. Was ic() invoked in a REPL (e.g. from the command line), a frozen application (e.g. packaged with PyInstaller), or did the underlying source code change during execution?
Bug happens when this print is executed and does not happen when it is not executed
If you comment the last print statement on this example, the bug will not happen. Super strange. The cause of the error is the multiline assertion, if you remove it, then it works as expected.
Extra details
OS
macOS Monterey 12.6
Python version
3.10.6
IDE
Visual Studio Code 1.73.0
Installation method
poetry add icecream
executing (and thus icecream) has always had trouble with pytest's magic. Usually it's OK when used outside of assert statements, this is a bug I haven't seen before. It seems to be specific to Python 3.10 (i.e. 3.9 and 3.11 should both be fine) and is unlikely to get fixed.