1. 程式人生 > 其它 >Python測試框架pytest(05)fixture - error和failed、fixture例項化、多個fixture

Python測試框架pytest(05)fixture - error和failed、fixture例項化、多個fixture

1、error和failed區別

1、在測試用例裡面斷言失敗,結果為failed。

建立test_fixture_failed.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import pytest

@pytest.fixture()
def user():
    print("使用者名稱")
    name = "AllTests軟體測試"
    return name

def test_case(user):
    assert user == "軟體測試
" # 測試用例失敗結果為failed if __name__ == "__main__": pytest.main(["-s", "test_fixture_failed.py"])

執行結果:

測試用例失敗結果為failed。

2、在fixture裡面斷言失敗,結果為error。

建立test_fixture_error.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import pytest

@pytest.fixture()
def user():
    
print("使用者名稱") name = "AllTests軟體測試" assert name == "軟體測試" # fixture失敗結果為error return name def test_case(user): assert user == "AllTests軟體測試" if __name__ == "__main__": pytest.main(["-s", "test_fixture_error.py"])

執行結果:

fixture失敗結果為error。

2、fixture的例項化順序

  • fixture 的 scope 例項化優先順序:session > package > module > class > function。即較高 scope 範圍的 fixture(session)在較低 scope 範圍的 fixture( function 、 class )之前例項化。

  • 具有相同作用域的 fixture 遵循測試函式中宣告的順序,並遵循 fixture 之間的依賴關係。在 fixture_A 裡面依賴的 fixture_B 優先例項化,然後到 fixture_A 例項化。

  • 自動使用(autouse=True)的 fixture 將在顯式使用(傳參或裝飾器)的 fixture 之前例項化。

1、建立test_fixture2.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""
import pytest

order = []

@pytest.fixture(scope="session")
def s1():
    order.append("s1")

@pytest.fixture(scope="package")
def p1():
    order.append("p1")

@pytest.fixture(scope="module")
def m1():
    order.append("m1")

@pytest.fixture(scope="class")
def c1():
    order.append("c1")

@pytest.fixture(scope="function")
def f0():
    order.append("f0")

@pytest.fixture
def f1(f3, a1):
    # 先例項化f3, 再例項化a1, 最後例項化f1
    order.append("f1")
    assert f3 == 123

@pytest.fixture
def f3():
    order.append("f3")
    a = 123
    yield a

@pytest.fixture
def a1():
    order.append("a1")

@pytest.fixture
def f2():
    order.append("f2")

def test_order(f1, c1, m1, f0, f2, s1, p1):
    # 按scope的優先順序,按順序執行s1,p1,m1,c1,f1(優先執行f3,之後a1,最後f1),f0,f2
    assert order == ["s1", "p1", "m1", "c1", "f3", "a1", "f1", "f0", "f2"]

2、執行結果:斷言成功

按 scope 的優先順序,按順序執行 s1,p1,m1,c1,f1(優先執行f3,之後a1,最後f1),f0,f2

3、使用多個fixture

1、建立test_fixture_2.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""
import pytest

@pytest.fixture()
def fixture_one():
    print("====fixture_one====")

@pytest.fixture()
def fixture_two():
    print("====fixture_two====")

def test_case(fixture_two, fixture_one):
    print("====執行用例====")

2、執行結果:

test_case函式執行前按順序先執行fixture_two,之後執行fixture_one。

微信公眾號:AllTests軟體測試