在 pytest 中,如何根据 bash shell 表达式设置环境变量?

In pytest, how do I set an environment variable based on a bash shell expression?

我正在使用 Python 3.8 和 pytest。我有这个 pytest.ini 文件 ...

[pytest]
env_override_existing_values = 1
env_files =
    tests/.test_env

我的测试/.test_env 包含

TZ=`ls -la /etc/localtime | cut -d/ -f8-9`

然而,这在我的 pytest 中得到了逐字评估——即 TZ 等于“ls -la /etc/localtime | cut -d/ -f8-9”。当我 运行 “pytest tests/my_test.py” 时,有没有一种方法可以将 pytest 的环境变量配置为表达式的结果?仅供参考,做类似“TZ=ls -la /etc/localtime | cut -d/ -f8-9; pytest tests/my_test.py”

之类的事情不是一种选择

所以基本上pytest.ini可能包含:

[pytest]
TZ=

然后,您可以在 cmd 行中将其传递为:

$ TZ=`ls -la /etc/localtime | cut -d/ -f8-9` pytest -c pytest.ini -s tests/**

(pytest 文档)[https://pypi.org/project/pytest-envfiles/] 建议 pytest“env_files”指令使用的文件需要包含文字 key=val 行。是的,关于 pytest env 文件的格式,文档并不清楚。因此,您不正确地期望这些文件是使用您的 $SHELL 程序“评估”的,更不用说以任何其他方式了,这并不奇怪。

我不明白你为什么不能do something like "TZ=ls -la /etc/localtime | cut -d/ -f8-9; pytest tests/my_test.py"。此外,您显然是在尝试将 $TZ 显式设置为平台的默认时区。为什么?那应该是默认的。这表明存在更深层次的问题。也就是说,你问的是 xyproblem.info 个问题。

所以,如果我理解正确的话,你想在 pytest 进程中设置一个 envvar,而不使用任何外部参数。您可以像这样在 conftest.py 中使用会话范围的 pytest fixture:

$ cat conftest.py
import os
import subprocess

import pytest


@pytest.fixture(scope="session", autouse=True)
def setenv():
    process = subprocess.run("ls -la /etc/localtime | cut -d/ -f8-9", shell=True, capture_output=True)
    os.environ["TZ"] = process.stdout.decode("utf8")

$ cat test_foo.py
import os


def test_my_test():
    print(os.environ["TZ"])
$ pytest -s
================================================================================= test session starts ==================================================================================
platform linux -- Python 3.8.2, pytest-6.0.1, py-1.9.0, pluggy-0.13.1
rootdir: /tmp/testy
collected 1 item                                                                                                                                                                       

test_foo.py New York

.

================================================================================== 1 passed in 0.01s ===================================================================================
$ echo $TZ

$