Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get files within the tests in Python?

I have the following package structure:

.
├── my_app
│   ├── app.py
│   ├── cli.py
│   ├── db.py
│   └── __init__.py
├── setup.py
├── tests
│   ├── data
│   │   └── foobar.gz
│   ├── test_app.py
│   └── test_database.py
└── tox.ini

Within test_app.py, I do this:

import pkg_resources
path = '../tests/data/foobar.gz'
full_path = pkg_resources.resource_filename(__name__, path)

Now I've seen the message:

/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py:1145:
  DeprecationWarning: Use of .. or absolute path in a resource path
  is not allowed and will raise exceptions in a future release.
self, resource_name

What should I do instead?

(I could also change the structure of the package, but I would like to keep the test data within the tests - it is not necessary for running the application)

like image 631
Martin Thoma Avatar asked May 14 '19 05:05

Martin Thoma


1 Answers

To get the test resource when passing the test filename to pkg_resources you want to use the path from the file with the tests like:

import pkg_resources
path = 'data/foobar.gz'
full_path = pkg_resources.resource_filename(__name__, path)

With pytest, I also use this pattern in conftest.py:

@pytest.fixture('session')
def test_data_dir():
    return os.path.join(os.path.dirname(__file__), 'data')

I can the use os.path.join() to easily get to any test data.

like image 117
Stephen Rauch Avatar answered Sep 21 '22 01:09

Stephen Rauch