Search code examples
pythonpython-3.xpycharmpython-unittest

unittest working in PyCharm but unable to run from command line


I'm trying to run a unit test in the command line to generate code coverage. I can run the command from PyCharm fine, but running it from command line doesn't work.

The test is in a testing folder like the following

a/b/c/testing/UnitTest.py

The files I import are imported in the format

from a.b.c.main.classes import MyClass

If I try and directly run the unit test from the folder, it tells me that it can't import module a.

I'm fairly certain that PyCharm is fixing this issue because I have the boxes "Add content roots to PYTHONPATH" and "Add source roots to PYTHONPATH" checked, but I can't figure out how to do something equivalent in the command line.

How can I either fix my imports so it doesn't require it to be run from the root level, or add the content and source roots to PYTHONPATH so I can run in the command line?


Solution

  • if you are on Windows,

    set PYTHONPATH=<Path to your Source folder >
    

    for linux,

    export PYTHONPATH=<Path to your Source folder >
    

    once you set that running below command from project folder should do the work

    python -m unittest discover