Pytest - 進階功能fixture

1. 概述

Pytest的fixture功能靈活好用,支持參數設置,便於進行多用例測試,簡單便捷,很有pythonic。
若是要深刻學習pytest,必學fixture。html

fixture函數的做用:python

  • 完成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 '\nbefore 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('\nbefore 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('\n-----------------') print('module : %s' % request.module.__name__) print('-----------------') @pytest.fixture(scope="function", autouse=True) def func_header(request): print('\n-----------------') 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, scalablehttps://docs.pytest.org/en/latest/fixture.html
相關文章
相關標籤/搜索