VSCode pytest test discovery fails VSCode pytest test discovery fails python python

VSCode pytest test discovery fails


I spent ages trying to decipher this unhelpful error after creating a test that had import errors. Verify that your test suite can actually be executed before doing any deeper troubleshooting.

pytest --collect-only is your friend.


This is not a complete answer as I do not know why this is happening and may not relate to your problem, depending how you have your tests structured.

I resolved this issue by putting an __init__.py file in my tests folder

E.G.:

├───.vscode│       settings.json│├───app│       myapp.py│└───tests        test_myapp.py        __init__.py

this was working a few days ago without this but the python extension was recently updated. I am not sure if this is the intended behavior or a side effect of how discoveries are now being made

https://github.com/Microsoft/vscode-python/blob/master/CHANGELOG.md
Use Python code for discovery of tests when using pytest. (#4795)


I just thought I would add my answer here as this might well affect someone who uses a .env file for their project's environment settings since it is such a common configuration for 12 factor apps.

My example assumes that you're using pipenv for your virtual environment management and that you have a .env file at the project's root directory.

My vscode workspace settings json file looks like below. The crucial line for me here was "python.envFile": "${workspaceFolder}/.env",

{    "python.pythonPath": ".venv/bin/python",    "python.linting.enabled": true,    "python.linting.pylintEnabled": true,    "python.linting.pycodestyleEnabled": false,    "python.linting.flake8Enabled": false,    "python.linting.pylintPath": ".venv/bin/pylint",    "python.linting.pylintArgs": [        "--load-plugins=pylint_django",    ],    "python.formatting.provider": "black",    "python.formatting.blackArgs": [        "--line-length",        "100"    ],    "python.testing.unittestEnabled": false,    "python.testing.nosetestsEnabled": false,    "python.testing.pytestEnabled": true,    "python.testing.pytestPath": ".venv/bin/pytest",    "python.envFile": "${workspaceFolder}/.env",    "python.testing.pytestArgs": [        "--no-cov"    ],}

I hope this saves someone the time I spent figuring this out.