Reputation: 767
I', using Pycharm in Ubuntu using python 3.7 and 3.8, and I'm facing two problems:
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
import os
print(os.environ.get('SECRET_KEY'))
Upvotes: 1
Views: 5006
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
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.
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.
Upvotes: 3