开发者

Python import src modules when running tests

My source files are located under src and my test files are located under tests. When I want to run a test file, say python myTest.py, I get an import error: "No module named ASourceModule.py".

How do I import all the modu开发者_JAVA百科les from source needed to run my tests?


You need to add that directory to the path:

import sys
sys.path.append('../src')

Maybe put this into a module if you are using it a lot.


If you don't want to add the source path to each test file or change your PYTHONPATH, you can use nose to run the tests.

Suppose your directory structure is like this:

project
    package
        __init__.py
        module.py
    tests
        __init__.py
        test_module.py

You should import the module normally in the test_module.py (e.g. from package import module). Then run the tests by running nosetests in the project folder. You can also run specific tests by doing nosetests tests/test_module.py.

The __init__.py in the tests directory is necessary if you want to run the tests from inside it.

You can install nose easily with easy_install or pip:

easy_install nose

or

pip install nose

nose extends unittest in a lot more ways, to learn more about it you can check their website: https://nose.readthedocs.org/en/latest/


On my system (Windows 10), I was required to do something like this:

import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../src")

Appending the relative directory directly to sys.path did not work


The best (most manageable) solution appears to be using a virtualenv and setuptools/distribute to install a development copy of your (src) package. That way your tests execute against a fully "installed" system.

In the pystest docs there is a section on "good practices" explaining this approach, see here.


For those using Pytest:

  • Make sure src is recognized as a package by putting an empty__init__.py inside.
  • Put an empty conftest.py in the project folder.
  • Make sure there is no __init__.py in the test directory.

Looks like this:

project
    conftest.py
    src
        __init__.py
        module.py
    test
        test_module.py

And make sure module.py contains the line:

from src import module

Source: Pytest docs

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜