本帖最后由 つ兜兜里没糖 于 2021-3-19 17:03 编辑
1.pytest命名规范
文件test 或test_开头
类 Test 开头
函数或者方法test_开头
2.测试的前置和后置
模块级:setup_module, teardown_module
函数级: setup_function, teardown_function
环境初始化的动作放到前置中,比如登录,准备测试数据,打开浏览器等等
环境清理的动作放到后置中,比如退出登录,关闭浏览器等等def setup_module():
print("测试前置,模块级别的,整个文件所有用例前执行一次")
def teardown_module():
print("测试后置,模块级别的,整个文件所有用例执行完执行一次")
def setup_function():
print("测试前置,函数级别的,每个用例前执行")
def teardown_function():
print("测试后置,函数级别的,每个用例后执行")
类别级:setup_class, teardown_class
方法级别:setup_method, teardown_method
缺点: 命名必须按照规则来
使用不灵活,比如类里面有3个用例,2个用例执行时需要前置后置,另一个不需要前置后置,这个场景无法实现class Test001: #类名是用Test开头
def setup_class(self):
print("测试前置,类级别,类里所有用例前执行一次")
def teardown_class(self):
print("测试后置,类级别,类里所有用例执行后执行一次")
def setup_method(self):
print("测试前置,方法级别,每个方法前执行")
def teardown_method(self):
print("测试后置,方法级别,每个方法后执行")
def test_001(self):
print("用例1")
def test_002(self):
print("用例2")
def test_003(self):
print("用例3")3.测试前置和后置 fixture 任意命名 使用灵活import pytest
# 使用@pytest.fixture()修饰后,该函数/方法属于前置和后置
@pytest.fixture(scope='function') # 默认是函数级别的
def login():
print("登录系统") #在yield之前是前置
yield
print("退出登录") #在yield之后是后置
# 是模块级别的,第一次使用这个fixture时, 调用前置,所有用例执行完之后,执行后置
@pytest.fixture(scope='module')
def db():
print("连接数据库")
yield
print("断开数据库连接")
def test_001():
print("查询的用例,不需要登录")4.pytest mark 标记
1.跳过用例(有缺陷的用例跳过不执行)
2.选择部分用例执行,工程中用例规模越来越大,包含界面自动化,接口自动化,性能,冒烟测试
只想执行冒烟测试的用例,怎么办。
自定义标记。mark,后面的字符串自己定义的
自定义标记在pytest.ini中注册下。执行时加参数
-m="smoke" 执行带smoke标记的用例
-m="func or smoke" 执行带smoke标记或者带func标记的用例
-m="func and smoke" 执行带smoke标记且带func标记的用例
-m="func or not smoke" 执行带func标记的用例但不执行带smoke标记的用例import pytest
version ='V1R1'
@pytest.mark.smoke #冒烟测试
def test001():
print("用例1")
@pytest.mark.skip("因为xxx缺陷,该用例执行失败,待缺陷解决后再执行")
def test002():
print("用例2")
# 前面的表达式为true时跳过,为false时不跳过
@pytest.mark.skipif(version=='V1R1', reason="V1R2以上版本增加的功能,V1R2不支持")
def test003():
print("用例3")
@pytest.mark.func #功能用例
def test004():
print("用例4")
@pytest.mark.func #给类上加标记,类中每个用例都带有这个标记
class Test001:
def test_005(self):
print("用例5")
@pytest.mark.smoke
def test_006(self):
print("用例6")
def test_007(self):
print("用例7")
def test_008(self):
print("用例8")
|