How to pass environment variables to pytest

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

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!

回答1:

Another alternative is to use the pytest-env plugin. It can be configured like so:

[pytest] env =      HOME=~/tmp     D:RUN_ENV=test 

the D: prefix allows setting a default value, and not override existing variables passed to py.test.

Note: you can explicitly run pytest with a custom config, if you only sometimes need to run a specialized environment set up:

pytest -c custom_pytest.ini 


回答2:

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



回答3:

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

   import os    import py    env_name = os.environ["ENV_NAME"]    env_no = os.environ["ENV_NUMBER"]    pytest_args=(env_name,env_no)    pytest.main('-s' ,pytest_args,test_file.py)  

in test_file.py you can use

   env_n, env_n = pytest.config.getoption('pytest_args') 

3) Alternate method if you just want to pass the date not set enviornment variable

on command line you can use it as

   py.test --testdata ="ENV_NAME:staging,ENV_NUMBER:5" 

You can use in your test file

pytest_params = pytest.config.getoption('testdata') params = pytest_params.split(":") param_dict = dict(params[i:i+2] for i in range(0,len(params),2)) env_name = param_dict["ENV_Name"] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!