Karan
Karan

Reputation: 15114

How to run python test files

I am developing python in eclipse. As a result, python src files and test files are in different directories.

Question is: How do we run on command line specific test files in the test folder? These obviously depend on files in the src folder.

Cheers

Edit: if I run

python test/myTestFile.py

I get dependency errors, eg. ImportError: No module named SrcFile1

Upvotes: 1

Views: 3355

Answers (2)

samplebias
samplebias

Reputation: 37919

You need to make sure your PYTHONPATH is set correctly so the command-line interpreter can find your packages, or run your test cases from within Eclipse Pydev. Update: Another option: running your tests using nose might make things a bit easier, since it can auto-discover packages and test cases.

If your project is laid out like so:

/home/user/dev/
    src/pkg1/
         mod1.py

    test/
         mod1_test.py

Use: PYTHONPATH=$HOME/dev/src python test/mod1_test.py. I'd also recommend using distribute and virtualenv to set up your project for development.

Updated in response to question in comments:

This shows how the PYTHONPATH environment variable extends Python's package sear ch path:

% PYTHONPATH=foo:bar python -c 'import sys; print sys.path[:3]'
['', '/home/user/foo', '/home/user/bar']

# exporting the variable makes it sticky for your current session. you can 
# add this to your shell's resource file (e.g. ~/.profile) or source
# it from a textfile to save typing:

% export PYTHONPATH=bar:baz
% python -c 'import sys; print sys.path[:3]'
['', '/home/user/foo', '/home/user/bar']
% python -c 'import sys; print sys.path[:3]'
['', '/home/user/foo', '/home/user/bar']

The above should get you going in the short term. Using distribute and virtualenv have a higher one-time setup cost but you get longer-term benefits from using them. When you get a chance, read some of the many tutorials on SO for setting these up to see if they're a good fit for your project.

Upvotes: 5

Bittrance
Bittrance

Reputation: 2260

There are 2 principal solutions to this. Either, you need to use e.g. PYTHONPATH environment variable to tell the tests where the source is, or you need to make tests and production code part of the same module tree by inserting the relevant __init__.py files. In the latter approach, the tree may look something like this:

|-- qbit
|   |-- __init__.py
|   |-- master.py
|   |-- policy.py
|   |-- pool.py
|   |-- synchronize.py
|   `-- worker.py
`-- test
    |-- __init__.py
    |-- support.py
    |-- test_policy.py
    |-- test_synchronize.py
    `-- test_worker.py

__init__.py can be an empty file.

Upvotes: 1

Related Questions