How can a python unit test work with data files specified in setup.py package_data

34 views Asked by At

I have json files which I would like to embed within my Python package.

I've read about using package_data in my setup.py and then using importlib.resources to access the data files at runtime (as documented here on the setuptools website.

What's confusing me is how to have this work when I'm running unit tests. A unit test won't have executed setup.py and so the json files won't be embedded for my code to read.

How do I write code which works when run both from a unit test and when running as an imported package?

A snippet of my setup.py is:

package_dir={"": "app"},
packages=find_packages(where="app"),
package_data={
    "mypackage": ["*.json"]
},

A module within mypackage is doing:

from importlib.resources import files
data_text = files("mypackage").joinpath("foo.json").read_text()

which produces the expected results when I'm consuming the package I've built (using setup.py), but when running from a unit test produces the error:

ModuleNotFoundError: No module named 'mypackage'

0

There are 0 answers