LoginSignup
1
4

More than 5 years have passed since last update.

Pythonのテストを動かしてみた

Posted at

とりあえずassertを使って動作確認をしてみる。
以下のサンプルコードを同一改装に保存する。

テスト用サンプルコード

sample_file1.py

def r_str(val):
    s = str(val)
    return s

def r_ch_str(val):
    s = str(val) + 'hgoe'
    return s

def r_true():
    return True

def r_false():
    return False

def raise_type_error():
    raise TypeError

テストコード

assert_test.py

import unittest
import sample_file1 as sf


# モジュール全体の初期化時に一度だけ読み込まれる
def setUpModule():
    print('set_up_module!')

# モジュール全体の終了時に一度だけ読み込まれる
def tearDownModule():
    print('tear_down_module!')

class TestAssert(unittest.TestCase):

    """
    初期設定
    """

    # テスト初期化時に一度だけ読み込まれる処理
    @classmethod
    def setUpClass(self):
        print('set_up_class!')

    # テスト終了時に一度だけ読み込まれる処理
    @classmethod
    def setUpClass(self):
        print('set_up_class!')

    # テスト単位の実行時に読み込まれる処理
    def setUp(self):
        print('set_up!')

        self.dummy_text = 'ダミーテキスト'
        self.dummy_num  = 0

    # テスト単位の実行時に読み込まれる処理
    def tearDown(self):
        print('tear_down!')


    """
    テスト開始
    """

    # assertEqual -> a == b
    def test_assert_equal(self):
        exam = self.dummy_text
        res  = sf.r_str(self.dummy_text)
        self.assertEqual(res, exam)

    # assertNotEqual -> a != b
    def test_assert_NotEqual(self):
        exam = self.dummy_text
        res  = sf.r_ch_str(self.dummy_text)
        self.assertNotEqual(res, exam)

    # assertTrue -> is True
    def test_assert_true(self):
        self.assertTrue(sf.r_true())

    # assertFalse -> is False
    def test_assert_false(self):
        self.assertFalse(sf.r_false())

    # assertRaises -> check ErrorType
    def test_assert_raises(self):
        self.assertRaises(TypeError, sf.raise_type_error)


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



テスト実行方法

$ python assert_test.py

デバッグ方法(ブレイクポイント)

以下のコードを停止したい場所に埋め込む

import pdb; pdb.set_trace()

def r_str(val):
    s = str(val)
    import pdb; pdb.set_trace()
    return s

感想

とりあえずこれだけわかればテストがかけそう。
今後も記事をアップデートする予定。

参考

1
4
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
1
4