前言
一直想学习自动化测试,但是都没行动,业余时间学习零零碎碎并记录20210420。
6、使用pytest重构项目
- pytest框架介绍
- pytest标记
- pytest参数处理
- pytest Fixtrue
- pytest allure生成测试报告
- pytest setup和teardown的5种应用
- 使用pytest重构项目
Unittest setup和teardown介绍
Pytest setup和teardown介绍
Pytest setup和teardown的5种应用实例
1、模块级别的setup_module ,teardown_module 开始于模块始末 全局的
import pytest
# 1、模块级别的setup_module ,teardown_module 开始于模块始末 全局的
def setup_module():
print("setup_module")
def test01():
print('test01')
def test02():
print('test02')
def teardown_module():
print("teardown_module")
运行结果:命令行输入: pytest -sv test_08.py
2、函数级别的 setup_function teardown_function执行每一个函数时都会执行
# 函数级别的 setup_function teardown_function执行每一个函数时都会执行
def setup_function():
print("setup_function")
def teardown_function():
print("teardown_function")
def test01():
print('test01')
def test02():
print('test02')
运行结果:命令行输入: pytest -sv 文件名.py
3、在类中只执行一次的 setup_class,teardown_class 注意类名上要加@classmethod
# 3、在类中只执行一次的 setup_class,teardown_class 注意类名上要加@classmethod
class TestCase01(object):
@classmethod
def setup_class(cls):
print("setup_class")
def test001(self):
print("test001")
def test002(self):
print("test002")
@classmethod
def teardown_class(cls):
print("teardown_class")
运行结果:命令行输入: pytest -sv 文件名.py
4、类中方法级的(setup_method、teardown_method)在每一个方法之前执行一次,在每一个方法之后执行一次
"""
4、方法级:开始于方法始末(在类中)
setup_method
teardown_method
"""
class TestMethod(object):
def setup_class(self):
print("setup_class(self):每个类之前执行一次\n")
def teardown_class(self):
print("teardown_class(self):每个类之后执行一次")
def setup_method(self):
print("setup_method(self):在每个方法之前执行")
def teardown_method(self):
print("teardown_method(self):在每个方法之后执行\n")
def add(self,a,b):
print("这是加法运算")
return a+b
def test_01(self):
print("正在执行test1")
x = "this"
assert 'h' in x
def test_add(self):
print("正在执行test_add()")
assert self.add(3, 4) == 7
运行结果:命令行输入: pytest -sv 文件名.py
另:
5、类里面的(setup/teardown)运行在调用方法前后
# 类里面的(setup/teardown)运行在调用方法前后
class TestMethod(object):
def setup(self):
print("setup(self):运行在调用方法之前执行\n")
def teardown(self):
print("teardown(self):运行在调用方法之后执行\n")
def add(self,a,b):
print("这是加法运算\n")
return a+b
def test_01(self):
print("正在执行test1\n")
x = "this"
assert 'h' in x
def test_add(self):
print("正在执行test_add()\n")
assert self.add(3, 4) == 7
运行结果