By Readonly

2008-09-14 05:41:11 8 Comments

If you're writing a library, or an app, where do the unit test files go?

It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.

Is there a best practice here?


@André 2008-09-24 17:44:16

We use


In each test file we insert ../src/ in sys.path. It's not the nicest solution but works. I think it would be great if someone came up w/ something like maven in java that gives you standard conventions that just work, no matter what project you work on.

@Steely Wing 2014-04-30 10:58:51

Only 1 test file

If there has only 1 test files, putting it in a top-level directory is recommended:


Run the test in CLI


Many test files

If has many test files, put it in a tests folder:


import unittest
from lib import module

class TestModule(unittest.TestCase):
    def test_module(self):

if __name__ == '__main__':

Run the test in CLI

# In top-level /module/ folder
python -m tests.test_module
python -m tests.test_module_function

Use unittest discovery

unittest discovery will find all test in package folder.

Create a in tests/ folder


Run the test in CLI

# In top-level /module/ folder

# -s, --start-directory (default current directory)
# -p, --pattern (default test*.py)

python -m unittest discover


Unit test framework

@Paul Hildebrandt 2009-05-02 17:08:05

We had the very same question when writing Pythoscope (, which generates unit tests for Python programs. We polled people on the testing in python list before we chose a directory, there were many different opinions. In the end we chose to put a "tests" directory in the same directory as the source code. In that directory we generate a test file for each module in the parent directory.

@Will 2012-04-01 20:44:21

Awesome! Just ran Pythoscope (great logo), on some legacy code and it was amazing. Instant best practices and you can get other developers to fill in the now failing test stubs. Now to hook it up into bamboo? :)

@cjs 2018-12-12 10:10:06

I put my tests in the same directory as the code under test (CUT); for the tests will be in or similar. (I tweak the test discovery process to find these.)

This puts the tests right beside the code in a directory listing, making it obvious that tests are there, and makes opening the tests as easy as it can possibly be when they're in a separate file. (For command line editors, vim foo* and when using a graphical filesystem browser, just click on the CUT file and then the immediately adjacent test file.)

As others have pointed out, this also makes it easier to refactor and to extract the code for use elsewhere should that ever be necessary.

I really dislike the idea of putting tests in a completely different directory tree; why make it harder than necessary for developers to open up the tests when they're opening the file with the CUT? It's not like the vast majority of developers are so keen on writing or tweaking tests that they'll ignore any barrier to doing that, instead of using the barrier as an excuse. (Quite the opposite, in my experience; even when you make it as easy as possible I know many developers who can't be bothered to write tests.)

@Janusz Skonieczny 2016-09-28 07:31:38

Every once in a while I find myself checking out the topic of test placement, and every time the majority recommends a separate folder structure beside the library code, but I find that every time the arguments are the same and are not that convincing. I end up putting my test modules somewhere beside the core modules.

The main reason for doing this is: refactoring.

When I move things around I do want test modules to move with the code; it's easy to lose tests if they are in a separate tree. Let's be honest, sooner or later you end up with a totally different folder structure, like django, flask and many others. Which is fine if you don't care.

The main question you should ask yourself is this:

Am I writing:

  • a) reusable library or
  • b) building a project than bundles together some semi-separated modules?

If a:

A separate folder and the extra effort to maintain its structure may be better suited. No one will complain about your tests getting deployed to production.

But it's also just as easy to exclude tests from being distributed when they are mixed with the core folders; put this in the

find_packages("src", exclude=["*.tests", "*.tests.*", "tests.*", "tests"]) 

If b:

You may wish — as every one of us do — that you are writing reusable libraries, but most of the time their life is tied to the life of the project. Ability to easily maintain your project should be a priority.

Then if you did a good job and your module is a good fit for another project, it will probably get copied — not forked or made into a separate library — into this new project, and moving tests that lay beside it in the same folder structure is easy in comparison to fishing up tests in a mess that a separate test folder had become. (You may argue that it shouldn't be a mess in the first place but let's be realistic here).

So the choice is still yours, but I would argue that with mixed up tests you achieve all the same things as with a separate folder, but with less effort on keeping things tidy.

@anarcat 2017-09-15 13:09:32

what's the problem with deploying tests to production, actually? in my experience, it's very useful: allows users to actually run tests on their environment... when you get bug reports, you can ask the user to run the test suite to make sure everything is alright there and send hot patches for the test suite directly... besides, it's not because you put your tests in module.tests that it will end up in production, unless you did something wrong in your setup file...

@Janusz Skonieczny 2017-10-30 07:19:33

As I wrote in my answer I usually do not separate tests. But. Putting tests into distribution package may lead to executing stuff you normally would not want in production env (eg. some module level code). It of course depends on how tests are written, but to be on the safe side it you leave them off, no one will run something harmful by mistake. I'm not against including tests in distributions, but I understand that as a rule of thumb it is safer. And putting them in separate folder makes it super easy not-to include them in dist.

@Arash 2016-05-09 17:54:13

I recommend you check some main Python projects on GitHub and get some ideas.

When your code gets larger and you add more libraries it's better to create a test folder in the same directory you have and mirror your project directory structure for each test type (unittest, integration, ...)

For example if you have a directory structure like:



After adding test folder you will have a directory structure like:




Many properly written Python packages uses the same structure. A very good example is the Boto package. Check

@brodul 2017-12-14 09:59:03

It is recommended to use "tests" instead of "test", because "test" is a Python build in module.

@alpha_989 2018-01-28 19:52:57

Not always.. for example matplotlib has it under matplotlib/lib/matplotlib/tests (…) , sklearn has it under scikitelearn/sklearn/tests (‌​sts)

@user6868 2008-09-15 12:52:00

For a file, the unit test should normally be called, following Pythonic naming conventions.

There are several commonly accepted places to put

  1. In the same directory as
  2. In ../tests/ (at the same level as the code directory).
  3. In tests/ (one level under the code directory).

I prefer #1 for its simplicity of finding the tests and importing them. Whatever build system you're using can easily be configured to run files starting with test_. Actually, the default unittest pattern used for test discovery is test*.py.

@dfarrell07 2013-08-13 21:24:53

The load_tests protocol searches for files named test*.py by default. Also, this top Google result and this unittest documentation both use the format.

@juniper- 2013-08-26 17:10:56

Using can save a keystroke or two when using tab-completion since you don't have a bunch of files starting with 'test_'.

@Medeiros 2013-10-11 04:21:46

@juniper, following your thoughts module_test would appear in auto completion when you are coding. That can be confusing or annoying.

@Kevin J. Rice 2015-05-04 14:10:36

When deploying code, we don't want to deploy the tests to our production locations. So, having them in one directory './tests/' is easy to yank when we do deployments. ALSO, some tests take sample data files, and having those in a test directory is vital lest we deploy test data.

@endolith 2017-06-18 15:00:15

@KevinJ.Rice Shouldn't you be testing that the code works on your production locations?

@Kevin J. Rice 2017-08-12 03:00:28

@endolith, Not testing code works (functional testing) at prod boxes, only running tests on dev and QA and maybe staging boxes if we have them. Prod boxes are locked down and have access to production databases, etc., and tests can accidentally access this critical infrastructure in bad ways. Best to leave tests off the prod boxes unless you're trying to do something very specific like monitor services, at which point we're talking monitoring not unit tests.

@Ken T 2017-08-24 10:04:31

Is it assumed that the path of the module was already added into Python so that you can import the module in your testing files?

@anarcat 2017-09-15 13:12:02

I find it quite useful to ship tests under the main module directory, as it allows me to actually ship code to production (if i want to!) which allows users to run the test suite directly before filing bugs...

@Cristian 2008-09-14 06:46:14

A common practice is to put the tests directory in the same parent directory as your module/package. So if your module was called your directory layout would look like:


Of course there is no one way of doing it. You could also make a tests subdirectory and import the module using absolute import.

Wherever you put your tests, I would recommend you use nose to run them. Nose searches through your directories for tests. This way, you can put tests wherever they make the most sense organizationally.

@Jonathan Hartley 2009-05-07 16:35:12

I'd like to do this but I can't make it work. To run the tests, I'm in the parent_dir, and type: "python tests\", and in "from import this, that, theother" That fails with: "ValueError: Attempted relative import in non-package" Both parent_dir and tests have an in them, so I'm not sure why they aren't packages. I suspect it's because the top-level script you run from the command line cannot be considered (part of) a package, even if it's in a dir with an So how do I run the tests? I'm working on Windows today, bless my cotton socks.

@Cristian 2009-05-16 09:27:23

The best way-- I've found-- to run unit tests is to install your library/program then run unit tests with nose. I would recommend virtualenv and virtualenvwrapper to make this a lot easier.

@cmcginty 2009-06-27 01:42:33

@Tartley - you need a file in your 'tests' directory for absolution imports to work. I have this method working with nose, so I'm not sure why you are having trouble.

@Jonathan Hartley 2009-07-22 08:23:14

Thanks Casey - but I do have an file in all relevant directories. I don't know what I do wrong, but I have this problem on all my Python projects and I can't understand why nobody else does. Oh deary.

@Jonathan Hartley 2009-07-22 08:25:23

One solution for my problem, with Python2.6 or newer, us to run the tests from the root of your project using: python -m project.package.tests.module_tests (instead of python project/package/tests/ This puts the test module's directory on the path, so the tests can then do a relative import to their parent directory to get the module-under-test.

@alpha_989 2018-01-28 19:59:34

nose and nose2 are in maintanance mode. From nose website: Nose has been in maintenance mode for the past several years and will likely cease without a new person/team to take over maintainership. New projects should consider using Nose2, py.test, or just plain unittest/unittest2.

@alpha_989 2018-01-28 20:00:04

from nose2 github ( Even though unittest2 plugins never arrived, nose2 is still being maintained! We have a small community interested in continuing to work on and use nose2 However, given the current climate, with much more interest accruing around pytest, nose2 is prioritizing bugfixes and maintenance ahead of new feature development.

@alpha_989 2018-01-28 20:00:35

So if you dont already use nose/nose2 it may be better to use py.test.

@Rahul Biswas 2014-03-28 04:22:38

From my experience in developing Testing frameworks in Python, I would suggest to put python unit tests in a separate directory. Maintain a symmetric directory structure. This would be helpful in packaging just the core libraries and not package the unit tests. Below is implemented through a schematic diagram.

                              <Main Package>
                               /          \
                              /            \
                            lib           tests
                            /                \
             [,,  [,,

In this way when you package these libraries using an rpm, you can just package the main library modules (only). This helps maintainability particularly in agile environment.

@Jasha 2018-06-01 11:41:53

I've realized that one potential advantage of this approach is that the tests can be developed (and maybe even version controlled) as an independent application of their own. Of course, to every advantage there is a disadvantage -- maintaining symmetry is basically doing "double entry accounting," and makes refactoring more of a chore.

@Jasha 2018-06-01 11:43:16

Soft follow-up question: why is the agile environment in particular well-suited to this approach? (i.e. what about the agile workflow makes a symmetric directory structure so beneficial?)

@Heikki Toivonen 2008-12-19 23:48:07

I prefer toplevel tests directory. This does mean imports become a little more difficult. For that I have two solutions:

  1. Use setuptools. Then you can pass test_suite='tests.runalltests.suite' into setup(), and can run the tests simply: python test
  2. Set PYTHONPATH when running the tests: PYTHONPATH=. python tests/

Here's how that stuff is supported by code in M2Crypto:

If you prefer to run tests with nosetests you might need do something a little different.

@Dale Reidy 2010-03-02 12:50:51

How I do it...

Folder structure:

    tests/ points to src/ as the location containing my projects modules, then i run: develop

Which adds my project into site-packages, pointing to my working copy. To run my tests i use: tests

Using whichever test runner I've configured.

@blokeley 2011-04-05 11:50:41

You seem to have over-ridden the term "module". Most Python programmers would probably think that the module is the file you called It would make more sense to call the top level directory "project".

@George V. Reilly 2008-09-15 03:09:29

In C#, I've generally separated the tests into a separate assembly.

In Python -- so far -- I've tended to either write doctests, where the test is in the docstring of a function, or put them in the if __name__ == "__main__" block at the bottom of the module.

@Thomas Andrews 2008-09-19 16:46:53

I also tend to put my unit tests in the file itself, as Jeremy Cantrell above notes, although I tend to not put the test function in the main body, but rather put everything in an

if __name__ == '__main__':
   do tests...

block. This ends up adding documentation to the file as 'example code' for how to use the python file you are testing.

I should add, I tend to write very tight modules/classes. If your modules require very large numbers of tests, you can put them in another, but even then, I'd still add:

if __name__ == '__main__':
   import tests.thisModule

This lets anybody reading your source code know where to look for the test code.

@endolith 2014-08-13 15:46:49

"as Jeremy Cantrell above notes" where?

@Keeely 2017-06-15 09:57:54

I like this way of working. The simplest of editors can be configured to run your file with a hot-key, so when you're viewing the code, you can run the tests in an instant. Unfortunately in languages other than Python this can look horrible, so if you're in a C++ or Java shop your colleagues may frown on this. It also doesn't work well with code coverage tools.

@tholo 2008-09-16 21:10:12

If the tests are simple, simply put them in the docstring -- most of the test frameworks for Python will be able to use that:

>>> import module
>>> module.method('test')

For other more involved tests, I'd put them either in ../tests/ or in tests/

@Sebastian Rittau 2008-09-15 14:56:35

When writing a package called "foo", I will put unit tests into a separate package "foo_test". Modules and subpackages will then have the same name as the SUT package module. E.g. tests for a module foo.x.y are found in foo_test.x.y. The files of each testing package then contain an AllTests suite that includes all test suites of the package. setuptools provides a convenient way to specify the main testing package, so that after "python develop" you can just use "python test" or "python test -s foo_test.x.SomeTestSuite" to the just a specific suite.

@John Millikin 2008-09-14 18:18:58

I use a tests/ directory, and then import the main application modules using relative imports. So in MyApp/tests/, there might be:

from .. import foo

to import the module.

@cprn 2016-07-25 19:12:31

"ValueError: Attempted relative import in non-package"

@quamrana 2008-09-14 18:02:12

I've recently started to program in Python, so I've not really had chance to find out best practice yet. But, I've written a module that goes and finds all the tests and runs them.

So, I have:


I'll have to see how it goes as I progress to larger projects.

@Stuart Axon 2015-10-05 19:15:29

Hi, the camelCase is a little weird in the python world.

@dwestbrook 2008-09-14 06:46:03

I don't believe there is an established "best practice".

I put my tests in another directory outside of the app code. I then add the main app directory to sys.path (allowing you to import the modules from anywhere) in my test runner script (which does some other stuff as well) before running all the tests. This way I never have to remove the tests directory from the main code when I release it, saving me time and effort, if an ever so tiny amount.

@Piotr Dobrogost 2011-11-29 19:21:53

I then add the main app directory to sys.path The problem is if your tests contain some helper modules (like test web server) and you need to import such helper modules from within your proper tests.

@Matt M. 2018-07-09 04:25:40

This is what it looks like for me: os.sys.path.append(os.dirname('..'))

Related Questions

Sponsored Content

54 Answered Questions

42 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 3332826 View
  • 2936 Score
  • 42 Answer
  • Tags:   python datetime time

30 Answered Questions

[SOLVED] Finding the index of an item in a list

  • 2008-10-07 01:39:38
  • Eugene M
  • 3938078 View
  • 3234 Score
  • 30 Answer
  • Tags:   python list indexing

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

21 Answered Questions

[SOLVED] Running unittest with typical test directory structure

  • 2009-12-13 16:10:23
  • Major Major
  • 215480 View
  • 706 Score
  • 21 Answer
  • Tags:   python unit-testing

62 Answered Questions

[SOLVED] Calling an external command from Python

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

20 Answered Questions

[SOLVED] What are metaclasses in Python?

15 Answered Questions

[SOLVED] How do I run all Python unit tests in a directory?

Sponsored Content