pytest--fixture的作用范围(scope)

fixture作用范围

fixture里面有个scope参数可以控制fixture的作用范围:session > module > class > function

fixture(scope="function", params=None, autouse=False, ids=None, name=None):
    """使用装饰器标记fixture的功能
     可以使用此装饰器(带或不带参数)来定义fixture功能。 fixture功能的名称可以在以后使用
     引用它会在运行测试之前调用它:test模块或类可以使用pytest.mark.usefixtures(fixturename标记。
     测试功能可以直接使用fixture名称作为输入参数,在这种情况下,夹具实例从fixture返回功能将被注入。
 
    :arg scope: scope 有四个级别参数 "function" (默认), "class", "module" or "session".
 
    :arg params: 一个可选的参数列表,它将导致多个参数调用fixture功能和所有测试使用它
 
    :arg autouse:  如果为True,则为所有测试激活fixture func 可以看到它。 如果为False(默认值)则显式需要参考来激活fixture
 
    :arg ids: 每个字符串id的列表,每个字符串对应于params 这样他们就是测试ID的一部分。 如果没有提供ID它们将从params自动生成
 
    :arg name:   fixture的名称。 这默认为装饰函数的名称。 如果fixture在定义它的同一模块中使用,夹具的功能名称将被请求夹具的功能arg遮蔽; 解决这个问题的一种方法是将装饰函数命名
                       “fixture_ <fixturename>”然后使用”@ pytest.fixture(name ='<fixturename>')“”。
  • function 每一个函数或方法都会调用
  • class 每一个类调用一次,一个类可以有多个方法
  • module每一个.py文件调用一次,该文件内又有多个function和class
  • session 是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
scope="function"

@pytest.fixture()如果不写参数,默认就是scope="function",它的作用范围是每个测试用例之前运行一次,销毁代码在测试用例运行之后运行

import pytest

@pytest.fixture()
def user():
    a = "admin"
    print("获取用户名")
    return a
@pytest.fixture(scope="function")
def pwd():
    print("获取用户密码")
    p = "888888"
    return p

def test_t1(user, pwd):
    print(f"用户名:{user},密码:{pwd}")
    assert pwd != None

def test_t2(pwd):
    print(f"用户密码:{pwd}")

if __name__ == "__main__":
    pytest.main(["-s", " test_001.py"])

运行结果:

============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\study\xyautotest
plugins: allure-pytest-2.8.19, Faker-4.18.0, hypothesis-6.14.6, assume-2.4.3, forked-1.3.0, html-2.1.1, metadata-1.10.0, ordering-0.6, rerunfailures-9.1.1, xdist-2.3.0, tep-0.8.9collected 2 items

test_001.py 获取用户名
获取用户密码
.用户名:admin,密码:888888
获取用户密码
.用户密码:888888
                                                           [100%]

============================== 2 passed in 0.11s ==============================

用例放到类里面也一样

import pytest

@pytest.fixture()
def user():
    a = "admin"
    print("获取用户名")
    return a
@pytest.fixture(scope="function")
def pwd():
    print("获取用户密码")
    p = "888888"
    return p

class Test_T:
    def test_t1(self, user, pwd):
        print("用户名:{},密码:{}".format(user, pwd))
        assert pwd != None

    def test_t2(self, pwd):
        print("用户密码:%s" % pwd)
        assert pwd == "888888"
if __name__ == "__main__":
    pytest.main(["-s", " test_001.py"])

运行结果:

============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\study\xyautotest
plugins: allure-pytest-2.8.19, Faker-4.18.0, hypothesis-6.14.6, assume-2.4.3, forked-1.3.0, html-2.1.1, metadata-1.10.0, ordering-0.6, rerunfailures-9.1.1, xdist-2.3.0, tep-0.8.9collected 2 items

test_001.py                                                            [100%]

============================== 2 passed in 0.11s ==============================

Process finished with exit code 0
获取用户名
获取用户密码
.用户名:admin,密码:888888
获取用户密码
.用户密码:888888
scope="class"

fixture为class级别的时候,如果一个class里面有多个用例,都调用了此fixture,那么此fixture只在该class里所有用例开始前执行一次。

import pytest


@pytest.fixture()
def user():
    a = "admin"
    print("获取用户名")
    return a


@pytest.fixture(scope="class")
def pwd():
    print("class获取用户密码")
    p = "888888"
    return p


def test_f1(user, pwd):
    print("test_f1,{},{}\n".format(user, pwd))


class Test_T:
    def test_t1(self, user, pwd):
        print("test_t1,用户名:{},密码:{}".format(user, pwd))
        assert pwd != None

    def test_t2(self, pwd):
        print("test_t2,用户密码:%s" % pwd)
        assert pwd == "888888"

if __name__ == "__main__":
    pytest.main(["-s", " test_001.py"])

运行结果:

发现scope=“class”的,在类外面也可以调用

============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\study\xyautotest
plugins: allure-pytest-2.8.19, Faker-4.18.0, hypothesis-6.14.6, assume-2.4.3, forked-1.3.0, html-2.1.1, metadata-1.10.0, ordering-0.6, rerunfailures-9.1.1, xdist-2.3.0, tep-0.8.9collected 3 items

test_001.py class获取用户密码
获取用户名
.test_f1,admin,888888

                                                          [100%]

============================== 3 passed in 0.13s ==============================

Process finished with exit code 0
class获取用户密码
获取用户名
.test_t1,用户名:admin,密码:888888
.test_t2,用户密码:888888
scope="module"

fixture为module级别时,在当前.py脚本里所有用例在开启前只执行一次

import pytest

@pytest.fixture(scope="module")
def one():
    a = "admin"
    print("获取用户名")
    return a

def test_f1(one):
    print("test_f1,{}\n".format(one))


class Test_T:
    def test_t1(self, one):
        print("test_t1,名:{}".format(one))
        assert one != None

    def test_t2(self, one):
        print("test_t2,名:%s" % one)
        assert one

if __name__ == "__main__":
    pytest.main(["-s", " test_001.py"])

运行结果:

============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\study\xyautotest
plugins: allure-pytest-2.8.19, Faker-4.18.0, hypothesis-6.14.6, assume-2.4.3, forked-1.3.0, html-2.1.1, metadata-1.10.0, ordering-0.6, rerunfailures-9.1.1, xdist-2.3.0, tep-0.8.9collected 3 items

test_001.py 获取用户名
.test_f1,admin

                                                          [100%]

============================== 3 passed in 0.11s ==============================

Process finished with exit code 0
.test_t1,名:admin
.test_t2,名:admin

scope="session"

fixture为session级别时可以跨.py模块调用的,也就是当我们有多个.py文件的用例时候,如果多个用例只需调用一次fixture,那就可以设置scope="session",并且写到conftest.py文件里。

conftest.py文件名称是固定的,pytest会自动识别该文件。放到工程的根目录下,就可以全局调用了,如果放到某个package包下,那就只在该package内有效。

#conftest.py
import pytest
 
@pytest.fixture(scope="session")
def the():
    print("\n 获取名字,session级别的scope")
    a="huazai"
    return a
#test_f1.py
import pytest
def test_1(the):
     print("\n test_1,名字:{}".format(the))
class Test_C:
    def test_2(self,the):
        print("test_2,名字:%s"%the)
if __name__=="__main__":
    pytest.main("test_f1.py")
#test_f2.py
import pytest
def test_t1(the):
     print("\n test_t1,名字:{}".format(the))
class Test_C:
    def test_t2(self,the):
        print("test_t2,名字:%s"%the)
if __name__=="__main__":
    pytest.main(["test_f2.py"]) 

 如果想同时运行test_f1.py, test_f2.py,在cmd执行

pytest -s test_f1.py test_f2.py

运行结果:

D:\study\xyautotest>pytest -s test_f2.py test_f1.py
======================================================== test session starts ================================================
platform win32 -- Python 3.8.2, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: D:\study\xyautotest
plugins: allure-pytest-2.8.19, Faker-4.18.0, hypothesis-6.14.6, assume-2.4.3, forked-1.3.0, html-2.1.1, metadata-1.10.0, ordering-0.6, rerunfailur
es-9.1.1, xdist-2.3.0, tep-0.8.9
collected 4 items                                                                                                                                

test_f2.py
 获取名字,session级别的scope

 test_t1,名字:huazai
.test_t2,名字:huazai
.
test_f1.py
 test_1,名字:huazai
.test_2,名字:huazai
.
======================================================== 4 passed in 0.11s ========================================================

posted @ 2021-09-13 14:46  qiupeng  阅读(134)  评论(0)    收藏  举报