I hear and I forget.
I see and I remeber.
I do and I understand.
建立 PyCharm 專案後,在 Terminal 用 pip 安裝
pip install pytest
import math def test_sqrt(): num = 25 assert math.sqrt(num) == 5 def test_square(): num = 7 assert 7 * 7 == 40 # 49 # assert 7 * 7 == 49 # 49 def test_equality(): # assert 10 == 11 # 10 assert 10 != 11 # 10
git clone git@github.com:cclai999/pytest-0706.git conda create --name pytestlab python=3.8
I hear and I forget.
I see and I remeber.
I do and I understand.
def hello_name(name): return f'Hello {name}' if __name__ == '__main__': print(hello_name("Max"))
test_hello_unittest.py
import unittest from hello import hello_name class TestHello(unittest.TestCase): def test_hello_name(self): self.assertEqual(hello_name('Max'), 'Hello Max')
python -m unittest test_hello_unittest.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
test_hello_pytest.py
from hello import hello_name def test_hello_name(): assert hello_name('Max') == 'Hello Max'
$ pytest test_hello_pytest.py
"F" 表示測試沒有通過,如果出現 "." 則表示成功
$ pytest -v test_hello_pytest.py
$ pytest test_hello_pytest.py
"F" 表示測試沒有通過,如果出現 "." 則表示成功
$ pytest -v test_hello_pytest.py
Unit tests are typically automated tests written and run by software developers to ensure that a section of an application (known as the "unit") meets its design and behaves as intended. In procedural programming, a unit could be an entire module, but it is more commonly an individual function or procedure.
有些人會稱為 CUT (Class Under Test or Code Under Test)
def sum(a,b): result = int(a) + int(b) return result
production code (calculator.py)
def divide(self, a, b): """Divide two numbers.""" try: return a / b except ZeroDivisionError as ex: raise CalculatorError("You can't divide by zero.") from ex
test code (test_calculator.py)
def test_divide_by_zero(): calculator = Calculator() # result = calculator.divide(9, 0) with pytest.raises(CalculatorError): result = calculator.divide(9, 0)
production code (triangle.py)
def type_of_triangle(a, b, c): if not is_valid_triangle(a, b, c): return "不是三角形" if (a == b) and (b == c): return "等邊三角形" elif (a == b) or (b == c) or (a == c): return "等腰三角形" elif (a * a + b * b == c * c) or (a * a + c * c == b * b) or (c * c + b * b == a * a): return "直角三角形" else: return "一般三角形"
test code (test_triangle.py)
@pytest.mark.parametrize("a,b,c,expected", [ (0, 1, 3, "不是三角形"), (1, 1, 1, "等邊三角形"), (2, 2, 3, "等腰三角形"), (3, 4, 5, "直角三角形"), (4, 5, 6, "一般三角形") ]) def test_type_of_triangle(a, b, c, expected): assert expected == type_of_triangle(a, b, c)
一個單元測試通常包含了三個行為
在單元測試之前先建立好變數或物件,可重覆利用
@pytest.fixture() def some_data(): return 42 def test_some_data(some_data): """Return value for fixture.""" assert some_data == 42 def test_inc_data(some_data): """Use fixture return value in a test.""" inc_data = some_data + 1 assert inc_data == 43
pytest -v test_fixtures.py
pytest -v --setup-show test_scope.py
pytest -v -s test_autouse.py
pytest -v -s test_yield.py