如何将环境变量传递给pytest

时间:2016-03-21 20:33:23

标签: pytest

在我开始在python项目中执行测试之前,我读了一些环境变量并设置了一些读取这些值的变量。我的测试将根据读取的这些值在所需的环境中运行。

例如:让我们说环境变量被称为" ENV_NAME"和" ENV_NUMBER"

现在,我想使用py.test

运行测试

如果我对这些环境变量进行硬编码,例如:ENV_NAME =' staging',ENV_NUMBER =' 5'在我的代码中,然后通过在项目目录的根目录执行py.test命令来运行测试,所有测试都成功运行。

但是,我不想对这些值进行硬编码。有没有办法,我可以将这些环境变量作为py.test的命令行参数发送?

我更多地考虑

  

py.test -ENV_NAME =' staging' -ENV_NUMBER =' 5&#39 ;.但是,这不起作用。

请帮忙!谢谢!

10 个答案:

答案 0 :(得分:37)

另一种方法是使用pytest-env插件。它可以这样配置:

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

D:前缀允许设置默认值,而不是覆盖传递给py.test的现有变量。

注意:如果您有时只需要运行专门的环境设置,则可以使用自定义配置显式运行pytest:

pytest -c custom_pytest.ini

答案 1 :(得分:11)

我终于找到了我正在寻找的答案。

我们可以在使用py.test

运行测试之前设置这样的环境变量

ENV_NAME ='分段' ENV_NUMBER =' 5' py.test

答案 2 :(得分:10)

有几种方法可以实现这个目标

1)如果您不想使用环境变量,可以使用pytest addoptions作为https://pytest.org/latest/example/simple.html

2)您可以编写这样的包装脚本来调用环境变量

   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) 
test_file.py中的

       你可以用

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

3)如果您只想传递日期未设置环境变量

,则为备用方法

在命令行上,您可以将其用作

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

您可以在测试文件中使用

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"]

答案 3 :(得分:3)

遵循@tutuDajuju使用pytest-env提供的想法-一种替代方法是利用pytest_load_initial_conftests编写自定义插件。尤其有用,尤其是当您不想或无法安装外部依赖项时。

这是一个简单的例子:

项目结构

.
├── __init__.py
├── pytest.ini
├── script.py
└── tests
    ├── __init__.py
    ├── plugins
    │   ├── __init__.py
    │   └── env_vars.py
    └── test_script.py

script.py

import os

FOOBAR = os.environ.get("FOOBAR")


def foobar():
    return FOOBAR

test_script.py

from script import foobar


def test_foobar():
    assert foobar() == "foobar"

pytest.ini

[pytest]
addopts = -p tests.plugins.env_vars

env_vars.py

import os

import pytest


@pytest.hookimpl(tryfirst=True)
def pytest_load_initial_conftests(args, early_config, parser):
    os.environ["FOOBAR"] = "foobar"

示例运行:

$ python -m pytest tests -v
========= test session starts =========
platform darwin -- Python 3.8.1, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 -- 
rootdir: /Users/user/pytest_plugins, inifile: pytest.ini
collected 1 item

tests/test_script.py::test_foobar PASSED                                                                                               [100%]

========= 1 passed in 0.01s =========

答案 4 :(得分:2)

类似于 bad_coder 提到的,你可以这样做:

# test.py
def test_hello_world(monkeypatch):
    # Setup
    monkeypatch.setenv('HELLO', 'world')

    # Test
    result = hello_world()

    # Verify
    assert(result == 'world')

答案 5 :(得分:1)

1。 当我不在函数外部加载环境变量时,会使用猴子补丁。

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. 如果使用PyCharm,则可以设置环境变量,[运行]-> [编辑配置]-> [默认值]-> [py.tests]-> [环境变量]

enter image description here

答案 6 :(得分:1)

除了其他答案。有一个选项可以覆盖pytest_generate_tests中的conftest.py并在那里设置ENV变量。

例如,将以下内容添加到conftest.py中:

import os

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

此代码将允许您在测试应用程序中获取TEST_NAME ENV变量。您也可以制作固定装置:

import os
import pytest

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

此外,此ENV变量将在您的应用程序中可用。

答案 7 :(得分:1)

在子外壳程序(包含括号)内运行export不会弄乱本地环境。使用.env文件中的参数提供导出。

(export $(xargs < .env); pytest -svvvx api)

答案 8 :(得分:0)

我需要创建一个pytest.ini文件,并且将环境变量传递给pytest命令。例如:

在pytest.ini文件中,我设置了一个空值,因为它会被传递给命令行命令的任何内容所覆盖:

[pytest]
MY_ENV_VAR=

命令行,设置了实际值:

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

我不知道为什么会这样工作。我只是发现它是经过反复试验的结果,因为其他答案并没有帮助我。

答案 9 :(得分:-4)

就像@MiaeKim 回答的最后一部分一样,如果使用 PyCharm,请在 New Configuration 中添加 PyCharm。传入 Environment Variables 的快速而简单的方法。

enter image description here