Before i start executing the tests in my python project, i read some environment variables and set some variables with these values read. My tests will run on the desired environment based on these values read.
for eg: Let's say the environment variables are called "ENV_NAME" and "ENV_NUMBER"
Now, I would like to run the tests using py.test
If i hard code these environment variables, for eg: ENV_NAME = 'staging', ENV_NUMBER = '5' in my code and then run the tests by executing the py.test command at the root of the project directory, all the tests run successfully.
But, i don't want to hardcode these values. Is there a way, i can send these environment variables as command line arguments for py.test?
I was thinking more in the lines of
py.test -ENV_NAME='staging' -ENV_NUMBER='5'. But, this is not working.
Please help! Thank you!
I finally found the answer i was looking for.
we can set the environment variables like this before running tests using py.test
ENV_NAME='staging' ENV_NUMBER='5' py.test
There are few ways you can achieve this
1) If you dont want to use the environment variable , you can use pytest addoptions as https://pytest.org/latest/example/simple.html
2) You can write a wrapper script like this to call enviornment variables
in test_file.py you can use
3) Alternate method if you just want to pass the date not set enviornment variable
on command line you can use it as
You can use in your test file
In addition to other answers. There is an option to overwrite
pytest_generate_tests
inconftest.py
and set ENV variables there.For example, add following into
conftest.py
:This code will allow you to grab
TEST_NAME
ENV variable in your tests application. Also you could make a fixture:Also, this ENV variable will be available in your application.
Another alternative is to use the pytest-env plugin. It can be configured like so:
the
D:
prefix allows setting a default value, and not override existing variables passed topy.test
.Note: you can explicitly run pytest with a custom config, if you only sometimes need to run a specialized environment set up:
I needed to create a
pytest.ini
file and pass the environment variables to thepytest
command. E.g:In the pytest.ini file I set an empty value because it is overwritten by whatever you pass to the command line command:
Command line, with the actual value set:
I don't know why does it work like this. I just found out that it works as a result of mere trial and error, because the other answers didn't help me.
1. I use monkey patch when I don't load environment variable variable outside function.