testing

unittest

Say you have a project named deadbeef, then the following directory structure seem to do the job quite well:

deadbeef/
β”œβ”€β”€ src
β”‚   β”œβ”€β”€ anothermodule
β”‚   β”‚   └── anotherscript.py
β”‚   └── module
β”‚       └── script.py
└── test
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ test_anothermodule
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   └── test_anotherscript.py
    └── test_module
        β”œβ”€β”€ __init__.py
        └── test_script.py

Where an example of how test_script.pycould be:

test_script.py
import unittest
import src.module.script

class TestScript(unittest.TestCase):
    def test_plus_one(self): 
        res = src.module.script.plus_one(0)
        self.assertEqual(res, 1)

if __name__ == '__main__':
    unittest.main()

This way, the structure is to a high degree self-explanatory. The source code for each module is separated from the test code and represented in the same structure, except for the use of test_*. Also, new modules and tests can be added as necessary without hassle.

Tests can then be run from deadbeef/utilizing automatic discovery as such:

pytest

Same directory structure as above can be used, and if it is preferred to go without __init__.py files, then execution is done as:

Last updated