pythonunit-testingcode-coveragepython-coverage

run unit tests and coverage in certain python structure


I have some funny noob problem.

I try to run unit tests from commandline:

H:\PRO\pyEstimator>python src\test\python\test_power_estimator.py
Traceback (most recent call last):
  File "src\test\python\test_power_estimator.py", line 2, in <module>
    import src.main.python.power_estimator as power
ImportError: No module named src.main.python.power_estimator

this same happens when I try to run it in desired folder:

H:\PRO\pyEstimator\src\test\python>python test_power_estimator.py

My folder structure looks like this.

├───src
│   │   __init__.py
│   │   __init__.pyc
│   │
│   ├───main
│   │   │   __init__.py
│   │   │   __init__.pyc
│   │   │
│   │   └───python
│   │       │   __init__.py
│   │       │   power_estimator.py
│   │       │   __init__.pyc
│   │       │   power_estimator.pyc
│   │       │
│   │       └───GUI
│   │               __init__.py
│   │
│   └───test
│       │   __init__.py
│       │
│       └───python
│               test_power_estimator.py
│               __init__.py
│               covrunner.bat
│               .coverage
│
└───doc

Maybe i don't see something obvious. I also try to run coverage. Is this approach good (file structure) ?


Solution

  • The immediate issue you are facing is a misunderstanding of what is "local code" in Python (I am not sure if there is an official terminology, so I am making this one up) and how to import it.

    When you run python src\test\python\test_power_estimator.py, the first element in sys.path is set to the directory containing the test_power_estimator.py script, not the current directory. So the statement "import src.main.python.power_estimator as power" looks for the package src in the directory src/test/python, and that fails.

    One way to work around the issue is to set the PYTHONPATH environment variable to "H:\PRO\pyEstimator"

    But the recommended way to run tests is to use a test runner script. I recommended using nosetest.

    In addition, nosetest has support for collecting coverage data while running your tests.

    Besides, it sounds like a bad idea to have a python package named "src". You should rename your package to be your project. Maybe "estimator" or "pyestimator" (lowercase, please).