pytest使用规则及示例
Pytest是一个功能强大且易于使用的python测试框架
,支持编写单元测试
、集成测试
和功能测试
。
Pytest使用规则:
- 测试文件命名应符合
test_*.py
或*_test.py
- 若使用class对测试用例进行分组,测试类名应符合
TestXxx
- 测试用例函数/方法名称应符合
test_*()
另外,值得注意的是,pytest支持在测试类中定义setup
和teardown
方法,这写方法会在每个测试方法运行前后分别调用,用于设置测试环境和清理资源。setup_class
和teardown_class
方法在测试类中的所有测试方法之前和之后分别只运行一次。
下面编写一个计算器类Calculator,并使用pytest进行测试。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import pytest
class Calculator: @staticmethod def add(a, b): return a + b
@staticmethod def sub(a, b): return a - b
@staticmethod def mul(a, b): return a * b
@staticmethod def div(a, b): try: return a / b except ZeroDivisionError: print("zero Division Error Exception")
class TestCalc: def test_calc_add(self): assert Calculator.add(1, 2) == 3
def test_calc_sub(self): assert Calculator.sub(3, 1) == 2
def test_calc_mul(self): assert Calculator.mul(2, 4) == 8
def test_calc_div(self): assert Calculator.div(8, 4) == 2
def test_calc_div_zero_div_exp(self): with pytest.raises(ZeroDivisionError): Calculator.div(3, 0)
|