victory的博客

长安一片月,万户捣衣声

0%

pytest | pytest使用规则及示例

pytest使用规则及示例

Pytest是一个功能强大且易于使用的python测试框架,支持编写单元测试集成测试功能测试

Pytest使用规则:

  1. 测试文件命名应符合test_*.py*_test.py
  2. 若使用class对测试用例进行分组,测试类名应符合TestXxx
  3. 测试用例函数/方法名称应符合test_*()

另外,值得注意的是,pytest支持在测试类中定义setupteardown方法,这写方法会在每个测试方法运行前后分别调用,用于设置测试环境和清理资源。setup_classteardown_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
# test_calculator.py 测试文件名称符合test_*.py
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: # 测试类名符合TestXxx
def test_calc_add(self): # 测试用例方法名符合test_*()
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)