How to pass environment variables to pytest

后端 未结 8 710
小鲜肉
小鲜肉 2020-12-05 01:48

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 en

相关标签:
8条回答
  • 2020-12-05 02:18

    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

    0 讨论(0)
  • 2020-12-05 02:18

    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://docs.pytest.org/en/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')
    
      
    
    1. 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"]
    
    0 讨论(0)
提交回复
热议问题