pytest_fixture

fixture有什么用

  在pytest框架中setup、teardown 可以让我们实现 每一个方法级别,类级别,模块级别的前后置操作,但没法自定义其中的某一个方法去实现前后置,

而fixture提供了这样的能力,让我们可以自定义某一个测试用例的前后置操作。

 

fixture 基本用法

参数列表及其定义:

  • scope:可以理解成fixture的作用域,默认:function,还有class、module、package、session四个【常用】
  • autouse:默认:False,需要用例手动调用该fixture;如果是True,所有作用域内的测试用例都会自动调用该fixture
  • name:默认:装饰器的名称,同一模块的fixture相互调用建议写个不同的name
  • ids:当使用params做参数化的时候,给每一个参数设置变量名
  • params:参数 化

 

autose:控制是否手动调用fixture,默认autose = False

手动调用的几种方式:

1、作为参数 传递给测试方法

import pytest


'''scope='function'
'''
@pytest.fixture
def myfixture():
    print('\n前置方法')


class Test_1:

    def test_1(self,myfixture):
        print('\ntest_1')

    def test_2(self):
        print('\ntest_2')

def test_other(myfixture):
    print('\nother function')


if __name__ == '__main__':
    pytest.main(['-vs','./test_autouse.py'])

2、通过装饰器 

@pytest.mark.usefixtures(fixturename)
import pytest

@pytest.fixture
def myfixture1():
    print('scope=function-------------')

@pytest.fixture(scope='class')
def myfixture2():
    print('scope=class--------------')


@pytest.mark.usefixtures('myfixture2')
class Test_1:

    def test_1(self,):
        print('test1------------')

    @pytest.mark.usefixtures('myfixture1')
    def test_2(self):
        print('test2------------')

    def test_3(self):
        print('test3------------')


@pytest.mark.usefixtures('myfixture1')
def test_other():
    print('other ----------------')

if __name__ == '__main__':
    pytest.main(['-vs','./test_autouse2.py'])

 

自动调用

autose = False

import pytest


@pytest.fixture(scope='class', autouse=True)
def login():
    print('登录系统')

# @pytest.fixture(autouse=True)
# def login2():
#     print('登录系统2')

def test_01():
    print('测试用例一')

class TestCase1:
    def test_03(self):
        print('测试用例三')

    def test04(self):
        print('测试用例四')

class TestCase2:
    def test_05(self):
        print('测试用例五')

    def test06(self):
        print('测试用例六')


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

socpe 标记方法的作用域

function:方法/函数级别,模块中所有函数/方法执行前都会执行该方法

class:类级别,作用于模块中的所有类,在每个类中都会执行一次。备注:如果模块中存在其他单独的函数,函数执行前也会执行该方法

module:模块级别的,作用于模块,整个模块中运行前会执行一次

package:

posted @ 2021-12-15 22:57  昆虫白  阅读(61)  评论(0)    收藏  举报