Novice学Pytest(6)-conftest.py的详细讲解

一、前言

  what's the conftest.py?我们可以理解成一个专门存放fixture的配置文件。for example,写yy自动化脚本时,多个测试用例文件(test_speak.py、test_send_gift和test_attention.py等test_*.py)的所有用例都需要登录功能(login)作为前置操作,所以不能把登录功能写到某个用例文件中。针对这个问题,及时雨contest.py来了,conftest.py支持单独管理一些全局的fixture

二、contest.py配置fixture注意事项

  • pytest会默认读取conftest.py里面的所有fixture
  • conftest.py 文件名称是固定的,不能改动
  • conftest.py只对同一个package下的所有测试用例生效
  • 不同目录可以有自己的conftest.py,一个项目中可以有多个conftest.py
  • 测试用例文件中不需要手动import conftest.py,pytest会自动查找

三、实战演练

  1.项目目录:

  2.conftest目录下的conftest.py eg:最顶层的conftest,一般写全局的fixture,在Web UI自动化中,可能会初始化driver

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 """
 5 __Title__   =
 6 __Time__    =  2021/8/14 21:53
 7 __Author__  =  Isaymore
 8 __Blog__    =  https://www.cnblogs.com/huainanhai/
 9 """
10 
11 import pytest
12 
13 @pytest.fixture(scope="session")
14 def login():
15     print("===登录功能,返回账号,token===")
16     name = "liyebin01"
17     token = "xiaobin1234"
18     yield name,token
19     print("===退出登录!!!===")
20 
21 @pytest.fixture(autouse=True)
22 def get_info(login):
23     name,token = login
24     print(f"===每个用例都调用的外层fixture:打印用户token:{token}===")
View Code

  3.conftest目录下的test_get_info.py:同级目录下的第一条测试用例

1 def test_get_info(login):
2     name,token = login
3     print("***基础用例:获取用户信息***")
4     print(f"用户名:{name},token:{token}")
View Code

  4.toutiao目录下的test_comment.py:包没有__init__.py文件,也没有conftest.py文件

1 def test_no_fixture(login):
2     print("===没有__init__测试用例,我进入头条了===",login)
View Code

  5.weibo目录下的conftest.py:配置一些针对微博的测试用例独有的fixture,eg:启动微博

1 import pytest
2 @pytest.fixture(scope="function")
3 def start_weibo(login):
4     name,token = login
5     print(f"&&&用户{name}进入微博首页&&&")
View Code

  6.weibo目录下的test_hotresearch.py

1 class TestWeibo:
2     def test_hotsearch(self,start_weibo):
3         print("查看微博热搜")
4 
5     def test_Joy(self,start_weibo):
6         print("查看微博周杰伦")
View Code

  7.conftest目录下的run.py

1 import pytest
2 
3 if __name__ == "__main__":
4     pytest.main(["-s","/conftest"])
View Code

  执行结果:

 

参考链接:https://www.cnblogs.com/poloyy/p/12663601.html

posted @ 2022-04-22 22:42  方缘  阅读(173)  评论(0编辑  收藏  举报