skip to Main Content

I’ve been trying to make VSCodes test discovery (using pytest) find my test, but without success. The discovery fails, because pytest cannot resolve where my modules are coming from, hence I need to add the correct folder to the PYTHONPATH. Everything works nicely, when I use the terminal. I just export the correct PYTHONPATH and when I run "pytest" it works.
However, I’m unable to make VSCode use that PYTHONPATH, when running the integrated test discovery.
Using a ".env" file in the root folder, with the PYTHONPATH defined DOES NOT WORK (as suggested everywhere on the internet). Also what is suggested here: How to integrate VSCode with pytest ('test discovery fails')? also does not work.

My current workaround is to export the PYTHONPATH in the shell, start VSCode from that same shell session and then it works. I would like for it to just work with the ".env" file for example.

Is there a way?

EDIT:

Just figured out that adding a "pytest.ini" to the root folder, where I use the config "pythonpath" https://docs.pytest.org/en/latest/reference/reference.html#confval-pythonpath works as well.
Still I find it highly frustrating that VSCode does not seem to use the ".env" file.

2

Answers


  1. Yes, there is a way to set the PYTHONPATH for pytest in VSCode using the .env file. The issue might be with how you are setting the PYTHONPATH in the .env file.

    Make sure that the .env file is in the root folder of your project, and it should look something like this:

    PYTHONPATH=/pathtoproject
    

    After creating or modifying the .env file, you need to restart VSCode.

    But sometimes it doesn’t work. If this is still not working, you can try specifying the PYTHONPATH in the VSCode settings.

    • Go to File > Preferences > Settings, search for "pythonpath"
    • Then add the path to your project’s root folder under the "Python > Analysis: Extra Paths" setting.
    Login or Signup to reply.
  2. You have two ways to add PYTHONPATH,

    • In the .env file

      PYTHONPATH = "E:\Desktop\project"
      
    • In launch.json:

                  "env": {
                      "PYTHONPATH": "E:\Desktop\project"
                  }
      

    Note that this all needs to be in debug mode to work.

    You can also add arguments to pytest with the following setting:

        "python.testing.pytestArgs": [
            "."
        ],
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search