Pytest可以在多个级别上实现测试参数化
一.@pytest.fixture装饰器调用参数
示例
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()
执行: