Search code examples
pythontestinggithub-actions

How to tell unit tests where the package library is in GitHub Actions


I have built a python library and I have unit tests running inside GitHub Actions but unit tests are failing for this reason.

Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/hostedtoolcache/Python/3.11.7/x64/lib/python3.11/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
test/foo_test.py:11: in <module>
    from mylib import Foo
E   ModuleNotFoundError: No module named 'mylib'

The reason of the error is because of my directory structure, since mylib is inside the src directory.

my_project/
|-- src/
|   |-- mylib/
|       |-- __init__.py
|       |-- foo.py
|
|-- tests/
|   |-- test_mylib.py (imports mylib.foo.Foo) no src prefix
|
|-- setup.py

pytest test in pycharm works because I have told my IDE where the sources (src) and the package (mylib) is:

how can I execute tests without requiring prefix src for my test files.

setup.py

packages=find_packages(where='src'),
package_dir={'': 'src'},

Attempt

I created a file pytest.ini with the content but it did't work (Unit tests couldn't find my package under src directory)

[pytest]
srcpaths = src

Solution

  • Found the solution to the problem from this answer

    pytest.ini example:

    [pytest]
    pythonpath = src