Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve unittest ImportErrors

When I run:

python -m unittest discover unit_tests

or

python setup.py test

I receive lots of ImportErrors for the blowdrycss project.

Sample:

test_BreakpointParser (unittest.loader._FailedTest) ... ERROR
test_classExtractor (unittest.loader._FailedTest) ... ERROR
test_classPropertyParser (unittest.loader._FailedTest) ... ERROR
test_colorParser (unittest.loader._FailedTest) ... ERROR
test_CSSBuilder (unittest.loader._FailedTest) ... ERROR
test_CSSFile (unittest.loader._FailedTest) ... ERROR
test_CSSPropertyValueParser (unittest.loader._FailedTest) ... ERROR
...
ImportError: No module named 'settings'
ImportError: No module named 'blowdrycss_settings'
ImportError: No module named 'blowdrycss.blowdrycss_settings'
ImportError: No module named 'utilities'
ImportError: No module named 'breakpointparser'

Project structure:

blowdrycss/
    blowdrycss/
        settings/
            __init__.py
            blowdrycss_settings.py
        unit_tests/
            __init__.py
            test_BreakpointParser.py
            test_*.py
            ...
        __init__.py
        blowdrycss.py
        breakpointparser.py
        utilities.py
        ...    

What is strange is that when I run these tests from PyCharm everything passes, but when I run from the command line it breaks.

Maybe it is a simple configuration issue, but I'm not sure what I'm doing wrong.

How do I resolve these ImportErrors?

like image 514
nu everest Avatar asked Feb 08 '23 20:02

nu everest


1 Answers

There were multiple issues.

The primary issue was that blowdrycss.py was the same name as the package. This caused the python importer to be confused.

Changing the name of blowdrycss.py to blowdry.py helped.

The other half of the problem was the the current working directory was not being added to the PYTHONPATH. I fixed this by adding the following lines to __init__.py:

cwd = os.getcwd()
sys.path.insert(0, cwd)
like image 58
nu everest Avatar answered Feb 16 '23 04:02

nu everest