H_Python_SQA
H_Python_SQA

Reputation: 61

How to open a file by its path relative to the Python module, when that module is tested with py.test?

I have a module inside a package which figures out the path of the invoking python program:

pathname = os.path.dirname(os.path.realpath(__file__))

from where it will pick up a mydata.json to read some parameter values.

This works fine when executing the script using python xyz.py

But the same stuff, when done using py.test at the directory, the path just points to some binary: /home/user/venv/bin/data/data.json

Basically the calling script is assumed to be py.test itself, which is located in the venv/bin.

How to overcome this problem ? I want to fetch the path of the script which in turn is being processed by py.test itself (via the module).

Upvotes: 6

Views: 4494

Answers (3)

Dawngerpony
Dawngerpony

Reputation: 3573

I know this is an old question but I couldn't resist. Using pathlib to retrieve and parse the contents of mydata.json from the fixtures directory relative to the test module test_stuff, Path(__file__).parent should work just fine for you to get the base directory.

import json
from pathlib import Path

fixture_path = Path(__file__).parent / "fixtures" / "mydata.json"

with open(fixture_path) as f:
    my_data = json.load(f)

The directory structure looks like this:

tests
├── fixtures
│   └── mydata.json
└── test_stuff.py

Upvotes: 0

Dmitry Tokarev
Dmitry Tokarev

Reputation: 2089

If i understand the problem correctly you should be using

import json
import os

path_to_current_file = os.path.realpath(__file__)
current_directory = os.path.split(path_to_current_file)[0]
path_to_file = os.path.join(current_directory, "mydata.json")
with open(path_to_file) as mydata:
    my_json_data = json.load(mydata)

Upvotes: 7

Lana Nova
Lana Nova

Reputation: 360

Slightly different version from the one offered above:

path_to_current_file = os.path.realpath(__file__)
current_directory = os.path.dirname(path_to_current_file)
path_to_file = os.path.join(current_directory, "mydata.json")

Upvotes: 3

Related Questions