How to pass environment variables to pytest

2020-02-08 06:53发布

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!

标签: pytest
6条回答
Lonely孤独者°
2楼-- · 2020-02-08 07:07

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

查看更多
Emotional °昔
3楼-- · 2020-02-08 07:19

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"]
查看更多
爷、活的狠高调
4楼-- · 2020-02-08 07:23

In addition to other answers. There is an option to overwrite pytest_generate_tests in conftest.py and set ENV variables there.

For example, add following into conftest.py:

import os

def pytest_generate_tests(metafunc):
        os.environ['TEST_NAME'] = 'My super test name| Python version {}'.format(python_version)

This code will allow you to grab TEST_NAME ENV variable in your tests application. Also you could make a fixture:

import os
import pytest

@pytest.fixture
def the_name():
    return os.environ.get('TEST_NAME')

Also, this ENV variable will be available in your application.

查看更多
▲ chillily
5楼-- · 2020-02-08 07:27

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
查看更多
在下西门庆
6楼-- · 2020-02-08 07:28

I needed to create a pytest.ini file and pass the environment variables to the pytest 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:

[pytest]
MY_ENV_VAR=

Command line, with the actual value set:

$ MY_ENV_VAR=something pytest -c pytest.ini -s tests/**

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.

查看更多
等我变得足够好
7楼-- · 2020-02-08 07:34

1. I use monkey patch when I don't load environment variable variable outside function.

import os

# success.py
def hello_world():
    return os.environ["HELLO"]

# fail.py
global_ref = os.environ["HELLO"] # KeyError occurs this line because getting environment variable before monkeypatching

def hello_world():
    return global_ref

# test.py
def test_hello_world(monkeypatch):
    # Setup
    envs = {
        'HELLO': 'world'
    }
    monkeypatch.setattr(os, 'environ', envs)

    # Test
    result = hello_world()

    # Verify
    assert(result == 'world')
  1. If you use PyCharm you can set environment varaibles, [Run] -> [Edit Configuration] -> [Defaults] -> [py.tests] -> [Environment Variables]

enter image description here

查看更多
登录 后发表回答