LoginSignup
0
1

More than 5 years have passed since last update.

Python2でユニットテストする

Last updated at Posted at 2019-01-02

はじめに

標準で入ってるユニットテストのフレームワークである unittest を使ってみる。

環境

Python 2.7

ディレクトリ、ファイル構造

$ tree -P '*.py' project
project
├── a.py
└── tests
    ├── __init__.py
    └── test_add.py

コード

mkdir -pv ./project

cat <<'__PYTHON__' | tee ./project/a.py
#!/usr/bin/env python2
# coding: utf-8

def add(x, y):
    return x - y

if __name__ == '__main__':
    print(add(1,2))
__PYTHON__
chmod -v +x ./project/a.py

mkdir -pv ./project/tests

cat <<'__PYTHON__' | tee ./project/tests/test_add.py
import unittest
import a

class TestAdd(unittest.TestCase):
    def test_add(self):
        x = 2
        y = 3
        expected = 5
        actual = a.add(x, y)
        self.assertEqual(expected, actual)

if __name__ == "__main__":
    unittest.main()
__PYTHON__

touch ./project/tests/__init__.py

実行結果

cd ./projects
python -m unittest tests.test_add
python -m unittest discover tests
$ python -m unittest tests.test_add
F
======================================================================
FAIL: test_add (tests.test_add.TestAdd)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests/test_add.py", line 10, in test_add
    self.assertEqual(expected, actual)
AssertionError: 5 != -1

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)
$ python -m unittest discover tests
F
======================================================================
FAIL: test_add (test_add.TestAdd)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/root/unittest/project/tests/test_add.py", line 10, in test_add
    self.assertEqual(expected, actual)
AssertionError: 5 != -1

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)
$

参考資料

基本的な使い方はここがわかりやすい。
https://qiita.com/aomidro/items/3e3449fde924893f18ca

ディレクトリ構造はここがわかりやすい。
https://qiita.com/hoto17296/items/fa0166728177e676cd36

0
1
3

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
1