【问题标题】:How to add env variable to pytest如何将环境变量添加到pytest
【发布时间】:2020-10-07 12:29:49
【问题描述】:

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

 somefile.env 
 KEY = "12345"

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

以上是 .env 和配置文件中给出的值。我可以在 python 脚本中访问 headers 值,但我无法在 pytest 中访问这个 header 值。例如,这是我在 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

当我在 pytest 中调用标头时,我将键值设为 None

【问题讨论】:

  • 您能否更新您的问题并添加您尝试过的代码?我的意思是你可以通过 Python 中的os 模块访问环境变量:os.environ.get("CUSTOM_ENV_VARIABLE") 那似乎是什么问题?
  • 更新问题
  • 我认为您可以将它们添加到pytest.ini 文件中。
  • 试过但没有运气。在 pytest.ini [pytest] env = HOME=~/tmp RUN_ENV=1234 中输入以下代码,因为1234 是我的关键。我不确定我是否以正确的方式这样做
  • 这能回答你的问题吗? How to pass environment variables to pytest

标签: python-3.x pycharm environment-variables pytest


【解决方案1】:

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

# contents of pytest.ini
[pytest]
env =
    D:RUN_ENV=1234

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

pip install pytest-env

此时RUN_ENV应该正确传递了

另见How to pass environment variables to pytest

【讨论】:

  • 您好,我已经尝试了上述解决方案,但无法传递/读取环境变量。我使用 Pycharm 作为 IDE 和 Python 3.9 版本。这是我尝试过的 #pytest.ini [pytest] env = D:RUN_ENV=1234 #testfile.py import os print(os.environ.get('RUN_ENV')) 当我运行 testfile.py 时,我得到了无
猜你喜欢
  • 1970-01-01
  • 2016-07-08
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
  • 2012-11-17
  • 1970-01-01
  • 2019-12-17
相关资源
最近更新 更多