pytest4-使用conftest.py实现多文件共享fixture

一个测试工程下是可以有多个conftest.py的文件,一般在工程根目录放一个conftest.py起到全局作用。
在不同的测试子目录也可以放conftest.py,作用范围只在该层级以及以下目录生效。

特别地:conftest.py不需要显示导入,pytest会自动读取该文件

session > module > class > function

@pytest.fixture(scope="session"):多个文件调用一次,可以跨.py,每个.py就是module

@pytest.fixture(scope="module"):module级别的fixture在当前.py模块里,只会在用例第一次调用前执行一次

@pytest.fixture(scope="class"):class级别的fixture,在每个类里,只会在第一次调用前执行一次

@pytest.fixture(scope="function"):function级别,每个函数都会调用(默认)

# conftest.py
import pytest


@pytest.fixture(scope="class")
def login():
    print("登录系统")

# test_fix.py
import pytest


class Test1:
    def test_s1(self,login):
        print("用例1:登录之后其它动作111")

    def test_s2(self):  # 不传login
        print("用例2:不需要登录,操作222")

    def test_s3(self, login):
        print("用例3:登录之后其它动作333")


class Test2:
    def test_s4(self, login):
        print("用例4:登录之后其它动作444")

    def test_s5(self):  # 不传login
        print("用例5:不需要登录,操作555")

    def test_s6(self, login):
        print("用例6:登录之后其它动作666")


输出结果:
testcases\test_fix.py 登录系统
用例1:登录之后其它动作111
.用例2:不需要登录,操作222
.用例3:登录之后其它动作333
.登录系统
用例4:登录之后其它动作444
.用例5:不需要登录,操作555
.用例6:登录之后其它动作666

猜你喜欢

转载自www.cnblogs.com/wang-mengmeng/p/11710000.html