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

2024-05-16 18:52:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎无法获得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得到rootdir,但这不是我需要的)

(我需要能够设置这些路径,以便测试file1.txtfile2.txt上的一些执行操作。我也需要这个工作,无论我尝试测试的各种东西有多深的嵌套。)我不太感兴趣设置特定的临时测试目录,并把它们取下来,等等。我只需要正在测试的文件的路径。在

我尝试过类似的方法:

^{pr2}$

但这只会产生:UNEXPECTED EXCEPTION: NameError("name '__file__' is not defined",)

我甚至可以访问一些内部函数/对象py.测试在

(我应该补充一下,我需要在Python2.7和Python3.x中使用它)


Tags: 文件pytest路径目录txtexecutepytest
1条回答
网友
1楼 · 发布于 2024-05-16 18:52:23

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

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

如果要查看打印的文本,则必须对pytest运行使用-s标志。在

来自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.

相关问题 更多 >