当前位置:网站首页>pytest框架实现前后置
pytest框架实现前后置
2022-07-02 06:36:00 【迷途~知返】
pytest前后置处理
setup/teardown,setup_class/teardown_class
setup/teardown和setup_class/teardown_class
import pytest
import time
class TestLogin:
age = 17
def setup_class(self):
print("在每个类执行前的初始化工作:比如:创建日志对象,创建数据库对象,创建接口对象")
# 在每个测试方法之前都会执行
def setup(self):
print("\n在执行测试用例之前初始化的代码,打开浏览器,加载网页")
@pytest.mark.smoke
def test_01_login(self):
print("测试login。。。")
def test_02_regis(self):
print("i crazy")
@pytest.mark.skip(reason="this is not dragon")
def test_05_drogn(self):
print('this is parper')
@pytest.mark.skipif(age<18,reason='还未成年')
def test_04_huahua(self):
print('hello my name is xxx')
@pytest.mark.usermanage
def test_03_haha(self):
print('hahahahahahahah')
def teardown(self):
print("\n在执行测试用例之后的扫尾代码:关闭浏览器")
def teardown_class(self):
print("在每个类执行之后的扫尾工作:比如:销毁的日志对象,销毁数据库对象,创建接口的请求对象")
if __name__ == "__main__":
pytest.main()
pytest.fixture()装饰器来实现部分用例的前后置
@pytest.fixture(scope=‘function’, params=‘’, autouse=‘’, name=‘’)
- scope表示的是被@pytest.fixture标记方法的作用域。默认是function,class,model,package,session
- params:参数化(list,tuple,字典列表[{},{},{}],字典元组({},{},{}))
- autouse:自动执行,默认是false
- ids:当使用params,给每一个值设置一个变量名,意义不大
- name:给被@pytest.fixture标记的方法取一个别名
scope=‘function’
手动调用前后置的方法,想让那些方法执行前后置就让那些方法执行
# coding:utf-8
import pytest
@pytest.fixture(scope='function')
def my_fixture():
print('前置的方法是,实现部分以及全部用例的前置')
yield
print('用例后置的方法,实现部分以及全部用例的后置')
class TestFixture:
def test_case(self, fix1): # 注意fix1为conftest中的方法
print('test 01,没有前置方法')
def test_02(self, my_fixture):
print('有前置方法')
if __name__ == '__main__':
pytest.main(['-vs'])

自动调用前后置方法,可以自动执行,但是不能控制那些方法执行那些不执行,只要是作用域内命中的方法都要执行fixture
# coding:utf-8
import pytest
@pytest.fixture(scope='function', autouse=True)
def my_fixture():
print('前置的方法是,实现部分以及全部用例的前置')
yield
print('用例后置的方法,实现部分以及全部用例的后置')
class TestFixture:
def test_case(self):
print('test 01,没有前置方法')
def test_02(self):
print('有前置方法')
if __name__ == '__main__':
pytest.main(['-vs'])
执行结果
============================= test session starts =============================
platform win32 -- Python 3.8.8, pytest-7.1.1, pluggy-1.0.0 -- D:\测码课堂\python基础\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\测码课堂\python基础\pytest_fixture\test_conftest
collecting ... collected 2 items
test_case01.py::TestFixture::test_case
conftest里的fix1
前置的方法是,实现部分以及全部用例的前置
test 01,没有前置方法
PASSED用例后置的方法,实现部分以及全部用例的后置
test_case01.py::TestFixture::test_02
conftest里的fix1
前置的方法是,实现部分以及全部用例的前置
有前置方法
PASSED用例后置的方法,实现部分以及全部用例的后置
============================== 2 passed in 0.03s ==============================
scope=‘class’
fixture为class级别时,如果一个class里面有多个用例,都调用了fixture,那么此fixture只在该class里面的所有用例开始执行前执行一次
# coding:utf-8
import pytest
@pytest.fixture(scope='class', autouse=True)
def my_fixture():
print('\n获取用户名,scope为class级别只运行一次')
a = 'zz'
yield a
print('\nfinish')
class TestCase:
def test_01(self, my_fixture):
"""用例传入fixture"""
print('测试账号:%s' % my_fixture)
assert my_fixture == 'zz'
def test_02(self, my_fixture):
"""用例传入fixture"""
print('测试账号:%s' % my_fixture)
assert my_fixture == 'zz'
if __name__ == '__main__':
pytest.main(['-vs', './test_class_fixture.py'])
测试结果
test_class_fixture.py::TestCase::test_01
获取用户名,scope为class级别只运行一次
测试账号:zz
PASSED
test_class_fixture.py::TestCase::test_02 测试账号:zz
PASSED
finish
作用域验证
# coding:utf-8
import pytest
@pytest.fixture(scope='function', autouse=True)
def my_fixture():
print('前置的方法是,实现部分以及全部用例的前置')
yield
print('用例后置的方法,实现部分以及全部用例的后置')
class TestCase01:
def test_01(self):
"""用例传入fixture"""
print('test01')
class TestCase02:
def test_01(self):
"""用例传入fixture"""
print('test02')
if __name__ == '__main__':
pytest.main(['-vs', './test_class_fixture02.py'])
测试结果
collecting ... collected 2 items
test_class_fixture02.py::TestCase01::test_01 前置的方法是,实现部分以及全部用例的前置
test01
PASSED用例后置的方法,实现部分以及全部用例的后置
test_class_fixture02.py::TestCase02::test_01 前置的方法是,实现部分以及全部用例的前置
test02
PASSED用例后置的方法,实现部分以及全部用例的后置
============================== 2 passed in 0.06s ==============================
params
# coding:utf-8
import pytest
@pytest.fixture(scope='function', params=['apple', 'pear', 'orange'])
def data_get(request):
return request.param
class TestFixture:
def test_01(self):
print('banana')
def test_02(self, data_get):
print(f'fruit is {
data_get}')
if __name__ == '__main__':
pytest.main(['-vs', './test_params.py'])
测试结果
test_params.py::TestFixture::test_01 banana
PASSED
test_params.py::TestFixture::test_02[apple] fruit is apple
PASSED
test_params.py::TestFixture::test_02[pear] fruit is pear
PASSED
test_params.py::TestFixture::test_02[orange] fruit is orange
PASSED
============================== 4 passed in 0.05s ==============================
yield作用:–笔记待补充完整
yiled:return,可以当作return来使用,
学习yeild前提:理解什么是生成器,生成器必会知识点:什么是可迭代对象
- yield函数本身是一个生成器,只有当用的时候才会去调用,优点:不会占用内存
- 生成器本身有一个next关键字工作原理就是通过调用next()方法,直到不活到异常
- yield类似于一个return的关键字,迭代一次遇到yield就返回yield后面的值,下一次迭代时从上一次遇到的yield后面的上一行代码开始即:yield是return的一个返回值,并且记住这个返回值的位置,下次调用yield时,就从这个位置后面开始:参考代码如下
生成器
def test_02(n):
generator = (i * i for i in range(n))
for i in generator:
yield i
if __name__ == '__main__':
print('-------------------------------')
num = test_02(4)
print(next(num))
print(next(num))
print(next(num))
print(next(num))
-------------------------------
0
1
4
9
通过conftest.py和@pytest.fixture()结合实现全局前置应用(比如:项目的全局登录,模块的全局处理)
- conftest.py文件是单独存放的一个夹具配置文件,名称是不能更改
- 可以在不同的py文件中使用同一个fixture函数
- 原则上conftest.py需要和运行的用例放在同一层,并且不需要做任何的import导入操作

# coding:utf-8
import pytest
# conftest.py文件代码
@pytest.fixture
def fix1():
print('\nconftest里的fix1')
# test_01.py文件代码
# coding:utf-8
import pytest
def test_case(fix1):
print('test 01')
if __name__ == '__main__':
pytest.main(['-vs'])
D:\测码课堂\python基础\venv\Scripts\python.exe D:/测码课堂/python基础/pytest_fixture/test_conftest/test_case01.py
============================= test session starts =============================
platform win32 -- Python 3.8.8, pytest-7.1.1, pluggy-1.0.0 -- D:\测码课堂\python基础\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\测码课堂\python基础\pytest_fixture\test_conftest
collecting ... collected 1 item
test_case01.py::test_case
conftest里的fix1
test 01
PASSED
============================== 1 passed in 0.02s ==============================
Process finished with exit code 0
边栏推荐
- Ue5 - ai Pursuit (Blueprint, Behavior tree)
- Tee command usage example
- Judging right triangle in C language
- 2837xd code generation - stateflow (2)
- 2837xd code generation module learning (1) -- GPIO module
- UE5——AI追逐(蓝图、行为树)
- 【虚幻4】从U3D到UE4的转型之路
- Introduction and prevention of penetration test
- [leetcode] sword finger offer 53 - I. find the number I in the sorted array
- Eslint reports an error
猜你喜欢

Feature (5): how to organize information
![[unreal] animation notes of the scene](/img/97/dafde0377b7c4337e1775db64ba6a4.png)
[unreal] animation notes of the scene

Leetcode -- the nearest common ancestor of 236 binary tree

2837xd代码生成模块学习(4)——idle_task、Simulink Coder

Blender多镜头(多机位)切换

The primary market project galaxy will conduct public offering on coinlist on February 17

2837xd code generation - stateflow (2)
![[illusory] weapon slot: pick up weapons](/img/a7/1e395fc9cdfd0359e7ae4d2313290d.png)
[illusory] weapon slot: pick up weapons

【UE5】AI随机漫游蓝图两种实现方法(角色蓝图、行为树)

2837xd code generation module learning (1) -- GPIO module
随机推荐
虚幻——动画蓝图、状态机制作人物走跑跳动作
2837xd code generation - Supplement (1)
[unreal] animation notes of the scene
2837xd code generation - Supplement (2)
虛幻AI藍圖基礎筆記(萬字整理)
MySQL transaction
Matlab generates DSP program -- official routine learning (6)
ICLR 2022: how does AI recognize "things I haven't seen"?
阿里云Prometheus监控服务
职业规划和发展
高考那些事
Remember the use of add method once
Matlab生成dsp程序——官方例程学习(6)
2837xd code generation module learning (1) -- GPIO module
Database -- acid of transaction -- introduction / explanation
Notes de base sur les plans illusoires d'IA (triés en 10 000 mots)
Junit5 supports suite methods
2837xd code generation - Supplement (3)
C language: making barrels
【Lua】常见知识点汇总(包含常见面试考点)