Pytest fixture之request传参
- 2019 年 11 月 28 日
- 筆記
Pytest中我们经常会用到数据参数化,我们来介绍下装饰器@pytest.fixture()配合request传参的使用
user = request.param
如果想把登录操作放到前置操作里,也就是用到@pytest.fixture装饰器,传参就用默认的request参数
user = request.param 这一步是接收传入的参数,本案例是传一个参数情况
@pytest.mark.parametrize("input_user",user_list,indirect=True)中indirect=True是指用user_list、pwd_list数据对“input_user”、“input_pwd”这个fixture进行参数化,虽然装饰器写在测试用例上,但是却是对测试用例使用的fixture进行传递数据,这正是indirect的意思.
request传多个参数、多个fixtrue
import pytest user_list=['wangxiao','zhangxiao'] pwd_list=['123456','123'] @pytest.fixture(scope="module") def input_user(request): user=request.param print("用户名:%s"%user) return user @pytest.fixture(scope="module") def input_pwd(request): pwd = request.param print("密码:%s"%pwd) return pwd @pytest.mark.parametrize("input_user",user_list,indirect=True) @pytest.mark.parametrize("input_pwd",pwd_list,indirect=True) def test_login(input_user,input_pwd): print(input_user,input_pwd) if __name__=='__main__': pytest.main(['-s','test01.py']) "C:Program FilesPython35python.exe" C:/Users/wangli/PycharmProjects/Test/test/test01.py ============================= test session starts ============================= platform win32 -- Python 3.5.2, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: C:UserswangliPycharmProjectsTesttest plugins: allure-pytest-2.8.5, html-1.22.0, metadata-1.8.0 collected 4 items test01.py 用户名:wangxiao 密码:123456 wangxiao 123456 .用户名:zhangxiao zhangxiao 123456 .密码:123 zhangxiao 123 .用户名:wangxiao wangxiao 123 . ============================== 4 passed in 0.06s ============================== Process finished with exit code 0
request传多个参数、单个fixtrue
import pytest user_list=[('wangxiao','123'),('chengzi','123456')] @pytest.fixture(scope="module") def login(request): user = request.param pwd = request.param print("用户名:%s,密码:%s"%(user,pwd)) return user,pwd @pytest.mark.parametrize("login",user_list,indirect=True) def test_login(login): print(login) if __name__=='__main__': pytest.main(['-s','test01.py']) "C:Program FilesPython35python.exe" C:/Users/wangli/PycharmProjects/Test/test/test01.py ============================= test session starts ============================= platform win32 -- Python 3.5.2, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: C:UserswangliPycharmProjectsTesttest plugins: allure-pytest-2.8.5, html-1.22.0, metadata-1.8.0 collected 2 items test01.py 用户名:('wangxiao', '123'),密码:('wangxiao', '123') (('wangxiao', '123'), ('wangxiao', '123')) .用户名:('chengzi', '123456'),密码:('chengzi', '123456') (('chengzi', '123456'), ('chengzi', '123456')) . ============================== 2 passed in 0.04s ============================== Process finished with exit code 0