当前位置:网站首页>Pytest framework implements pre post
Pytest framework implements pre post
2022-07-02 10:22:00 【Lost ~ know to return】
pytest Pre post processing
setup/teardown,setup_class/teardown_class
setup/teardown and setup_class/teardown_class
import pytest
import time
class TestLogin:
age = 17
def setup_class(self):
print(" Initialization before each class execution : such as : Create a log object , Create database objects , Create an interface object ")
# Before each test method
def setup(self):
print("\n Code initialized before executing the test case , Open the browser , Load web page ")
@pytest.mark.smoke
def test_01_login(self):
print(" test 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=' Under age ')
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 The outstanding code after executing the test case : Close the browser ")
def teardown_class(self):
print(" The unfinished work after the execution of each class : such as : Destroyed log objects , Destroy database objects , Create the request object of the interface ")
if __name__ == "__main__":
pytest.main()
pytest.fixture() Decorator to achieve part Pre post of use case
@pytest.fixture(scope=‘function’, params=‘’, autouse=‘’, name=‘’)
- scope It means being @pytest.fixture Scope of marking method . The default is function,class,model,package,session
- params: A parameterized (list,tuple, Dictionary list [{},{},{}], Dictionary tuples ({},{},{}))
- autouse: Automatic execution , The default is false
- ids: When using params, Set a variable name for each value , It doesn't make much sense
- name: To be @pytest.fixture The marked method takes an alias
scope=‘function’
Manually call pre post methods , If you want those methods to execute before and after, let those methods execute
# coding:utf-8
import pytest
@pytest.fixture(scope='function')
def my_fixture():
print(' The method of preposition is , Realize the front of some and all use cases ')
yield
print(' Post use case method , Realize the postposition of some and all use cases ')
class TestFixture:
def test_case(self, fix1): # Be careful fix1 by conftest The method in
print('test 01, No pre method ')
def test_02(self, my_fixture):
print(' There are pre methods ')
if __name__ == '__main__':
pytest.main(['-vs'])

Automatically Call pre post method , Can automatically execute , But we can't control which methods are executed and which are not , Any method that hits within the scope must be executed fixture
# coding:utf-8
import pytest
@pytest.fixture(scope='function', autouse=True)
def my_fixture():
print(' The method of preposition is , Realize the front of some and all use cases ')
yield
print(' Post use case method , Realize the postposition of some and all use cases ')
class TestFixture:
def test_case(self):
print('test 01, No pre method ')
def test_02(self):
print(' There are pre methods ')
if __name__ == '__main__':
pytest.main(['-vs'])
Execution results
============================= test session starts =============================
platform win32 -- Python 3.8.8, pytest-7.1.1, pluggy-1.0.0 -- D:\ Code measurement class \python Basics \venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\ Code measurement class \python Basics \pytest_fixture\test_conftest
collecting ... collected 2 items
test_case01.py::TestFixture::test_case
conftest Inside fix1
The method of preposition is , Realize the front of some and all use cases
test 01, No pre method
PASSED Post use case method , Realize the postposition of some and all use cases
test_case01.py::TestFixture::test_02
conftest Inside fix1
The method of preposition is , Realize the front of some and all use cases
There are pre methods
PASSED Post use case method , Realize the postposition of some and all use cases
============================== 2 passed in 0.03s ==============================
scope=‘class’
fixture by class When level , If one class There are multiple use cases in it , They all called. fixture, Then this fixture Only in this class All the use cases inside are executed once before execution
# coding:utf-8
import pytest
@pytest.fixture(scope='class', autouse=True)
def my_fixture():
print('\n Get username ,scope by class Level runs only once ')
a = 'zz'
yield a
print('\nfinish')
class TestCase:
def test_01(self, my_fixture):
""" Case incoming fixture"""
print(' Test account number :%s' % my_fixture)
assert my_fixture == 'zz'
def test_02(self, my_fixture):
""" Case incoming fixture"""
print(' Test account number :%s' % my_fixture)
assert my_fixture == 'zz'
if __name__ == '__main__':
pytest.main(['-vs', './test_class_fixture.py'])
test result
test_class_fixture.py::TestCase::test_01
Get username ,scope by class Level runs only once
Test account number :zz
PASSED
test_class_fixture.py::TestCase::test_02 Test account number :zz
PASSED
finish
Scope validation
# coding:utf-8
import pytest
@pytest.fixture(scope='function', autouse=True)
def my_fixture():
print(' The method of preposition is , Realize the front of some and all use cases ')
yield
print(' Post use case method , Realize the postposition of some and all use cases ')
class TestCase01:
def test_01(self):
""" Case incoming fixture"""
print('test01')
class TestCase02:
def test_01(self):
""" Case incoming fixture"""
print('test02')
if __name__ == '__main__':
pytest.main(['-vs', './test_class_fixture02.py'])
test result
collecting ... collected 2 items
test_class_fixture02.py::TestCase01::test_01 The method of preposition is , Realize the front of some and all use cases
test01
PASSED Post use case method , Realize the postposition of some and all use cases
test_class_fixture02.py::TestCase02::test_01 The method of preposition is , Realize the front of some and all use cases
test02
PASSED Post use case method , Realize the postposition of some and all use cases
============================== 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 result
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 effect :– Notes to be completed
yiled:return, Can be viewed as return To use ,
Study yeild Premise : Understand what a generator is , Generator must know something : What is an iterative object
- yield The function itself is a generator , Only when it is used, it will be called , advantage : No memory consumption
- The generator itself has a next Keywords work by calling next() Method , Until you don't live abnormally
- yield Similar to a return Key words of , Iterate and meet yield Just go back to yield Value after , The next iteration starts from the last one yield The next line of code starts with :yield yes return A return value of , And remember the location of this return value , Next call yield when , Just start from the back of this position : The reference codes are as follows
generator
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
adopt conftest.py and @pytest.fixture() Combined with the implementation of global front-end applications ( such as : Global login of the project , Global processing of modules )
- conftest.py The file is a fixture configuration file stored separately , The name cannot be changed
- Can be in different py Use the same in the file fixture function
- In principle, conftest.py The required and running use cases are placed on the same layer , And you don't need to do anything import Import operation

# coding:utf-8
import pytest
# conftest.py File code
@pytest.fixture
def fix1():
print('\nconftest Inside fix1')
# test_01.py File code
# coding:utf-8
import pytest
def test_case(fix1):
print('test 01')
if __name__ == '__main__':
pytest.main(['-vs'])
D:\ Code measurement class \python Basics \venv\Scripts\python.exe D:/ Code measurement class /python Basics /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:\ Code measurement class \python Basics \venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\ Code measurement class \python Basics \pytest_fixture\test_conftest
collecting ... collected 1 item
test_case01.py::test_case
conftest Inside fix1
test 01
PASSED
============================== 1 passed in 0.02s ==============================
Process finished with exit code 0
边栏推荐
- Blender stone carving
- Blender volume fog
- 网络通信学习
- [ue5] blueprint making simple mine tutorial
- 【虚幻】过场动画笔记
- Junit5 支持suite的方法
- How to handle error logic gracefully
- 【Unity3D】嵌套使用Layout Group制作拥有动态子物体高度的Scroll View
- 【leetcode】33. Search rotation sort array
- Notes de base sur les plans illusoires d'IA (triés en 10 000 mots)
猜你喜欢
随机推荐
Spatial interpretation | comprehensive analysis of spatial structure of primary liver cancer
How to handle error logic gracefully
Blender多镜头(多机位)切换
MySQL index
虚幻——动画蓝图、状态机制作人物走跑跳动作
VLAN experiment
Project practice, redis cluster technology learning (VII)
职业规划和发展
go语言入门
UE illusory engine programmed plant generator setup -- how to quickly generate large forests
【虚幻4】UMG组件的简介与使用(更新中...)
XA Transaction SQL Statements
This monitoring system makes workers tremble: turnover intention and fishing can be monitored. After the dispute, the product page has 404
Junit4运行mvn test 测试套件升级方案
How to achieve the top progress bar effect in background management projects
C language: making barrels
Project practice, redis cluster technology learning (VIII)
How to judge the quality of primary market projects when the market is depressed?
Delivery mode design of Spartacus UI of SAP e-commerce cloud
Ue5 - ai Pursuit (Blueprint, Behavior tree)








