如何将环境变量添加到pytest

use*_*496 2 environment-variables pytest pycharm python-3.x

我正在尝试向 pytest 添加环境变量。我已经成功地为常规 python 脚本添加了 env 和配置,但我无法使用 pytest 的 env var。

 somefile.env 
 KEY = "12345"

 Config.py
 import os
 headers = {"Key": os.environ.get("KEY"), "content_Type": "application/json"}
Run Code Online (Sandbox Code Playgroud)

以上是 .env 和配置文件中给出的值。我可以在 python 脚本中访问标头值,但无法在 pytest 中访问此标头值。例如,这是我在 pytest 中的代码

 import os
 from config import headers

  print(headers) #---> as this works as expected and prints key value

  #Pytests starts
  def test_one():
  print(headers) # prints key as None
Run Code Online (Sandbox Code Playgroud)

当我在 pytest 中调用标头时,我得到的键值为 None

jan*_*dom 8

这里的解决方案如@user29496所述

# contents of pytest.ini
[pytest]
env =
    D:RUN_ENV=1234
Run Code Online (Sandbox Code Playgroud)

除非你安装 pytest-env,否则这将默默地失败/不起作用

pip install pytest-env
Run Code Online (Sandbox Code Playgroud)

至此,RUN_ENV应该可以正确通过了。另请参阅如何将环境变量传递给 pytest