7

Is there a particular directory structure used for TDD in Python?

Tutorials talk about the content of the tests, but not where to place them

From poking around Python Koans, suspect its something like:

/project/main_program.py         # This has main method, starts program
/project/classes/<many classes>.py
/project/main_test.py            # This simply directs unittest onto tests, can use parameters fed to it to customise tests for environment
/project/tests/<many tests>.py

# to run tests, type "python -m unittest main_test.py" (into a terminal)
# to run program, type "python main_program.py"

Am I doing this right? Is there a good guide which teaches the directory hierarchy for TDD? I heard that having mixed files of code and tests is bad.

References:

Community
  • 1
  • 1
xxjjnn
  • 14,591
  • 19
  • 61
  • 94
  • For Newbies: If you have the structure as shown above, then to test /project/classes/codey.py with /project/tests/testy.py you would have "import codey from classes" written in testy.py so that it knows where to look. When importing, python searches up. So if you had /cat/sat/on/sometest.py and /cat/trolled/dog/somecode.py then "import somecode from cat.trolled.dog" would go into the test. – xxjjnn Mar 26 '12 at 12:03

2 Answers2

4

Based on your project, Whatever style lets you

  • Seperate implementation code from testing code
  • Create new tests easily
  • Run all tests in one operation (e.g. for regression testing)

The python koans/etc are just guidelines. In the end you want to uphold DRY with your unittests and be able to test easily, maintainably and intuitively. In the end it is up to you to decide your folder structure.

I feel like you are focusing too much on satisfying convention instead of satisfying your project.

Preet Kukreti
  • 8,417
  • 28
  • 36
  • 1
    That's cool it doesn't matter =) Think outside the... hey, what did you do with the box Python? – xxjjnn Mar 26 '12 at 12:04
  • It's still a valid question, and it gets asked on every prog language forum eventually. Ref http://stackoverflow.com/questions/193161/what-is-the-best-project-structure-for-a-python-application for more notes. – J.Z. Nov 18 '13 at 15:24
1

There are two basic options: in a top-level "test" (or "tests") directory, or in "test" directories within your package at every level. The former has the advantage of making it easy to have both unit tests and other tests consistently. The latter has the advantage of making it easy to run your tests against the installed version of the code, and is recommended by this blog post, which describes the basic structure that works well for Python projects.

At the end of the day, the important thing is to make them easy to find and run.

Mike Graham
  • 73,987
  • 14
  • 101
  • 130