563

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?

Chen Levy
  • 15,438
  • 17
  • 74
  • 92
readonly
  • 343,444
  • 107
  • 203
  • 205

18 Answers18

251

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

There are several commonly accepted places to put test_module.py:

  1. In the same directory as module.py.
  2. In ../tests/test_module.py (at the same level as the code directory).
  3. In tests/test_module.py (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.

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
user6868
  • 8,550
  • 2
  • 17
  • 3
  • 12
    The [load_tests protocol](http://docs.python.org/2/library/unittest.html#load-tests-protocol) searches for files named test*.py by default. Also, [this top Google result](http://docs.python-guide.org/en/latest/writing/tests/) and [this unittest documentation](http://docs.python.org/2/library/unittest.html#command-line-interface) both use the test_module.py format. – dfarrell07 Aug 13 '13 at 21:24
  • 7
    Using foo_test.py can save a keystroke or two when using tab-completion since you don't have a bunch of files starting with 'test_'. – juniper- Aug 26 '13 at 17:10
  • 12
    @juniper, following your thoughts module_test would appear in auto completion when you are coding. That can be confusing or annoying. – Igor Medeiros Oct 11 '13 at 04:21
  • 21
    When deploying code, we don't want to deploy the tests to our production locations. So, having them in one directory './tests/test_blah.py' 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. – Kevin J. Rice May 04 '15 at 14:10
  • 3
    @KevinJ.Rice Shouldn't you be testing that the code works on your production locations? – endolith Jun 18 '17 at 15:00
  • 3
    @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. – Kevin J. Rice Aug 12 '17 at 03:00
  • 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? – Ken T Aug 24 '17 at 10:04
  • 2
    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... – anarcat Sep 15 '17 at 13:12
102

Only 1 test file

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

module/
    lib/
        __init__.py
        module.py
    test.py

Run the test in CLI

python test.py

Many test files

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

module/
    lib/
        __init__.py
        module.py
    tests/
        test_module.py
        test_module_function.py
# test_module.py

import unittest
from lib import module

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

if __name__ == '__main__':
    unittest.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 __init__.py in tests/ folder

module/
    lib/
        __init__.py
        module.py
    tests/
        __init__.py
        test_module.py
        test_module_function.py

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

Reference

Unit test framework

Steely Wing
  • 16,239
  • 8
  • 58
  • 54
  • 2
    I have the same structure that you have outlined under "Many Test Files" but when I try `from lib import module` I get an error: `ImportError: No module named 'lib'` – Shervin Rad Jan 06 '22 at 17:52
  • 2
    @ShervinRad You need run in the `module` folder, not `lib` or `tests` folder, python use the relative path to import. – Steely Wing Jan 07 '22 at 07:20
52

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

parent_dir/
  foo.py
  tests/

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.

Cristian
  • 42,563
  • 25
  • 88
  • 99
  • 17
    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\foo_test.py", and in foo_test.py: "from ..foo import this, that, theother" That fails with: "ValueError: Attempted relative import in non-package" Both parent_dir and tests have an __init__.py 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 __init__.py. So how do I run the tests? I'm working on Windows today, bless my cotton socks. – Jonathan Hartley May 07 '09 at 16:35
  • 4
    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. – Cristian May 16 '09 at 09:27
  • @Tartley - you need a __init__.py 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. – cmcginty Jun 27 '09 at 01:42
  • 4
    Thanks Casey - but I do have an __init__.py 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 Jul 22 '09 at 08:23
  • 9
    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/module_tests.py). 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. – Jonathan Hartley Jul 22 '09 at 08:25
  • `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 Jan 28 '18 at 19:59
  • from `nose2` github (https://github.com/nose-devs/nose2): _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 Jan 28 '18 at 20:00
  • So if you dont already use `nose`/`nose2` it may be better to use `py.test`. – alpha_989 Jan 28 '18 at 20:00
32

We had the very same question when writing Pythoscope (https://pypi.org/project/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.

CivFan
  • 13,560
  • 9
  • 41
  • 58
Paul Hildebrandt
  • 2,724
  • 28
  • 26
  • 2
    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? :) – Will Apr 01 '12 at 20:44
26

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
   tests.thisModule.runtests

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

Thomas Andrews
  • 1,577
  • 1
  • 13
  • 31
  • 1
    "as Jeremy Cantrell above notes" where? – endolith Aug 13 '14 at 15:46
  • 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. – Keeely Jun 15 '17 at 09:57
26

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 setup.py:

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.

Serp C
  • 864
  • 1
  • 10
  • 24
Janusz Skonieczny
  • 17,642
  • 11
  • 55
  • 63
  • 1
    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... – anarcat Sep 15 '17 at 13:09
  • 2
    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. – Janusz Skonieczny Oct 30 '17 at 07:19
14

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

from .. import foo

to import the MyApp.foo module.

John Millikin
  • 197,344
  • 39
  • 212
  • 226
13

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
                            /                \
             [module1.py, module2.py,  [ut_module1.py, ut_module2.py,
              module3.py  module4.py,   ut_module3.py, ut_module.py]
              __init__.py]

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.

Rahul Biswas
  • 185
  • 1
  • 8
  • 2
    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 Jun 01 '18 at 11:41
  • 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?) – Jasha Jun 01 '18 at 11:43
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 setup.py and mirror your project directory structure for each test type (unittest, integration, ...)

For example if you have a directory structure like:

myPackage/
    myapp/
       moduleA/
          __init__.py
          module_A.py
       moduleB/
          __init__.py
          module_B.py
setup.py

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

myPackage/
    myapp/
       moduleA/
          __init__.py
          module_A.py
       moduleB/
          __init__.py
          module_B.py
test/
   unit/
      myapp/
         moduleA/
            module_A_test.py
         moduleB/
            module_B_test.py
   integration/
          myapp/
             moduleA/
                module_A_test.py
             moduleB/
                module_B_test.py
setup.py

Many properly written Python packages uses the same structure. A very good example is the Boto package. Check https://github.com/boto/boto

Arash
  • 609
  • 6
  • 10
  • 1
    It is recommended to use "tests" instead of "test", because "test" is a Python build in module. https://docs.python.org/2/library/test.html – brodul Dec 14 '17 at 09:59
  • Not always.. for example `matplotlib` has it under `matplotlib/lib/matplotlib/tests` (https://github.com/matplotlib/matplotlib/tree/38be7aeaaac3691560aeadafe46722dda427ef47/lib/matplotlib/tests) , `sklearn` has it under `scikitelearn/sklearn/tests` (https://github.com/scikit-learn/scikit-learn/tree/master/sklearn/tests) – alpha_989 Jan 28 '18 at 19:52
13

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.

dwestbrook
  • 5,108
  • 3
  • 25
  • 20
  • 4
    *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. – Piotr Dobrogost Nov 29 '11 at 19:21
  • This is what it looks like for me: `os.sys.path.append(os.dirname('..'))` – Mattwmaster58 Jul 09 '18 at 04:25
9

How I do it...

Folder structure:

project/
    src/
        code.py
    tests/
    setup.py

Setup.py points to src/ as the location containing my projects modules, then i run:

setup.py develop

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

setup.py tests

Using whichever test runner I've configured.

Dale Reidy
  • 1,189
  • 9
  • 22
  • You seem to have over-ridden the term "module". Most Python programmers would probably think that the module is the file you called `code.py`. It would make more sense to call the top level directory "project". – blokeley Apr 05 '11 at 11:50
5

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 setup.py test
  2. Set PYTHONPATH when running the tests: PYTHONPATH=. python tests/runalltests.py

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.

bstpierre
  • 30,042
  • 15
  • 70
  • 103
4

I put my tests in the same directory as the code under test (CUT). In projects where I can tweak pytest with my plugin, for foo.py I use foo.pt for the tests which makes editing a particular module and its test together really easy: vi foo.*.

Where I can't do this, I use foo_ut.py or similar. You can still use vi foo* though that will also catch foobar.py and foobar_ut.py if those exist.

In either case 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 editors started from the command line, as described above; for GUI systems, click on the code file and the adjacent (or very nearly 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.)

cjs
  • 25,752
  • 9
  • 89
  • 101
3

We use

app/src/code.py
app/testing/code_test.py 
app/docs/..

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.

buhtz
  • 10,774
  • 18
  • 76
  • 149
André
  • 12,971
  • 3
  • 33
  • 45
1

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.

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
George V. Reilly
  • 15,885
  • 7
  • 43
  • 38
1

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')
'testresult'

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

0

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 __init__.py 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 setup.py develop" you can just use "python setup.py test" or "python setup.py test -s foo_test.x.SomeTestSuite" to the just a specific suite.

Sebastian Rittau
  • 20,642
  • 3
  • 24
  • 21
-3

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:

app/
 appfile.py
test/
 appfileTest.py

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

quamrana
  • 37,849
  • 12
  • 53
  • 71