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.py
could be:
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:
$ python -m unittest
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
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:
$ python -m pytest
========================================================= test session starts =========================================================
platform linux -- Python 3.11.5, pytest-7.4.2, pluggy-1.3.0
rootdir: ...
plugins: cov-4.1.0
collected 2 items
test/test_anothermodule/test_anotherscript.py . [ 50%]
test/test_module/test_script.py . [100%]
========================================================== 2 passed in 0.02s ==========================================================
Last updated