gpt4 book ai didi

python - pytest 获取当前测试文件的文件路径

转载 作者:行者123 更新时间:2023-12-04 16:44:52 25 4
gpt4 key购买 nike

我似乎无法在 pytest 中获取当前正在测试的文件的文件路径。

例如,考虑如下目录结构:

devops_scripts
├── devops_utilities
│   ├── backupMonthly.py
│   ├── generateAnsibleINI.py
│   └── tests
│   └── test_backup.txt
├── monitoring
│   ├── analyizeCatalinaLog.py
│   ├── fetchCatalinaLogs.py
│   └── getaccountcredit.py
├── pi_provisioning
│   ├── piImageMake.sh
│   ├── piImageRead.sh
│   └── piImageSquashSd.py
└── script_utilities
   ├── README.md
   ├── __init__.py
   ├── execute.py
   ├── path_handling.py
   ├── sql_handling.py
   └── tests
   ├── sourcedirfortests
   │   ├── file1.txt
   │   └── file2.txt
   ├── test_ansible.txt
   └── test_execute.txt

如果我运行 pytest从顶层它将下降到测试 test_execute.txt .当 test_execute.txt正在测试如何获取文件路径? (我可以通过 rootdir 获得 os.path.abspath('.') 但这不是我需要的)

(我需要能够设置这些路径,以便在 file1.txtfile2.txt 上测试一些执行内容。无论我尝试测试的各种事物嵌套多深,我也需要它来工作。)我不是对设置特定的临时测试目录并将它们删除等感兴趣。我只需要正在测试的文件的路径。

我试过这样的事情:
>>> print os.path.abspath(__file__)

但这只会产生: UNEXPECTED EXCEPTION: NameError("name '__file__' is not defined",)
我什至没有访问 py.test 中的一些内部函数/对象

(我应该补充一点,我需要它在 Python 2.7 和 Python 3.x 中工作)

最佳答案

Pytest 为当前运行的测试设置 PYTEST_CURRENT_TEST env var。它不仅具有当前文件信息,还具有当前收集的测试 ID 的信息(如测试名称、参数等)。

import os
def test_current():
print(os.getenv('PYTEST_CURRENT_TEST'))

您必须使用 -s如果您想查看打印的文本,请使用 pytest 运行的标志。

来自 Reference Doc :

During the test session pytest will set PYTEST_CURRENT_TEST to the current test nodeid and the current stage, which can be setup, call and teardown.

关于python - pytest 获取当前测试文件的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com