Pytest

1. 概述

Pytest的fixture功能灵活好用,支持参数设置,便于进行多用例测试,简单便捷,颇有pythonic。
如果要深入学习pytest,必学fixture。

fixture函数的作用:

  • 完成setup和teardown操作,处理数据库、文件等资源的打开和关闭
  • 完成大部分测试用例需要完成的通用操作,例如login、设置config参数、环境变量等
  • 准备测试数据,将数据提前写入到数据库,或者通过params返回给test用例,等

2. 使用介绍

2.1. 简介

  • 把一个函数定义为Fixture很简单,只能在函数声明之前加上“@pytest.fixture”。其他函数要来调用这个Fixture,只用把它当做一个输入的参数即可
  • 多个fixture方法,可以互相调用,最好不要递归哈(没试过,有兴趣的童鞋可以试试)
  • 一个test函数可以包含多个fixture参数
  • fixture作用域:fixture可以修饰单个函数,单个或多个类的成员函数,单个类

2.2. 三种使用方式

方式1,将fixture函数,作为test函数的参数

import pytest

@pytest.fixture()
def before():
    print '
before each test'

def test_1(before):
    print 'test_1()'

def test_2(before):
    print 'test_2()'
    assert 0

方式2,@pytest.mark.usefixtures("before")

import pytest

@pytest.fixture()
def before():
    print('
before each test')

@pytest.mark.usefixtures("before")
def test_1():
    print('test_1()')

@pytest.mark.usefixtures("before")
def test_2():
    print('test_2()')

class Test1:
    @pytest.mark.usefixtures("before")
    def test_3(self):
        print('test_1()')

    @pytest.mark.usefixtures("before")
    def test_4(self):
        print('test_2()')

@pytest.mark.usefixtures("before")
class Test2:
    def test_5(self):
        print('test_1()')

    def test_6(self):
        print('test_2()')

方式3,用autos调用fixture,使用时需要谨慎

@pytest.fixture(scope="function", autouse=True)

import time
import pytest

@pytest.fixture(scope="module", autouse=True)
def mod_header(request):
    print('
-----------------')
    print('module      : %s' % request.module.__name__)
    print('-----------------')

@pytest.fixture(scope="function", autouse=True)
def func_header(request):
    print('
-----------------')
    print('function    : %s' % request.function.__name__)
    print('time        : %s' % time.asctime())
    print('-----------------')

def test_one():
    print('in test_one()')

def test_two():
    print('in test_two()')

  • fixture scope
  • function:每个test都运行,默认是function的scope
  • class:每个class的所有test只运行一次
  • module:每个module的所有test只运行一次
  • session:每个session只运行一次

2.3. fixture返回参数

import pytest

@pytest.fixture(params=[1, 2, 3])
def test_data(request):
    return request.param

def test_not_2(test_data):
    print('test_data: %s' % test_data)
    assert test_data != 2

3. 参考

  • pytest fixtures: explicit, modular, scalable
    https://docs.pytest.org/en/latest/fixture.html
原文地址:https://www.cnblogs.com/zhuochong/p/10620486.html