Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 modules from source needed to run my tests?

like image 550
Karan Avatar asked Jan 21 '11 16:01

Karan


People also ask

Why is Python running my module when I import it?

This happens because when Python imports a module, it runs all the code in that module. After running the module it takes whatever variables were defined in that module, and it puts them on the module object, which in our case is salutations .

Can we import * from module in Python?

A module can be imported by another program to make use of its functionality. This is how you can use the Python standard library as well. Simply put, a module is a file consisting of Python code. It can define functions, classes, and variables, and can also include runnable code.


3 Answers

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.

like image 123
Thomas Avatar answered Sep 23 '22 02:09

Thomas


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/

like image 39
Anderson Vieira Avatar answered Sep 24 '22 02:09

Anderson Vieira


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

like image 18
Frank Bryce Avatar answered Sep 24 '22 02:09

Frank Bryce