I've heard that pytest is often used when writing tests in Python 3, but for the time being, it's standard unittest. I wondered if I should write it at //docs.python.jp/3/library/unittest.html#module-unittest), so I summarized it by trial and error.
As far as the structure of some packages is seen, it seems that the theory is to create a test directory in the same hierarchy as the package directory.
$ tree
.
├── foo
│ ├── foo.py
│ ├── :
│ └── xxx.py
└── tests
├── test_foo.py
├── :
└── test_xxx.py
foo/foo.py
class Foo:
def say(self):
return 'foo'
tests/test_foo.py
from unittest import TestCase
from foo.foo import Foo
class TestFoo(TestCase):
def test_say(self):
self.assertEqual(Foo().say(), 'foo')
tests
directory$ python -m unittest discover tests
In unittest, you can execute all the tests in the directory by using discover subcommand.
By default, all test * .py
files in the specified directory are run, but you can optionally change them.
It doesn't seem to recursively follow subdirectories.
$ python -m unittest tests.test_foo
Note that you can't run it directly like $ python tests / test_foo.py
. Python treats the executed file directory (/ tests
) as a top-level hierarchy, so you can't go back up and import packaged files, resulting in an error.
Recommended Posts