Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest get the file path of current test file

Tags:

python

pytest

I can't seem to get the file path of the current file being tested in pytest.

For instance consider something like the following directory structure:

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

If I run pytest from the top level it will descend to testing test_execute.txt. When test_execute.txt is under testing how do I get the file path to it? (I can get the rootdir through os.path.abspath('.') but that is not what I need)

(I need to be able to set these paths in order to test some execution things on file1.txt and file2.txt. I also need this to work no matter how deeply nested the various things I am trying to test.) I am not so interested in setting up specific temp testing directories and taking them down, etc. I just need the path of the file which is being tested.

I have tried things like:

>>> print os.path.abspath(__file__)

But that just yields: UNEXPECTED EXCEPTION: NameError("name '__file__' is not defined",)

I am not above even accessing some internal functions / objects in py.test

(I should add that I need this to work in Python 2.7 and Python 3.x)

like image 349
Jason Harris Avatar asked Dec 30 '25 17:12

Jason Harris


1 Answers

Contrary to what the accepted answer says, do not use PYTEST_CURRENT_TEST environment variable. The documentation clearly says "it shouldn’t be relied on", and in this case, it is not even what the OP asked for, which is, "file path of the current file being tested".

Given the following directory structure:

graph/
├── test/
│   └── __init__.py/
│       └── test_graph.py
├── __init__.py
└── functions.py

The value of PYTEST_CURRENT_TEST from a function test_bfs in the file test_graph.py is:

'graph/test/test_graph.py::test_bfs (call)'

Whereas, request.path has the value graph/test/test_graph.py. This is exactly what the OP asked for.

More about request: FixtureRequest here.

like image 129
Abhijit Sarkar Avatar answered Jan 02 '26 08:01

Abhijit Sarkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!