前言
之前一直有在和大家聊pytest的一些内容,今天呢想和大家分享pytest框架的精髓,话不多说,我们直接开始吧,还有喜欢的记得关注我哟。
介绍:
fixture区别于unnitest的传统单元测试(setup/teardown)有显著改进:
1.有独立的命名,并通过声明它们从测试函数、模块、类或整个项目中的使用来激活。
2.按模块化的方式实现,每个fixture都可以互相调用。
3.fixture的范围从简单的单元测试到复杂的功能测试,可以对fixture配置参数,或者跨函数function,类class,模块module或整个测试session范围。
谨记:当我们使用pytest框架写case的时候,一定要拿它的命令规范去case,这样框架才能识别到哪些case需要执行,哪些不需要执行。
用例设计原则
文件名以test_*.py文件和*_test.py
以test_开头的函数
以Test开头的类
以test_开头的方法
fixture可以当做参数传入
定义fixture跟定义普通函数差不多,唯一区别就是在函数上加个装饰器@pytest.fixture(),fixture命名不要以test开头,跟用例区分开。fixture是有返回值得,没有返回值默认为None。用例调用fixture的返回值,直接就是把fixture的函数名称当做变量名称。
ex:
import pytest
@pytest.fixture()
def test1():
a = 'leo'
return a
def test2(test1):
assert test1 == 'leo'
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
输出:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item
test_fixture.py . [100%]
========================== 1 passed in 0.02 seconds ===========================
Process finished with exit code 0
使用多个fixture
如果用例需要用到多个fixture的返回数据,fixture也可以返回一个元祖,list或字典,然后从里面取出对应数据。
ex:
import pytest
@pytest.fixture()
def test1():
a = 'leo'
b = '123456'
print('传出a,b')
return (a, b)
def test2(test1):
u = test1[0]
p = test1[1]
assert u == 'leo'
assert p == '123456'
print('元祖形式正确')
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
输出结果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item
test_fixture.py 传出a,b
.元祖形式正确
[100%]
========================== 1 passed in 0.02 seconds ===========================
Process finished with exit code 0
当然也可以分成多个fixture,然后在用例中传多个fixture参数
import pytest
@pytest.fixture()
def test1():
a = 'leo'
print('\n传出a')
return a
@pytest.fixture()
def test2():
b = '123456'
print('传出b')
return b
def test3(test1, test2):
u = test1
p = test2
assert u == 'leo'
assert p == '123456'
print('传入多个fixture参数正确')
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\exercise, inifile:collected 1 item
test_fixture.py
传出a
传出b
.传入多个fixture参数正确
fixture互相调用
import pytest
@pytest.fixture()
def test1():
a = 'leo'
print('\n传出a')
return a
def test2(test1):
assert test1 == 'leo'
print('fixture传参成功')
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
输出结果:
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects