Search code examples
environment-variablespytest

How to pass environment variables to pytest


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.

E.g., Let's say the environment variables are called ENV_NAME and ENV_NUMBER. I would like to run the tests using pytest.

If I hard code these environment variables (e.g.,ENV_NAME = 'staging', ENV_NUMBER = '5') in my code and then run the tests by executing the pytest 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 set these environment variables as command line arguments for pytest?

I was thinking more in the lines of

pytest -ENV_NAME='staging' -ENV_NUMBER='5'.

But this is not working.


Solution

  • 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