11、pytest -- 測試的參數化

往期索引:https://www.cnblogs.com/luizyao/p/11771740.html

在實際工作中,測試用例可能需要支持多種場景,我們可以把和場景強相關的部分抽象成參數,通過對參數的賦值來驅動用例的執行;

參數化的行爲表現在不同的層級上:

另外,我們也可以通過pytest_generate_tests這個鉤子方法自定義參數化的方案;

1. @pytest.mark.parametrize標記

@pytest.mark.parametrize的根本作用是在收集測試用例的過程中,通過對指定參數的賦值來新增被標記對象的調用(執行)

首先,我們來看一下它在源碼中的定義:

# _pytest/python.py

def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None):

着重分析一下各個參數:

  • argnames:一個用逗號分隔的字符串,或者一個列表/元組,表明指定的參數名;

    對於argnames,實際上我們是有一些限制的:

    • 只能是被標記對象入參的子集:

      @pytest.mark.parametrize('input, expected', [(1, 2)])
      def test_sample(input):
          assert input + 1 == 1

      test_sample中並沒有聲明expected參數,如果我們在標記中強行聲明,會得到如下錯誤:

      In test_sample: function uses no argument 'expected'
    • 不能是被標記對象入參中,定義了默認值的參數:

      @pytest.mark.parametrize('input, expected', [(1, 2)])
      def test_sample(input, expected=2):
          assert input + 1 == expected

      雖然test_sample聲明瞭expected參數,但同時也爲其賦予了一個默認值,如果我們在標記中強行聲明,會得到如下錯誤:

      In test_sample: function already takes an argument 'expected' with a default value
    • 會覆蓋同名的fixture

      @pytest.fixture()
      def expected():
          return 1
      
      
      @pytest.mark.parametrize('input, expected', [(1, 2)])
      def test_sample(input, expected):
          assert input + 1 == expected

      test_sample標記中的expected(2)覆蓋了同名的fixture expected(1),所以這條用例是可以測試成功的;

      這裏可以參考:4、fixtures:明確的、模塊化的和可擴展的 -- 在用例參數中覆寫fixture

  • argvalues:一個可迭代對象,表明對argnames參數的賦值,具體有以下幾種情況:

    • 如果argnames包含多個參數,那麼argvalues的迭代返回元素必須是可度量的(即支持len()方法),並且長度和argnames聲明參數的個數相等,所以它可以是元組/列表/集合等,表明所有入參的實參:

      @pytest.mark.parametrize('input, expected', [(1, 2), [2, 3], set([3, 4])])
      def test_sample(input, expected):
          assert input + 1 == expected

      注意:考慮到集合的去重特性,我們並不建議使用它;

    • 如果argnames只包含一個參數,那麼argvalues的迭代返回元素可以是具體的值:

      @pytest.mark.parametrize('input', [1, 2, 3])
      def test_sample(input):
          assert input + 1
    • 如果你也注意到我們之前提到,argvalues是一個可迭代對象,那麼我們就可以實現更復雜的場景;例如:從excel文件中讀取實參:

      def read_excel():
          # 從數據庫或者 excel 文件中讀取設備的信息,這裏簡化爲一個列表
          for dev in ['dev1', 'dev2', 'dev3']:
              yield dev
      
      
      @pytest.mark.parametrize('dev', read_excel())
      def test_sample(dev):
          assert dev

      實現這個場景有多種方法,你也可以直接在一個fixture中去加載excel中的數據,但是它們在測試報告中的表現會有所區別;

    • 或許你還記得,在上一篇教程(10、skip和xfail標記 -- 結合pytest.param方法)中,我們使用pytest.paramargvalues參數賦值:

      @pytest.mark.parametrize(
          ('n', 'expected'),
          [(2, 1),
          pytest.param(2, 1, marks=pytest.mark.xfail(), id='XPASS')])
      def test_params(n, expected):
          assert 2 / n == expected

      現在我們來具體分析一下這個行爲:

      無論argvalues中傳遞的是可度量對象(列表、元組等)還是具體的值,在源碼中我們都會將其封裝成一個ParameterSet對象,它是一個具名元組(namedtuple),包含values, marks, id三個元素:

      >>> from _pytest.mark.structures import ParameterSet as PS
      >>> PS._make([(1, 2), [], None])
      ParameterSet(values=(1, 2), marks=[], id=None)

      如果直接傳遞一個ParameterSet對象會發生什麼呢?我們去源碼裏找答案:

      # _pytest/mark/structures.py
      
      class ParameterSet(namedtuple("ParameterSet", "values, marks, id")):
      
          ...
      
          @classmethod
          def extract_from(cls, parameterset, force_tuple=False):
              """
              :param parameterset:
                  a legacy style parameterset that may or may not be a tuple,
                  and may or may not be wrapped into a mess of mark objects
      
              :param force_tuple:
                  enforce tuple wrapping so single argument tuple values
                  don't get decomposed and break tests
              """
      
              if isinstance(parameterset, cls):
                  return parameterset
              if force_tuple:
                  return cls.param(parameterset)
              else:
                  return cls(parameterset, marks=[], id=None)

      可以看到如果直接傳遞一個ParameterSet對象,那麼返回的就是它本身(return parameterset),所以下面例子中的兩種寫法是等價的:

      # src/chapter-11/test_sample.py
      
      import pytest
      
      from _pytest.mark.structures import ParameterSet
      
      
      @pytest.mark.parametrize(
          'input, expected',
          [(1, 2), ParameterSet(values=(1, 2), marks=[], id=None)])
      def test_sample(input, expected):
          assert input + 1 == expected

      到這裏,或許你已經猜到了,pytest.param的作用就是封裝一個ParameterSet對象;那麼我們去源碼裏求證一下吧!

      # _pytest/mark/__init__.py
      
      def param(*values, **kw):
          """Specify a parameter in `pytest.mark.parametrize`_ calls or
          :ref:`parametrized fixtures <fixture-parametrize-marks>`.
      
          .. code-block:: python
      
              @pytest.mark.parametrize("test_input,expected", [
                  ("3+5", 8),
                  pytest.param("6*9", 42, marks=pytest.mark.xfail),
              ])
              def test_eval(test_input, expected):
                  assert eval(test_input) == expected
      
          :param values: variable args of the values of the parameter set, in order.
          :keyword marks: a single mark or a list of marks to be applied to this parameter set.
          :keyword str id: the id to attribute to this parameter set.
          """
          return ParameterSet.param(*values, **kw)

      正如我們所料,現在你應該更明白怎麼給argvalues傳參了吧;

  • indirectargnames的子集或者一個布爾值;將指定參數的實參通過request.param重定向到和參數同名的fixture中,以此滿足更復雜的場景;

    具體使用方法可以參考以下示例:

    # src/chapter-11/test_indirect.py
    
    import pytest
    
    
    @pytest.fixture()
    def max(request):
        return request.param - 1
    
    
    @pytest.fixture()
    def min(request):
        return request.param + 1
    
    
    # 默認 indirect 爲 False
    @pytest.mark.parametrize('min, max', [(1, 2), (3, 4)])
    def test_indirect(min, max):
        assert min <= max
    
    
    # min max 對應的實參重定向到同名的 fixture 中
    @pytest.mark.parametrize('min, max', [(1, 2), (3, 4)], indirect=True)
    def test_indirect_indirect(min, max):
        assert min >= max
    
    
    # 只將 max 對應的實參重定向到 fixture 中
    @pytest.mark.parametrize('min, max', [(1, 2), (3, 4)], indirect=['max'])
    def test_indirect_part_indirect(min, max):
        assert min == max
  • ids:一個可執行對象,用於生成測試ID,或者一個列表/元組,指明所有新增用例的測試ID

    • 如果使用列表/元組直接指明測試ID,那麼它的長度要等於argvalues的長度:

      @pytest.mark.parametrize('input, expected', [(1, 2), (3, 4)],
                        ids=['first', 'second'])
      def test_ids_with_ids(input, expected):
          pass

      蒐集到的測試ID如下:

      collected 2 items
      <Module test_ids.py>
        <Function test_ids_with_ids[first]>
        <Function test_ids_with_ids[second]>
    • 如果指定了相同的測試IDpytest會在後面自動添加索引:

      @pytest.mark.parametrize('input, expected', [(1, 2), (3, 4)],
                        ids=['num', 'num'])
      def test_ids_with_ids(input, expected):
          pass

      蒐集到的測試ID如下:

      collected 2 items
      <Module test_ids.py>
        <Function test_ids_with_ids[num0]>
        <Function test_ids_with_ids[num1]>
    • 如果在指定的測試ID中使用了非ASCII的值,默認顯示的是字節序列:

      @pytest.mark.parametrize('input, expected', [(1, 2), (3, 4)],
                        ids=['num', '中文'])
      def test_ids_with_ids(input, expected):
          pass

      蒐集到的測試ID如下:

      collected 2 items
      <Module test_ids.py>
        <Function test_ids_with_ids[num]>
        <Function test_ids_with_ids[\u4e2d\u6587]>

      可以看到我們期望顯示中文,實際上顯示的是\u4e2d\u6587

      如果我們想要得到期望的顯示,該怎麼辦呢?去源碼裏找答案:

      # _pytest/python.py
      
      def _ascii_escaped_by_config(val, config):
          if config is None:
              escape_option = False
          else:
              escape_option = config.getini(
                  "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
              )
          return val if escape_option else ascii_escaped(val)

      我們可以通過在pytest.ini中使能disable_test_id_escaping_and_forfeit_all_rights_to_community_support選項來避免這種情況:

      [pytest]
      disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True

      再次蒐集到的測試ID如下:

      <Module test_ids.py>
        <Function test_ids_with_ids[num]>
        <Function test_ids_with_ids[中文]>
    • 如果通過一個可執行對象生成測試ID

      def idfn(val):
          # 將每個 val 都加 1
          return val + 1
      
      
      @pytest.mark.parametrize('input, expected', [(1, 2), (3, 4)], ids=idfn)
      def test_ids_with_ids(input, expected):
          pass

      蒐集到的測試ID如下:

      collected 2 items
      <Module test_ids.py>
        <Function test_ids_with_ids[2-3]>
        <Function test_ids_with_ids[4-5]>

      通過上面的例子我們可以看到,對於一個具體的argvalues參數(1, 2)來說,它被拆分爲12分別傳遞給idfn,並將返回值通過-符號連接在一起作爲一個測試ID返回,而不是將(1, 2)作爲一個整體傳入的;

      下面我們在源碼中看看是如何實現的:

      # _pytest/python.py
      
      def _idvalset(idx, parameterset, argnames, idfn, ids, item, config):
          if parameterset.id is not None:
              return parameterset.id
          if ids is None or (idx >= len(ids) or ids[idx] is None):
              this_id = [
                  _idval(val, argname, idx, idfn, item=item, config=config)
                  for val, argname in zip(parameterset.values, argnames)
              ]
              return "-".join(this_id)
          else:
              return _ascii_escaped_by_config(ids[idx], config)

      和我們猜想的一樣,先通過zip(parameterset.values, argnames)argnamesargvalues的值一一對應,再將處理過的返回值通過"-".join(this_id)連接;

      另外,如果我們足夠細心,從上面的源碼中還可以看出,假設已經通過pytest.param指定了id屬性,那麼將會覆蓋ids中對應的測試ID,我們來證實一下:

      @pytest.mark.parametrize(
          'input, expected',
          [(1, 2), pytest.param(3, 4, id='id_via_pytest_param')],
          ids=['first', 'second'])
      def test_ids_with_ids(input, expected):
          pass

      蒐集到的測試ID如下:

      collected 2 items
      <Module test_ids.py>
        <Function test_ids_with_ids[first]>
        <Function test_ids_with_ids[id_via_pytest_param]>

      測試IDid_via_pytest_param,而不是second

    講了這麼多ids的用法,對我們有什麼用呢?

    我覺得,其最主要的作用就是更進一步的細化測試用例,區分不同的測試場景,爲有針對性的執行測試提供了一種新方法;

    例如,對於以下測試用例,可以通過-k 'Window and not Non'選項,只執行和Windows相關的場景:

    # src/chapter-11/test_ids.py
    
    import pytest
    
    
    @pytest.mark.parametrize('input, expected', [
        pytest.param(1, 2, id='Windows'),
        pytest.param(3, 4, id='Windows'),
        pytest.param(5, 6, id='Non-Windows')
    ])
    def test_ids_with_ids(input, expected):
        pass
  • scope:聲明argnames中參數的作用域,並通過對應的argvalues實例劃分測試用例,進而影響到測試用例的收集順序;

    • 如果我們顯式的指明scope參數;例如,將參數作用域聲明爲模塊級別:

      # src/chapter-11/test_scope.py
      
      import pytest
      
      
      @pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)], scope='module')
      def test_scope1(test_input, expected):
          pass
      
      
      @pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)], scope='module')
      def test_scope2(test_input, expected):
          pass

      蒐集到的測試用例如下:

      collected 4 items
      <Module test_scope.py>
        <Function test_scope1[1-2]>
        <Function test_scope2[1-2]>
        <Function test_scope1[3-4]>
        <Function test_scope2[3-4]>

      以下是默認的收集順序,我們可以看到明顯的差別:

      collected 4 items
      <Module test_scope.py>
        <Function test_scope1[1-2]>
        <Function test_scope1[3-4]>
        <Function test_scope2[1-2]>
        <Function test_scope2[3-4]>
    • scope未指定的情況下(或者scope=None),當indirect等於True或者包含所有的argnames參數時,作用域爲所有fixture作用域的最小範圍;否則,其永遠爲function

      # src/chapter-11/test_scope.py
      
      @pytest.fixture(scope='module')
      def test_input(request):
          pass
      
      
      @pytest.fixture(scope='module')
      def expected(request):
          pass
      
      
      @pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)],
                              indirect=True)
      def test_scope1(test_input, expected):
          pass
      
      
      @pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)],
                              indirect=True)
      def test_scope2(test_input, expected):
          pass

      test_inputexpected的作用域都是module,所以參數的作用域也是module,用例的收集順序和上一節相同:

      collected 4 items
      <Module test_scope.py>
        <Function test_scope1[1-2]>
        <Function test_scope2[1-2]>
        <Function test_scope1[3-4]>
        <Function test_scope2[3-4]>

1.1. empty_parameter_set_mark選項

默認情況下,如果@pytest.mark.parametrizeargnames中的參數沒有接收到任何的實參的話,用例的結果將會被置爲SKIPPED

例如,當python版本小於3.8時返回一個空的列表(當前Python版本爲3.7.3):

# src/chapter-11/test_empty.py

import pytest
import sys


def read_value():
    if sys.version_info >= (3, 8):
        return [1, 2, 3]
    else:
        return []


@pytest.mark.parametrize('test_input', read_value())
def test_empty(test_input):
    assert test_input

我們可以通過在pytest.ini中設置empty_parameter_set_mark選項來改變這種行爲,其可能的值爲:

  • skip:默認值
  • xfail:跳過執行直接將用例標記爲XFAIL,等價於xfail(run=False)
  • fail_at_collect:上報一個CollectError異常;

1.2. 多個標記組合

如果一個用例標記了多個@pytest.mark.parametrize標記,如下所示:

# src/chapter-11/test_multi.py

@pytest.mark.parametrize('test_input', [1, 2, 3])
@pytest.mark.parametrize('test_output, expected', [(1, 2), (3, 4)])
def test_multi(test_input, test_output, expected):
    pass

實際收集到的用例,是它們所有可能的組合:

collected 6 items
<Module test_multi.py>
  <Function test_multi[1-2-1]>
  <Function test_multi[1-2-2]>
  <Function test_multi[1-2-3]>
  <Function test_multi[3-4-1]>
  <Function test_multi[3-4-2]>
  <Function test_multi[3-4-3]>

1.3. 標記測試模塊

我們可以通過對pytestmark賦值,參數化一個測試模塊:

# src/chapter-11/test_module.py

import pytest

pytestmark = pytest.mark.parametrize('test_input, expected', [(1, 2), (3, 4)])


def test_module(test_input, expected):
    assert test_input + 1 == expected

2. pytest_generate_tests鉤子方法

pytest_generate_tests方法在測試用例的收集過程中被調用,它接收一個metafunc對象,我們可以通過其訪問測試請求的上下文,更重要的是,可以使用metafunc.parametrize方法自定義參數化的行爲;

我們先看看源碼中是怎麼使用這個方法的:

# _pytest/python.py

def pytest_generate_tests(metafunc):
    # those alternative spellings are common - raise a specific error to alert
    # the user
    alt_spellings = ["parameterize", "parametrise", "parameterise"]
    for mark_name in alt_spellings:
        if metafunc.definition.get_closest_marker(mark_name):
            msg = "{0} has '{1}' mark, spelling should be 'parametrize'"
            fail(msg.format(metafunc.function.__name__, mark_name), pytrace=False)
    for marker in metafunc.definition.iter_markers(name="parametrize"):
        metafunc.parametrize(*marker.args, **marker.kwargs)

首先,它檢查了parametrize的拼寫錯誤,如果你不小心寫成了["parameterize", "parametrise", "parameterise"]中的一個,pytest會返回一個異常,並提示正確的單詞;然後,循環遍歷所有的parametrize的標記,並調用metafunc.parametrize方法;

現在,我們來定義一個自己的參數化方案:

在下面這個用例中,我們檢查給定的stringinput是否只由字母組成,但是我們並沒有爲其打上parametrize標記,所以stringinput被認爲是一個fixture

# src/chapter-11/test_strings.py

def test_valid_string(stringinput):
    assert stringinput.isalpha()

現在,我們期望把stringinput當成一個普通的參數,並且從命令行賦值:

首先,我們定義一個命令行選項:

# src/chapter-11/conftest.py

def pytest_addoption(parser):
    parser.addoption(
        "--stringinput",
        action="append",
        default=[],
        help="list of stringinputs to pass to test functions",
    )

然後,我們通過pytest_generate_tests方法,將stringinput的行爲由fixtrue改成parametrize

# src/chapter-11/conftest.py

def pytest_generate_tests(metafunc):
    if "stringinput" in metafunc.fixturenames:
        metafunc.parametrize("stringinput", metafunc.config.getoption("stringinput"))

最後,我們就可以通過--stringinput命令行選項來爲stringinput參數賦值了:

λ pipenv run pytest -q --stringinput='hello' --stringinput='world' src/chapter-11/test_strings.py
..                                                                     [100%] 
2 passed in 0.02s

如果我們不加--stringinput選項,相當於parametrizeargnames中的參數沒有接收到任何的實參,那麼測試用例的結果將會置爲SKIPPED

λ pipenv run pytest -q src/chapter-11/test_strings.py
s                                                                  [100%] 
1 skipped in 0.02s

注意:

不管是metafunc.parametrize方法還是@pytest.mark.parametrize標記,它們的參數(argnames)不能是重複的,否則會產生一個錯誤:ValueError: duplicate 'stringinput'

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章