0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python: unittest 抽象テストケースの定義方法

Posted at

あらまし

Python test ドキュメント: test --- Python 用回帰テストパッケージ — Python 3.10.16 ドキュメントを読んでいて、おもしろい記述を見つけた:

できる限りテストコードを再利用するようにしましょう。時として、入力の違いだけを記述すれば良くなるくらい、テストコードを小さくすることができます。例えば以下のように、サブクラスで入力を指定することで、コードの重複を最小化することができます:

class TestFuncAcceptsSequencesMixin:

   func = mySuperWhammyFunction

   def test_func(self):
       self.func(self.arg)

class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
   arg = [1, 2, 3]

class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
   arg = 'abc'

class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
   arg = (1, 2, 3)

このパターンを使うときには、 unittest.TestCase を継承した全てのクラスがテストとして実行されることを忘れないでください。 上の例の Mixin クラスはテストデータを持っておらず、それ自身は実行できないので、 unittest.TestCase を継承していません。

なるほど、この書き方は確かに使いやすいが TestFuncAcceptsSequencesMixin の中で unittest.TestCase.assert* を使いたい場合どうするんだ?と思ったので調査した。

結論

下記のようにするとよい。

class TestFuncAcceptsSequencesMixin(unittest.TestCase): # ←いったんミックスインクラスをテストケースにしてしまう

    func = mySuperWhammyFunction

    def test_func(self):
        self.func(self.arg)
        self.assertEqual(1,1) # ←使える!

class AcceptLists(TestFuncAcceptsSequencesMixin):
    arg = [1, 2, 3]

class AcceptStrings(TestFuncAcceptsSequencesMixin):
    arg = 'abc'

class AcceptTuples(TestFuncAcceptsSequencesMixin):
    arg = (1, 2, 3)

del TestFuncAcceptsSequencesMixin # ←ミックスインクラスを消す!

こうすることで unittest のテストディスカバリからミックスインクラスの存在を隠蔽することができる。

参考にしました

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?