【Pytest】fixture使用request傳參,結合parametrize

傳一組參數

@File    : test_fixture_parametrize.py
@Author  : 靈樞
@Time    : 2020/4/8 4:51 PM
@Desc    :  
"""
import pytest


test_account = ["user1", "user2"]


@pytest.fixture(scope="module")
def login(request):
    user = request.param
    print("登錄賬戶: %s" %user)
    return user


@pytest.mark.parametrize("login", test_account, indirect=True) 
def test_login(login):
    user_name = login
    print("login的返回值是:%s" % user_name)
    assert 1 == 1


if __name__ == '__main__':
    pytest.main(["-s", "test_fixture_parametrize.py"])

注意:

  • indirect=True是爲了把login當成一個函數去執行,而不是一個參數。
  • fixture是可以有返回值的,如果沒return,默認返回None。
  • 如果用例要調用fixture的返回值,直接把fixture的函數名稱當成變量名稱就可以了。

運行結果如下:
在這裏插入圖片描述

傳兩組參數

# encoding: utf-8 
"""
@File    : test_fixture_parametrize2.py
@Author  : 靈樞
@Time    : 2020/4/8 4:51 PM
@Desc    :  
"""
import pytest


test_account = [{"username": "user1", "password": "111111"},
                  {"username": "user2", "password": "222222"}]


@pytest.fixture(scope="module")
def login(request):
    username = request.param["username"]
    password = request.param["password"]
    print("登錄賬戶名: %s" % username)
    print("登錄密碼: %s" % password)
    return username+":"+password


@pytest.mark.parametrize("login", test_account, indirect=True)
def test_login(login):
    '''登錄用例'''
    account = login
    print("登錄賬戶爲:%s" % account)
    assert 1 == 1


if __name__ == '__main__':
    pytest.main(["-s", "test_fixture_parametrize2.py"])

運行結果爲:
在這裏插入圖片描述

多個fixture和多個parametrize

2個fixture和2個parametrize疊加時,用例組合是2個參數個數相乘

# encoding: utf-8 
"""
@File    : test_fixture_parametrize3.py
@Author  : 靈樞
@Time    : 2020/4/8 4:51 PM
@Desc    : 2個fixture和2個parametrize疊加時,用例組合是2個參數個數相乘

"""
import pytest


test_username = ["user1", "user2"]
test_password = ["111111", "222222"]


@pytest.fixture(scope="module")
def test_user(request):
    username = request.param
    print("登錄用戶名: %s" % username)
    return username


@pytest.fixture(scope="module")
def test_psw(request):
    password = request.param
    print("登錄密碼:%s" % password)
    return password


@pytest.mark.parametrize("test_user", test_username, indirect=True)
@pytest.mark.parametrize("test_psw", test_password, indirect=True)
def test_login(test_user, test_psw):
    '''登錄賬戶'''
    username = test_user
    password = test_psw
    print("登錄賬戶爲:%s : %s" % (username, password))
    assert 1 == 1


if __name__ == '__main__':
    pytest.main(["-s", "test_fixture_parametrize3.py"])

運行結果如下:
在這裏插入圖片描述

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