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

<p>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.  </p>

<p>Is there a best practice here?</p>

[{'answer_id': 61168, 'author': 'dwestbrook', 'author_id': 3119, 'author_profile': 'https://Stackoverflow.com/users/3119', 'pm_score': 4, 'selected': False, 'text': '<p>I don\'t believe there is an established "best practice".</p>\n\n<p>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.</p>\n'}, {'answer_id': 61169, 'author': 'Cristian', 'author_id': 680, 'author_profile': 'https://Stackoverflow.com/users/680', 'pm_score': 6, 'selected': False, 'text': '<p>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:</p>\n\n<pre><code>parent_dir/\n  foo.py\n  tests/\n</code></pre>\n\n<p>Of course there is no one way of doing it. You could also make a tests subdirectory and import the module using <a href="http://www.python.org/dev/peps/pep-0328/" rel="noreferrer">absolute import</a>.</p>\n\n<p>Wherever you put your tests, I would recommend you use <a href="http://nose.readthedocs.org/en/latest/" rel="noreferrer">nose</a> to run them. <a href="http://nose.readthedocs.org/en/latest/" rel="noreferrer">Nose</a> searches through your directories for tests. This way, you can put tests wherever they make the most sense organizationally.</p>\n'}, {'answer_id': 61518, 'author': 'quamrana', 'author_id': 4834, 'author_profile': 'https://Stackoverflow.com/users/4834', 'pm_score': -1, 'selected': False, 'text': "<p>I've recently started to program in Python, so I've not really had chance to find out best practice yet.\nBut, I've written a module that goes and finds all the tests and runs them.</p>\n\n<p>So, I have:</p>\n\n<pre>\napp/\n appfile.py\ntest/\n appfileTest.py\n</pre>\n\n<p>I'll have to see how it goes as I progress to larger projects.</p>\n"}, {'answer_id': 61531, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 4, 'selected': False, 'text': '<p>I use a <code>tests/</code> directory, and then import the main application modules using relative imports. So in MyApp/tests/foo.py, there might be:</p>\n\n<pre><code>from .. import foo\n</code></pre>\n\n<p>to import the <code>MyApp.foo</code> module.</p>\n'}, {'answer_id': 61820, 'author': 'George V. Reilly', 'author_id': 6364, 'author_profile': 'https://Stackoverflow.com/users/6364', 'pm_score': 1, 'selected': False, 'text': '<p>In C#, I\'ve generally separated the tests into a separate assembly.</p>\n\n<p>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 <code>if __name__ == "__main__"</code> block at the bottom of the module.</p>\n'}, {'answer_id': 62527, 'author': 'user6868', 'author_id': 6868, 'author_profile': 'https://Stackoverflow.com/users/6868', 'pm_score': 8, 'selected': False, 'text': '<p>For a file <code>module.py</code>, the unit test should normally be called <code>test_module.py</code>, following Pythonic naming conventions.</p>\n\n<p>There are several commonly accepted places to put <code>test_module.py</code>:</p>\n\n<ol>\n<li>In the same directory as <code>module.py</code>.</li>\n<li>In <code>../tests/test_module.py</code> (at the same level as the code directory).</li>\n<li>In <code>tests/test_module.py</code> (one level under the code directory).</li>\n</ol>\n\n<p>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 <code>test_</code>. Actually, the <a href="https://docs.python.org/library/unittest.html#test-discovery" rel="noreferrer">default <code>unittest</code> pattern used for test discovery is <code>test*.py</code></a>.</p>\n'}, {'answer_id': 63645, 'author': 'Sebastian Rittau', 'author_id': 7779, 'author_profile': 'https://Stackoverflow.com/users/7779', 'pm_score': 0, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 77145, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>If the tests are simple, simply put them in the docstring -- most of the test frameworks for Python will be able to use that:</p>\n\n<pre><code>&gt;&gt;&gt; import module\n&gt;&gt;&gt; module.method('test')\n'testresult'\n</code></pre>\n\n<p>For other more involved tests, I'd put them either in <code>../tests/test_module.py</code> or in <code>tests/test_module.py</code>.</p>\n"}, {'answer_id': 103610, 'author': 'Thomas Andrews', 'author_id': 7061, 'author_profile': 'https://Stackoverflow.com/users/7061', 'pm_score': 5, 'selected': False, 'text': "<p>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</p>\n\n<pre><code>if __name__ == '__main__':\n   do tests...\n</code></pre>\n\n<p>block.  This ends up adding documentation to the file as 'example code' for how to use the python file you are testing.</p>\n\n<p>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:</p>\n\n<pre><code>if __name__ == '__main__':\n   import tests.thisModule\n   tests.thisModule.runtests\n</code></pre>\n\n<p>This lets anybody reading your source code know where to look for the test code.</p>\n"}, {'answer_id': 128616, 'author': 'André', 'author_id': 9683, 'author_profile': 'https://Stackoverflow.com/users/9683', 'pm_score': 2, 'selected': False, 'text': "<p>We use </p>\n\n<pre><code>app/src/code.py\napp/testing/code_test.py \napp/docs/..\n</code></pre>\n\n<p>In each test file we insert <code>../src/</code> in <code>sys.path</code>. 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.</p>\n"}, {'answer_id': 382596, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I prefer toplevel tests directory. This does mean imports become a little more difficult. For that I have two solutions:</p>\n\n<ol>\n<li>Use setuptools. Then you can pass <code>test_suite=\'tests.runalltests.suite\'</code> into <code>setup()</code>, and can run the tests simply: <code>python setup.py test</code></li>\n<li>Set PYTHONPATH when running the tests: <code>PYTHONPATH=. python tests/runalltests.py</code></li>\n</ol>\n\n<p>Here\'s how that stuff is supported by code in M2Crypto:</p>\n\n<ul>\n<li><a href="http://svn.osafoundation.org/m2crypto/trunk/setup.py" rel="nofollow noreferrer">http://svn.osafoundation.org/m2crypto/trunk/setup.py</a></li>\n<li><a href="http://svn.osafoundation.org/m2crypto/trunk/tests/alltests.py" rel="nofollow noreferrer">http://svn.osafoundation.org/m2crypto/trunk/tests/alltests.py</a></li>\n</ul>\n\n<p>If you prefer to run tests with nosetests you might need do something a little different.</p>\n'}, {'answer_id': 815212, 'author': 'Paul Hildebrandt', 'author_id': 99896, 'author_profile': 'https://Stackoverflow.com/users/99896', 'pm_score': 5, 'selected': False, 'text': '<p>We had the very same question when writing Pythoscope (<a href="https://pypi.org/project/pythoscope/" rel="nofollow noreferrer">https://pypi.org/project/pythoscope/</a>), 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.  </p>\n'}, {'answer_id': 2363162, 'author': 'Dale Reidy', 'author_id': 50746, 'author_profile': 'https://Stackoverflow.com/users/50746', 'pm_score': 3, 'selected': False, 'text': "<p>How I do it...</p>\n\n<p>Folder structure:</p>\n\n<pre><code>project/\n    src/\n        code.py\n    tests/\n    setup.py\n</code></pre>\n\n<p>Setup.py points to src/ as the location containing my projects modules, then i run:</p>\n\n<pre><code>setup.py develop\n</code></pre>\n\n<p>Which adds my project into site-packages, pointing to my working copy. To run my tests i use:</p>\n\n<pre><code>setup.py tests\n</code></pre>\n\n<p>Using whichever test runner I've configured.</p>\n"}, {'answer_id': 22704148, 'author': 'Rahul Biswas', 'author_id': 2726038, 'author_profile': 'https://Stackoverflow.com/users/2726038', 'pm_score': 4, 'selected': False, 'text': '<p>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. </p>\n\n<pre><code>                              &lt;Main Package&gt;\n                               /          \\\n                              /            \\\n                            lib           tests\n                            /                \\\n             [module1.py, module2.py,  [ut_module1.py, ut_module2.py,\n              module3.py  module4.py,   ut_module3.py, ut_module.py]\n              __init__.py]\n</code></pre>\n\n<p>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. </p>\n'}, {'answer_id': 23386287, 'author': 'Steely Wing', 'author_id': 1877620, 'author_profile': 'https://Stackoverflow.com/users/1877620', 'pm_score': 7, 'selected': False, 'text': '<h1>Only 1 test file</h1>\n\n<p>If there has only 1 test files, putting it in a top-level directory is recommended:</p>\n\n<pre><code>module/\n    lib/\n        __init__.py\n        module.py\n    test.py\n</code></pre>\n\n<p>Run the test in CLI</p>\n\n<pre class="lang-sh prettyprint-override"><code>python test.py\n</code></pre>\n\n<h1>Many test files</h1>\n\n<p>If has many test files, put it in a <code>tests</code> folder:</p>\n\n<pre><code>module/\n    lib/\n        __init__.py\n        module.py\n    tests/\n        test_module.py\n        test_module_function.py\n</code></pre>\n\n<pre class="lang-py prettyprint-override"><code># test_module.py\n\nimport unittest\nfrom lib import module\n\nclass TestModule(unittest.TestCase):\n    def test_module(self):\n        pass\n\nif __name__ == \'__main__\':\n    unittest.main()\n</code></pre>\n\n<p>Run the test in CLI</p>\n\n<pre class="lang-sh prettyprint-override"><code># In top-level /module/ folder\npython -m tests.test_module\npython -m tests.test_module_function\n</code></pre>\n\n<h2>Use <a href="https://docs.python.org/3/library/unittest.html#test-discovery" rel="noreferrer"><code>unittest discovery</code></a></h2>\n\n<p><code>unittest discovery</code> will find all test in package folder.</p>\n\n<p>Create a <code>__init__.py</code> in <code>tests/</code> folder</p>\n\n<pre><code>module/\n    lib/\n        __init__.py\n        module.py\n    tests/\n        __init__.py\n        test_module.py\n        test_module_function.py\n</code></pre>\n\n<p>Run the test in CLI</p>\n\n<pre class="lang-sh prettyprint-override"><code># In top-level /module/ folder\n\n# -s, --start-directory (default current directory)\n# -p, --pattern (default test*.py)\n\npython -m unittest discover\n</code></pre>\n\n<h1>Reference</h1>\n\n<ul>\n<li><a href="https://pytest.readthedocs.io/en/latest/goodpractices.html" rel="noreferrer"><code>pytest</code> Good Practices</a> for test layout</li>\n<li><a href="https://docs.python.org/3/library/unittest.html" rel="noreferrer"><code>unittest</code></a></li>\n</ul>\n\n<h1>Unit test framework</h1>\n\n<ul>\n<li><a href="https://nose.readthedocs.org/en/latest/" rel="noreferrer">nose</a></li>\n<li><a href="https://docs.nose2.io/en/latest/" rel="noreferrer">nose2</a></li>\n<li><a href="https://pytest.readthedocs.io/en/latest/contents.html" rel="noreferrer">pytest</a></li>\n</ul>\n'}, {'answer_id': 37122327, 'author': 'Arash', 'author_id': 832304, 'author_profile': 'https://Stackoverflow.com/users/832304', 'pm_score': 4, 'selected': False, 'text': '<p>I recommend you check some main Python projects on GitHub and get some ideas.</p>\n\n<p>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, ...)</p>\n\n<p>For example if you have a directory structure like:</p>\n\n<pre><code>myPackage/\n    myapp/\n       moduleA/\n          __init__.py\n          module_A.py\n       moduleB/\n          __init__.py\n          module_B.py\nsetup.py\n</code></pre>\n\n<p>After adding test folder you will have a directory structure like:</p>\n\n<pre><code>myPackage/\n    myapp/\n       moduleA/\n          __init__.py\n          module_A.py\n       moduleB/\n          __init__.py\n          module_B.py\ntest/\n   unit/\n      myapp/\n         moduleA/\n            module_A_test.py\n         moduleB/\n            module_B_test.py\n   integration/\n          myapp/\n             moduleA/\n                module_A_test.py\n             moduleB/\n                module_B_test.py\nsetup.py\n</code></pre>\n\n<p>Many properly written Python packages uses the same structure. A very good example is the Boto package.\nCheck <a href="https://github.com/boto/boto" rel="noreferrer">https://github.com/boto/boto</a></p>\n'}, {'answer_id': 39740835, 'author': 'Janusz Skonieczny', 'author_id': 260480, 'author_profile': 'https://Stackoverflow.com/users/260480', 'pm_score': 5, 'selected': False, 'text': '<p>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. </p>\n\n<p>The main reason for doing this is: <strong>refactoring</strong>.</p>\n\n<p>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 <a href="https://github.com/django/django" rel="noreferrer">django</a>, <a href="https://github.com/pallets/flask" rel="noreferrer">flask</a> and many others. Which is fine if you don\'t care.</p>\n\n<p>The main question you should ask yourself is this:  </p>\n\n<p>Am I writing:  </p>\n\n<ul>\n<li>a) reusable library or  </li>\n<li>b) building a project than bundles together some semi-separated modules?</li>\n</ul>\n\n<p>If a: </p>\n\n<p>A separate folder and the extra effort to maintain its structure may be better suited. No one will complain about your tests getting <em>deployed to production</em>. </p>\n\n<p>But it\'s also just as easy to exclude tests from being distributed when they are mixed with the core folders; <a href="http://setuptools.readthedocs.io/en/latest/setuptools.html?highlight=find_packages#using-find-packages" rel="noreferrer">put this in the setup.py</a>:</p>\n\n<pre><code>find_packages("src", exclude=["*.tests", "*.tests.*", "tests.*", "tests"]) \n</code></pre>\n\n<p>If b: </p>\n\n<p>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. </p>\n\n<p>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).</p>\n\n<p>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.    </p>\n'}, {'answer_id': 53740627, 'author': 'cjs', 'author_id': 107294, 'author_profile': 'https://Stackoverflow.com/users/107294', 'pm_score': 2, 'selected': False, 'text': '<p>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 <code>foo.py</code> I use <code>foo.pt</code> for the tests which makes editing a particular module and its test together really easy: <code>vi foo.*</code>.</p>\n<p>Where I can\'t do this, I use <code>foo_ut.py</code> or similar. You can still use <code>vi foo*</code> though that will also catch <code>foobar.py</code> and <code>foobar_ut.py</code> if those exist.</p>\n<p>In either case I tweak the test discovery process to find these.</p>\n<p>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.</p>\n<p>As <a href="https://stackoverflow.com/a/39740835/107294">others have pointed out</a>, this also makes it easier to refactor and to extract the code for use elsewhere should that ever be necessary.</p>\n<p>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.)</p>\n'}]
['https://Stackoverflow.com/questions/61151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4883/']