1. 程式人生 > 其它 >Pytest測試框架基礎-fixture詳解

Pytest測試框架基礎-fixture詳解

  fixture修飾的方法可以被其他函式引用,這樣就可以實現類似 setup,teardown的效果,但是fixture更加靈活,下面將詳細講解一下其用法。

  

  一、方式1:直接將fixture修飾的方法名稱當做引數傳入,如下程式碼:

  

import pytest
from selenium import webdriver

@pytest.fixture()
def open():
    driver = webdriver.Chrome()
    driver.maximize_window()
    print('啟動瀏覽器')
    return driver
    #或者yield driver

def test_case01(open):
    driver = open
    driver.get("https://www.baidu.com")
    print('第一個測試用例')

def test_case02(open):
    driver = open
    driver.get('https://www.cnblogs.com/longlongleg/')
    print('第二個測試用例')


def test_case03(open):
   open.get('https://www.google.com.hk/')
    print('第三個測試用例')

def test_case04():
   
    print('第四個測試用例')
if __name__ == '__main__': pytest.main(['-vs','test_case01.py'])

  open是由fixture修飾的一個方法,在其他的測試用例當中,將open做為引數引入。每一個測試用例都會執行一遍open的方法,沒有引用的如case04,則不會執行open函式內容。yield跟return類似,都可以返回引數,但是return後面如果還有內容不會執行,但是yield會執行其後的內容

  二、方式2:新增範圍進行引用@pytest.fixture(scope='class'),範圍有多種,如下

    function: 預設作用域,每個測試用例都執行一次

    class: 每個測試類只執行一次

    module: 每個模組只執行一次

    package:每個python包只執行一次

    session: 整個會話只執行一次,即整個專案執行時,只執行一次

    

    以class為例

import pytest

@pytest.fixture(scope='class')
def open():
    print('hello,world')


@pytest.mark.usefixtures('open')
class TestDemo:

    def test_case1(self):
        print('case 01')

    def test_case2(self):
        print('case 02')

    def test_case3(self):
        print('case 3')



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

    執行TestDemo裡面的測試用例之前,會執行一次open函式。也可以將open當做引數寫在每個testcase裡面。

    以module為例,將fixture修飾的函式寫在conftest中,被引用的引數會預設先去尋找conftest.py裡面的方法,程式碼如下所示

    conftest.py

from selenium import webdriver
import pytest

@pytest.fixture(scope='module')
def open():
    driver = webdriver.Chrome()
    driver.maximize_window()
   print('open function')
   return driver

    testcase.py

import pytest


class Testcase:

    def testcase01(self,open):
        open.get("https://www.baidu.com")
        print('Testcase03:case1')

    def testcase02(self,open):
        open.get("https://www.google.com.hk/")
        print('Testcase03:case2')

def testcase03(open):
    open.get('https://www.cnblogs.com/longlongleg/')
    print('Testcase03:case3')

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

  

  此時三個testcase都只會執行一次open,如果範圍為class,那麼會執行兩次open。因為最後一個測試用例不屬於class Testcase類裡面。

  module範圍輸出內容

  

  如果為class範圍,輸出內容