网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
了解详情》docs.qq.com/doc/DSlVlZExWQ0FRSE9H
提醒一下这俩都是设置全部用例的,也就是说你设置以后每一条用例都是要执行的
def setup()每一次执行用例前都会先执行一下这个方法中的代码
def teardown()每一次执行用例之后都会执行一下这个方法中的代码
def setup_class()每个类执行前的初始化工作
def teardown_class()每个类执行后的扫尾工作
代码示例:
import pytest
class TestLogin:
def setup(self):
print("这是前置")
def teardown(self):
print("这是后置")
def test_08(self):
print("你好08")
def test_01(self):
print("你好01")
def test_05(self):
print("你好05")
def test_03(self):
print("你好03")
运行结果:
可以看到,每一条用例执行的时候都打印了前置和后置,下面看看类的前后置
代码示例:
import pytest
class TestLogin:
def setup_class(self):
print("这是一个前置")
def teardowm_class(self):
print("这是后置")
def test_08(self):
print("你好08")
def test_01(self):
print("你好01")
def test_05(self):
print("你好05")
def test_03(self):
print("你好03")
运行结果:
可以看到这里的类的前后置就只会在这个类运行前后置执行一次,而中间的用例并不会逐条执行了
前面几篇随笔基本上已经了解了pytest 命令使用,收集用例,finxture使用及作用范围,今天简单介绍一下conftest.py文件的作用和实际项目中如是使用此文件!
实例场景
首先们思考这样一个问题:如果我们在编写测试用的时候,每一个测试文件里面的用例都需要先登录后才能完成后面的操作,那么们该如何实现呢?这就需要我们掌握conftest.py文件的使用了。
实例代码
创建如下一个目录
ConftestFile
|conftest.py
|test_file_01.py
|test_file_02.py
|__init__.py
# conftest.py
import pytest
@pytest.fixture()
def login():
print('\n---------------conftest文件login方法开始执行----------------------------')
print('login in conftest.py')
print('----------------conftest.py文件login方法执行结束---------------------------')
# test_file_01.py
def test_01(login):
print('\n------------------用例文件1测试用例1开始执行------------------')
print('login after : in test_file_01->case test_01')
print('-------------------用例文件1测试用例1执行结束------------------------')
# test_file_02.py
def test_02(login):
print('\n------------------用例文件2测试用例2开始执行------------------')
print('login after : in test_file_01->case test_01')
print('-------------------用例文件2测试用例2执行结束------------------------')
我们先来运行一下这个实例代码看看输出结果
1.在pycharm可以右键目录运行
2.可以在cmd目录中输入 pytest -vs 来运行
test_file_01.py
---------------conftest文件login方法开始执行----------------------------
login in conftest.py
----------------conftest.py文件login方法执行结束---------------------------
.
------------------用例文件1测试用例1开始执行------------------
login after : in test_file_01->case test_01
-------------------用例文件1测试用例1执行结束------------------------
[ 50%]
test_file_02.py
---------------conftest文件login方法开始执行----------------------------
login in conftest.py



**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上软件测试知识点,真正体系化!**
**开源项目:docs.qq.com/doc/DSlVlZExWQ0FRSE9H**