1. 程式人生 > 實用技巧 >pytest引數化

pytest引數化

Pytest可以在多個級別上實現測試引數化

[email protected]裝飾器呼叫引數

示例

import pytest
from selenium import webdriver
from time import sleep    

@pytest.fixture(scope="module",params=["python","java"])
def modarg(request):
    param = request.param
    # print(f"setup modarg {param}")
    yield param
    # print(f"teardown modarg {param}")
def test_login(modarg): dr = webdriver.Chrome() dr.get('https://www.baidu.com') dr.find_element_by_id('kw').send_keys(modarg) dr.find_element_by_id('su').click() sleep(2) print(modarg) dr.quit()

執行:

pytest -v -s xxx.py

二.@pytest.mark.parametrize:引數化測試功能

示例1

import pytest
from selenium import webdriver from time import sleep @pytest.mark.parametrize( "username", [ "python", "java" ] ) def test_login(username): dr = webdriver.Chrome() dr.get('https://www.baidu.com') dr.find_element_by_id('kw').send_keys(username) dr.find_element_by_id(
'su').click() sleep(2) print(username) dr.quit()

執行方式同上!

多引數示例2:

import pytest
from selenium import webdriver
from time import sleep
@pytest.mark.parametrize(
    "username,password",
    [
        ("admin","admin123"),
        ("guest","guest123"),
    ]
)

def test_login(username,password):
    dr = webdriver.Chrome()
    dr.maximize_window()
    dr.get('https://www.baidu.com')
    js = "document.querySelector('#u1 > a.s-top-login-btn.c-btn.c-btn-primary.c-btn-mini.lb').click()"
    dr.execute_script(js)
    sleep(1)
    js1 = "document.querySelector('#TANGRAM__PSP_11__footerULoginBtn').click()"
    dr.execute_script(js1)
    sleep(1)
    dr.find_element_by_id('TANGRAM__PSP_11__userName').send_keys(username)
    dr.find_element_by_id('TANGRAM__PSP_11__password').send_keys(password)
    js2 = "document.querySelector('#TANGRAM__PSP_11__submit').click()"
    dr.execute_script(js2)
    sleep(2)
    print(username)
    print(password)
    dr.quit()

執行: