天天看點

pytest-參數化測試(pytest.mark)

pytest 參數化測試

使用的工具 

pytest.mark.parametrize(argnames, argvalues)

  • argnames表示參數名。
  • argvalues表示清單形式的參數值。

使用以裝飾器的形式使用。

隻有一個參數的測試用例

import pytest

user_name = ['chenjiaxing', 'lijiacheng']

@pytest.mark.parametrize('user_name', user_name)
def test_login_01(user_name):
    """ 通過使用者名登入 """
    print('注冊使用者名是: {}'.format(user_name))           

運作結果

test.py::test_login_01[chenjiaxing] PASSED                               [ 50%]注冊使用者名是: chenjiaxing

test.py::test_login_01[lijiacheng] PASSED                                [100%]注冊使用者名是: lijiacheng


========================== 2 passed in 0.05 seconds ===========================

Process finished with exit code 0           

多個參數的測試用例

方式一:

import pytest
user_name = ['chenjiaxing', 'lijiacheng']
pwd_list = ['D6YFH', 'ww5FK']


@pytest.mark.parametrize('user_name', user_name)
@pytest.mark.parametrize('pwd', pwd_list)
def test_login_02(user_name, pwd):
    """ 通過手機号注冊 """
    print('注冊手機号是: {} 驗證碼是: {}'.format(user_name, pwd))           

運作結果

test.py::test_login_02[D6YFH-chenjiaxing] PASSED                         [ 25%]注冊手機号是: chenjiaxing 驗證碼是: D6YFH

test.py::test_login_02[D6YFH-lijiacheng] PASSED                          [ 50%]注冊手機号是: lijiacheng 驗證碼是: D6YFH

test.py::test_login_02[ww5FK-chenjiaxing] PASSED                         [ 75%]注冊手機号是: chenjiaxing 驗證碼是: ww5FK

test.py::test_login_02[ww5FK-lijiacheng] PASSED                          [100%]注冊手機号是: lijiacheng 驗證碼是: ww5FK


========================== 4 passed in 0.19 seconds ===========================

Process finished with exit code 0           

方式二:

import itertools
import pytest
user_name = ['chenjiaxing', 'lijiacheng']
pwd_list = ['D6YFH', 'ww5FK']

@pytest.mark.parametrize('user_name,pwd', list(itertools.product(user_name, pwd_list)))
def test_login_03(user_name, pwd):
    """ 通過使用者名登入 """
    print('注冊使用者名是: {} 密碼是: {}'.format(user_name, pwd))           

運作結果

test.py::test_login_03[chenjiaxing-D6YFH] PASSED                         [ 25%]注冊使用者名是: chenjiaxing 密碼是: D6YFH

test.py::test_login_03[chenjiaxing-ww5FK] PASSED                         [ 50%]注冊使用者名是: chenjiaxing 密碼是: ww5FK

test.py::test_login_03[lijiacheng-D6YFH] PASSED                          [ 75%]注冊使用者名是: lijiacheng 密碼是: D6YFH

test.py::test_login_03[lijiacheng-ww5FK] PASSED                          [100%]注冊使用者名是: lijiacheng 密碼是: ww5FK


========================== 4 passed in 0.05 seconds ===========================

Process finished with exit code 0           

方式一和方式二運作結果是一樣,可以看到,每一個使用者名與每一個密碼一一對應組合,如果有很多個組合的話,用例數将會更多,不用寫那麼多用例就可以輕松實作,happy~