fixture翻译过来就是测试夹具,主要来配置测试资源,fixture是通过装饰器标注的。
一、fixture基础入门
函数在用装饰器@pytest.fixture()标记之后,该函数名就可以当作参数传入到测试函数里面,看下面的代码,
函数my_fixture用装饰器@pytest.fixture(),就可以将函数名当作参数传入到test_bali函数,执行测试用例可以看到执行my_fixture
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture()
def my_fixture():
print("this is a fixture")
def test_param():
a = 1
b = 1
assert a == b
def test_baili(my_fixture):
assert 1 == 1
二、fixture常用参数说明
@pytest.fixture(scope=scope,params=params,autouse=false,ids=ids,name=name)
pycharm中,在@pytest.fixture()的括号里按
- scope:分别有5个取值function、class、module、package、session,默认值是function,代表fixture能分享的范围
- params:可接受列表、元祖等参数,来实现参数化,通过request.param来取里面的值
- ids:测试用例的id列表
- name:给fixture取个别名,取了别名后,只能通过别名使用
- autouse:为True时函数自动使用,默认值时False
1.scope参数使用示例
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture(scope="class", name="myFixture")
def my_fixture():
print("this a fixture")
@pytest.mark.usefixtures("myFixture") #另外调用fixture的方式
class TestFixture:
def test_fixture(self):
assert 1 == 1
#@pytest.mark.usefixtures("myFixture") 类级别,在类中只执行一次,无论放在哪里只执行一次,后面放再多也不执行
def test_fixture1(self):
assert 2 == 2
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture(scope="function", name="myFixture")
def my_fixture():
print("this a fixture")
@pytest.mark.usefixtures("myFixture")
class TestFixture:
def test_fixture(self):
assert 1 == 1
def test_fixture1(self):
assert 2 == 2
2.autouse参数使用示例
autouse默认是False。设置为True后,默认第一次使用fixture后面也默认使用。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture(scope="function", name="myFixture", autouse=True)
def my_fixture():
print("this a fixture")
class TestFixture:
@pytest.mark.usefixtures("myFixture")
def test_fixture(self):
assert 1 == 1
def test_fixture1(self):
assert 2 == 2
3.params参数使用示例
params参数主要用于参数化,params主要接受可迭代的对象,比如列表,例子如下
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture(scope="function", params=["诸葛亮", "妲己", "孙尚香"])
def my_fixture(request):
print("this a fixture")
return request.param
class TestFixture:
def test_fixture(self, my_fixture):
print(str(my_fixture))
assert 1 == 1
def test_fixture1(self):
assert 2 == 2
三、@pytest.mark.parametrize参数化
除了上述通过fixture能够实现参数化,
我们最常用的是@pytest.mark.parametrize来实现参数化
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture(scope="function", params=["诸葛亮", "妲己", "孙尚香"])
def my_fixture(request):
print("this a fixture")
return request.param
class TestFixture:
def test_fixture(self, my_fixture):
print(str(my_fixture))
assert 1 == 1
@pytest.mark.parametrize("hero", ["程咬金", "老夫子", "夏洛特"])
def test_fixture1(self, hero):
print(hero)
assert 2 == 2
#@pytest.mark.parametrize第一个参数是字符串作为用例的变量名,后面是可
# 迭代的对象,如果是多个参数则通过逗号隔开“name1,name2”,后面的每一项也需要对应,比如
# (val1,val2)
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END