pytest框架[email protected]()

pytest的几大函数介绍:
@pytest.yield_fixture()
@pytest.mark.xfail()
@pytest.mark.skipif

(1)@pytest.fixture()【主要用两个参数:scope\autouse】

@pytest.fixture函数定义:
fixture修饰器来标记固定的工厂函数,在其他函数,模块,类或整个工程调用它时会被激活并优先执行,通常会被用于完成预置处理和重复操作

fixture(scope=‘function’,params=None,autouse=False,ids=None,name=None),源码解读:
scope默认fuction,有4个级别:function、class、module、package/session。
autouse默认关闭,fixture(autouse=True):默认在每个测试用例执行被装饰的函数。
params是个形参,可以传入多个参数
name用的少,暂不解读。

@pytest.fixture函数3大功能:
功能1:装饰函数_直接看代码中test_case_8的调用,被fixture标记的函数,函数名可以作为入参放进要执行的函数里面。当前函数会优先执行被标记的函数。跟类的继承相似。

# coding=utf-8
import pytest

@pytest.fixture()
def test_case_3():
    print('---3号用例完成---')

@pytest.fixture()
def test_case_4():
    print('---4号用例完成---')

@pytest.fixture()
def test_case_5():
    print('---5号用例完成---')

@pytest.fixture()
def test_case_6():
    print('---6号用例完成---')

@pytest.fixture()
def test_case_7():
    print('---7号用例完成---')

@pytest.fixture()
def test_case_8():
    print('---8号用例完成---')

# (1)这里按照【从下到上的顺序】,执行优先级是3、4、5
@pytest.mark.usefixtures('test_case_5')
@pytest.mark.usefixtures('test_case_4')
@pytest.mark.usefixtures('test_case_3')
class Testlogin001:

    # 被pytest.fixture()装饰的函数,函数名可以作为变量传递给测试用例,最终在执行测试用例之前执行这个装饰过的函数
    def test_case_1(self, test_case_8):
        print('---1号用例完成---')

    # (2)这里按照调用了前面的函数test_case_6,局部的调用,执行优先级是最高的。
    @pytest.mark.usefixtures('test_case_7')
    @pytest.mark.usefixtures('test_case_6')
    def test_case_2(self):
        print('---2号用例完成---')


if __name__ == "__main__":
    pytest.main(['-vs', 'test_1.py'])
    
test_1.py::Testlogin001::test_case_1 
启动浏览器
---进入要执行模块的的界面---
---3号用例完成---
---4号用例完成---
---5号用例完成---
---8号用例完成---
---1号用例完成---
PASSED
退出浏览器

功能2:自动执行标记的函数。【被fixture标记的函数,默认不自动执行】
这里一般放在conftest.py文件里面。测试用例执行前,每个测试用例会自动启动浏览器,自动进入当前模块的界面等。

import pytest
 @pytest.fixture(autouse=True) # 设置为默认运行
 def before():
     print("------->before")
     
 class Test_ABC:
     def setup(self):
         print("------->setup")
     def test_a(self):
         print("------->test_a")
         assert 1
         
 if __name__ == '__main__':
     pytest.main("-s  test_abc.py")

conftest.py文件

# coding=utf-8
import pytest
from selenium import webdriver
import logging

logger = logging.getLogger()

@pytest.fixture(autouse=True)
def start_module():
    print('---进入要执行模块的的界面---')

功能3:设置作用域

fixture函数是结合conftest.py的文件来使用的,使用场景:
@pytest.fixture() 被装饰的函数,在每个测试用例前执行一次【如果你想让每个用例都重启浏览器,进入要测试的界面,就用这个】
@pytest.fixture(scope=‘class’) 被装饰的函数,在测试用例的类前面被执行一次。
@pytest.fixture(scope=‘modlue’) 被装饰的函数,在py文件前执行一次。
@pytest.fixture(scope=‘package’) 被装饰的函数,在当前的目录下执行一次。

猜你喜欢

转载自blog.csdn.net/weixin_45451320/article/details/113278303