1. 程式人生 > 其它 >pytest 中fixture引數化到底什麼時候使用?

pytest 中fixture引數化到底什麼時候使用?

pytest 中fixture引數化到底什麼時候使用?

背景

都知道我們可以把前置準備和後置處理放到fixture中,那麼fixture引數化是用來幹什麼的?

官方教程

# content of conftest.py
import pytest
import smtplib


@pytest.fixture(scope="module", params=["smtp.gmail.com", "mail.python.org"])
def smtp_connection(request):
    smtp_connection = smtplib.SMTP(request.param, 587, timeout=5)
    yield smtp_connection
    print("finalizing {}".format(smtp_connection))
    smtp_connection.close()

這裡引數化用來處理不同的郵箱地址,那麼一個用例就會執行兩次,我們日常自動化測試的時候怎麼用?

目前我能想到的就是一套用例在不同的測試環境執行,比如params=["test.com", "dev.com"],或者是在不同瀏覽器中執行同一個用例params=["ie", "chrome"]

程式碼實現

# content of conftest.py
import pytest


@pytest.fixture(params=['test', 'dev'])
def myfixture(request):
    print('\n')
    print('前置條件正在執行')
    env = request.param
    print(env)
    yield env
    print('後置條件正在執行')

自動化用例:

# content of test_1.py

def test_1(myfixture):

    print('正在執行自動化用例')
    env = myfixture
    print('執行中的env:%s' % env)

執行結果:一個用例執行兩遍,分別在不同的測試環境

============================= test session starts ==============================
collecting ... collected 2 items

test_.py::test_1[test] 

前置條件正在執行
test
PASSED                                            [ 50%]正在執行自動化用例
執行中的env:test
後置條件正在執行

test_.py::test_1[dev] 

前置條件正在執行
dev
PASSED                                             [100%]正在執行自動化用例
執行中的env:dev
後置條件正在執行


============================== 2 passed in 0.01s ===============================