1. 程式人生 > 其它 >pytest.mark.usefixtures使用

pytest.mark.usefixtures使用

pytest.mark.usefixtures使用

背景

如果每個用例都需要相同的fixture,我們手動在每一個用例上面新增fixture有點累。切記這個fixturescope='function'

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

解決

我們把用例放到一個類中,在類上面新增pytest.mark.usefixtures,來給每一個用例新增fixture,當然你也可以在fixture使用autouse=True來實現自動執行,但是這有一個弊端,如果我有一個用例不需要該fixture就需要額外處理了。

用例:

@pytest.mark.usefixtures('myfixture')
class TestCase:
    def test_1(self):
        print('正在執行自動化用例1')

    def test_2(self):
        print('正在執行自動化用例2')

conftest.py

:

import pytest


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

執行結果:

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

test_.py::TestCase::test_1[test] 

前置條件正在執行
test
PASSED                                  [ 25%]正在執行自動化用例1
後置條件正在執行

test_.py::TestCase::test_1[dev] 

前置條件正在執行
dev
PASSED                                   [ 50%]正在執行自動化用例1
後置條件正在執行

test_.py::TestCase::test_2[test] 

前置條件正在執行
test
PASSED                                  [ 75%]正在執行自動化用例2
後置條件正在執行

test_.py::TestCase::test_2[dev] 

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


============================== 4 passed in 0.01s ===============================

Process finished with exit code 0