pythonテストコードの書き方(unittest)
| 登録日 | :2025/07/22 19:13 |
|---|---|
| カテゴリ | :Python基礎 |
unittestでテストを書くサンプル
以下のcalculation.pyを、unittestを使ってテストをするサンプルコード
calculation.py
import os.path
class Cal(object):
def __init__(self):
self.test_string = 'test'
def save_tmp_file(self, dir_path, file_name):
if not os.path.exists(dir_path):
os.mkdir(dir_path)
file_path = os.path.join(dir_path, file_name)
with open(file_path, 'w') as f:
f.write(self.test_string)
@staticmethod
def add_num_and_double(x, y):
if type(x) is not int or type(y) is not int:
raise ValueError
result = x + y
result *= 2
return result
unitlistによるテストコード
test_calculation.py
import unittest
from test.calculation import Cal
release_name = 'lesson'
class CalTest(unittest.TestCase):
def setUp(self):
print('setup')
self.cal = Cal()
def tearDown(self) -> None:
print('clean up')
del self.cal
@unittest.skipIf(release_name=='lesson', 'skip!!')
def test_add_num_and_double(self):
self.assertEqual(self.cal.add_num_and_double(1, 1), 4)
def test_raise(self):
with self.assertRaises(ValueError):
self.cal.add_num_and_double('1', '1')
if __name__ == '__main__':
unittest.main()