Rodrigo A
Rodrigo A

Reputation: 767

PyCharm pytest and environment variables not working

I', using Pycharm in Ubuntu using python 3.7 and 3.8, and I'm facing two problems:

  1. I'm using pytest, when I try to run it using run 'pytest for.. it doesn't show the test window and prints nothing, just "Process finished with exit code 0"

If I run the test with pytest filename.py it works just fine.

What could be missing? From File -> Settings -> Tools -> Python Integrated Tools -> Default test runner is already set to pytest

enter image description here

  1. I'm setting environment variables as shown bellow, but when trying to import it, it gets None
    import os

print(os.environ.get('SECRET_KEY'))

enter image description here

Upvotes: 1

Views: 5006

Answers (2)

genericname
genericname

Reputation: 177

You can install the plugin pytest-env

(this package was last updated 4 years ago, but still gets the job done - I am using python 3.8.5 and pipenv 2020.8.13 and it works well).

and then add to your pytet.ini file the environment variables you would like to set:

[pytest]
addopts = -s -v

env =
    SECRET_KEY = 12345

BTW, This plugin is intended to env vars and I thing using it with secret keys is a bit of abuse, but it will get the job done.

Upvotes: 0

Pavel Karateev
Pavel Karateev

Reputation: 8495

First problem - you have a "pure Python" run configuration for api_test.py so when you try to run this file PyCharm reuses the configuration instead of creating a new one.

enter image description here

To resolve this issue either use Run | Run ... menu and select "pytest" there - PyCharm will create a new "test" run configuration.

Or remove api_test configuration from Run | Edit Configurations ... so there will be nothing no re-use for PyCharm.

The corresponding ticket in PyCharm's bug tracker https://youtrack.jetbrains.com/issue/PY-30052 Please vote for it.


Second problem - this is the right direction but a wrong menu. You are setting the environment variable for PyCharm built-in Python Console while you need to set it for a specific run configuration.

Run | Edit Configurations ... -> select the configuration used to run a script which checks the environment variable and define it there.

enter image description here

Upvotes: 3

Related Questions