テストコードをさくっと学んだので自分用のメモを残す
Documents
Installation
pip install pytest
まずは関数をテストする。
src >> testするファイルを格納
# src/code.py
def sum_numbers(a, b):
return a + b
tests >> testcodeを格納するフォルダ
from folder_name import fileName
# tests/test_1.py
from src import code
def test_1():
result = code.sum_numbers(1, 2)
assert result == 3
#assert result == 2 #error
テストコードを実行する
pytest testS/test_1.py
成功例
tests\test_1.py . [100%]
================================== 1 passed in 0.02s ======================================
失敗例
tests\test_1.py . [100%]
================================== 1 failed in 0.06s ======================================
引数あり
# src/code.py
def sum_numbers(a, b):
return (a + b), a
# tests/test_1.py
from src import code
def test_1():
result1, result2 = code.sum_numbers(1, 2)
assert result1 == 3
assert result2 == 2
def test_1():
result1, result2 = code.sum_numbers(1, 2)
assert result1 == 3
> assert result2 == 2
E assert 1 == 2
tests\test_1.py:6: AssertionError
================================= short test summary info ==================================
FAILED tests/test_1.py::test_1 - assert 1 == 2
================================== 1 failed in 0.07s =======================================
# src/code.py
def sum_numbers(a, b):
return (a + b), a
assert result2 == 1に変更
# tests/test_1.py
from src import code
def test_1():
result1, result2 = code.sum_numbers(1, 2)
assert result1 == 3
assert result2 == 1
tests\test_1.py [100%]
================================== 1 passed in 0.02s =======================================
# from src import code
# def test_1():
# result1, result2 = code.sum_numbers(1, 2)
# assert result1 == 3
# assert result2 == 1
# content of test_class.py
def test_equal():
result = 1 +2
assert result == 3
def teest_notequal():
result = 1 + 2
assert result != 10
def test_string():
result = 'hello'
assert result == 'hello'
def test_string():
string = 'hello'
assert string.startswith('H')
def test_string():
string = 'hello'
assert 'he' in string
def test_boolean():
result = True
assert result == True