[Tutor] Where to store test-code?
Mats Wichmann
mats at wichmann.us
Thu Jun 13 10:01:31 EDT 2019
On 6/13/19 2:22 AM, Thomas Güttler wrote:
> Up to now I use this structure:
>
> src/myapp/setup.py
> src/myapp/myapp/real_code.py
>
> Now I want to write a test for a method which is implemented real_code.py.
>
> Where should I write store the file which contains the unittest?
>
> Is there a guideline for the directory structure of tests?
>
> I know that there are several ways. I know that all these ways work.
> Nevertheless
> it would be great to have a sane default. If there is a guideline IDEs
> could assist
> to create new tests at a common location.
This question gets asked all the time, and it's hard to answer.
Other than the general requirement that the placement of the test should
not make it hard to find the code to be tested, *your* answer will be
determined by the scope of the project and by preferences.
You can put tests inline in the docstring, if you want to use doctest.
People dismiss this as a viable alternative, but the Python standard
library does this in some places - you don't get to write exhaustive
unit tests this way, but you can have something that serves as an
example and a quick test at the same time. For some examples, try this:
pydoc difflib
(hopefully you're not on Windows where that's probably not in the search
path)
If using pytest or unittest, you can put your tests in the same
directory as the code to be tested, naming the test file for foo.py as
test_foo.py, that way they're picked up automatically. For your example,
in src/myapp/myapp.
If you want separation of your app/module code and the tests , you can
put them a level up, thus src/myapp.
If you will have a lot of "source" files, you'll probably want a
parallel directory (probably simplifies deploy, if you intend to deploy
the code without the tests), thus src/myapp/tests (which is what it
sounds like what you're angling for us to tell you :) ). If you do that
though, there's a complication - tests will now have a harder time
finding the module code which is to be imported in running the tests,
and you'll have to take a few extra steps to make that work right.
If this were a TV courtroom drama someone would have risen to say
"objection, calls for speculation" - these things don't have an absolute
answer.
Anyway, the pytest project has some commentary on this that will likely
be more well thought out than my ramblings:
https://docs.pytest.org/en/latest/goodpractices.html
More information about the Tutor
mailing list