Pytest Cannot Import Module While Python Can

pytest cannot import module while python can

Found the answer:

DO NOT put a __init__.py file in a folder containing TESTS if you plan on using pytest. I had one such file, deleting it solved the problem.

This was actually buried in the comments to the second answer of PATH issue with pytest 'ImportError: No module named YadaYadaYada' so I did not see it, hope it gets more visibility here.

How to solve ImportError with pytest

The self-named module testingonly and file name of testingonly.py may be causing some issues with the way the modules are imported.

Remove the __init__.py from the tests directory. Ref this answer .

Try renaming testingonly.py to mytest.py and then importing it into your project again.

In the cli.py, it should be:

from testingonly.mytest import Tester

And then for your test file test_testingonly.py:

from testingonly.mytest import Tester

You're test_testingonly.py file should look like this:

import pytest
from testingonly.mytest import Tester # Import the Tester Class


def test_tester(capsys):
# Create the Tester Class
te = Tester()
# Get the captured output
captured = capsys.readouterr()
# Assert that the capture output is tested
assert captured.out == "Hello\n"

Finally, Run your tests with:

python -m pytest tests/

Here is a fully working example based off of your code: https://github.com/cdesch/testingonly

pytest cannot import module while python can

Found the answer:

DO NOT put a __init__.py file in a folder containing TESTS if you plan on using pytest. I had one such file, deleting it solved the problem.

This was actually buried in the comments to the second answer of PATH issue with pytest 'ImportError: No module named YadaYadaYada' so I did not see it, hope it gets more visibility here.

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

Yes, the source folder is not in Python's path if you cd to the tests directory.

You have 2 choices:

  1. Add the path manually to the test files, something like this:

    import sys, os
    myPath = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, myPath + '/../')
  2. Run the tests with the env var PYTHONPATH=../.

ModuleNotFoundError with pytest

Solution: use the PYTHONPATH env. var

PYTHONPATH=. pytest

As mentioned by @J_H, you need to explicitly add the root directory of your project, since pytest only adds to sys.path directories where test files are (which is why @Mak2006's answer worked.)



Good practice: use a Makefile or some other automation tool

If you do not want to type that long command all the time, one option is to create a Makefile in your project's root dir with, e.g., the following:

.PHONY: test
test:
PYTHONPATH=. pytest

Which allows you to simply run:

make test

Another common alternative is to use some standard testing tool, such as tox.



Related Topics



Leave a reply



Submit