LoginSignup
82
81

More than 5 years have passed since last update.

Python 3 標準の unittest でテストを書く際のディレクトリ構成

Last updated at Posted at 2017-05-22

Python 3 でテストを書く際に pytest がよく使われているというのは耳にしたものの、とりあえず標準である unittest で書いてみるか、と思って試行錯誤したのでまとめる。

ディレクトリ構成とコード例

いくつかのパッケージの構成を見た限りでは、パッケージのディレクトリと同じ階層にテストディレクトリを作るのがセオリーらしい。

$ 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 ディレクトリ内のすべてのテストケースを実行する

$ python -m unittest discover tests

unittest では discover サブコマンド を使うことでディレクトリ内のテストをまとめて実行することができる。

デフォルトでは、指定したディレクトリ内の test*.py ファイルをすべて実行するが、オプションで変更することもできる。

サブディレクトリを再帰的に辿ってくれたりはしないらしい。

ひとつのテストケースだけを実行する

$ python -m unittest tests.test_foo

注意点として、直接 $ python tests/test_foo.py のように実行することはできない。Python では実行されたファイルのディレクトリ (/tests) がトップレベルの階層として扱われるため、それより上の階層に遡ってパッケージのファイルを import することができず、エラーになってしまう。

82
81
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
82
81