Python test入門 その2

はじめに

前回の記事Python test入門 その1に引き続き、Pythonのテストについて、標準ライブラリであるunittestを使って学んでいきます。

今回も公式リファレンスのコードを引用しながら、解説をしていきます。

解説

テストディスカバリ

複数のファイルに対してテストを実行したい場合があります。

その場合は下記のようにコマンドを実行します。

1
python -m unittest discover

カレントディレクトリにある、testから始まるテストスクリプトを実行します。

前処理と後処理

テストにあたり、前処理や後処理を実行したい場合があります。

そういった場合は、setUptearDownを用います。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import unittest

class TestStringMethods(unittest.TestCase):

def setUp(self):
print ('setUp')

def tearDown(self):
print ('tearDown')

def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')

def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())

def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)

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

(改行が入らず分かりにくいですが)前処理と後処理が実行されていることが確認できます。

各処理はそれぞれのテストケースに対して実施されます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
test_isupper (__main__.TestStringMethods) ... setUp
tearDown
ok
test_split (__main__.TestStringMethods) ... setUp
tearDown
ok
test_upper (__main__.TestStringMethods) ... setUp
tearDown
ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

クラス単位で前処理、後処理を行いたい場合はクラスメソッドを利用して、下記のように実装します。

1
2
3
4
5
6
7
@classmethod
def setUpClass(self):
print ('setUpClass')

@classmethod
def tearDownClass(self):
print ('tearDownClass')

メソッド

以下に示した12のメソッドが用意されています

1
2
3
4
5
6
7
8
9
10
11
12
assertEqual(a, b)
assertNotEqual(a, b)
assertTrue(x)
assertFalse(x)
assertIs(a, b)
assertIsNot(a, b)
assertIsNone(x)
assertIsNotNone(x)
assertIn(a, b)
assertNotIn(a, b)
assertIsInstance(a, b)
assertNotIsInstance(a, b)

一部、コードを載せておきます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import unittest

class TestMethods(unittest.TestCase):
def test_assert_equal(self):
self.assertEqual(1, 1)

def test_assert_not_equal(self):
self.assertNotEqual(1, 2)

def test_assert_true(self):
self.assertTrue(True)

def test_assert_false(self):
self.assertFalse(False)

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

次回に続きます!

Python test入門 その3

記事情報

  • 投稿日:2020年4月9日
  • 最終更新日:2020年4月10日