pytest之conftest.py、pytest.ini配置文件使用

1.前言

  • conftest.py 测试用例的一些fixture配置
  • pytest.ini 它是pytest的主配置文件,可以改变pytest的默认行为

2.conftest.py

对于某些用例都需要执行的功能,比如登陆、切换环境、登陆后进入大模块等。像这样的前置功能或者后置功能写到一个用例里面,其他用例就不能使用了。所以需要配置文件,管理通用的前置操作,类似于通用关键字。pytest中可以使用conftest.py实现。

  • conftest.py名称固定,pytest默认读取
  • conftest.py 和运行的用例要再一个package下,用例可以放进最顶级的package下的子package下面。保证conftest.py文件在最外层的package下就可以了。
  • pytest可以自动找到该文件,读取里面的函数。
    目录结构如下:
project
|
└───folder
|   |	__init__.py
│   │   conftest.py
│   │   test_one.py
│   └───subfolder
|		|   __init__.py
│       │   test_two.py
│       │   
│       │   ...

运行test_two.py文件,可以读取到folder文件夹下conftest.py定义好的前置、后置方法。
运行test_one.py文件,可以读取到folder文件夹下conftest.py定义好的前置、后置方法。

3.pytest.ini

  • 修改pytest-cache缓存文件生成位置 cache_dir

每次执行不同package下的module文件,都会生成一个pytest-cache文件,我是看着不习惯。统一自定义到外层package下。
在pytest.ini 中添加如下配置:可以把pytest-cache文件生成在和pytest.ini同一目录下。

[pytest]
cache_dir = .pytest-cache
  • 修改默认命令行 addopts

如下,每次执行时候等价于 pytest -q *.py

[pytest]

addopts = -q

cache_dir = .pytest-cache
  • mark标记

    • 注册标记
[pytest]

addopts = -q

cache_dir = .pytest-cache

markers =
   webtest:  mark a test as a webtest
   hello:  this is a hello tag
    • 打标记实例
@pytest.mark.hello
def test_one():
    x = "this"
    assert "" in x


@pytest.mark.webtest
class TestMyClass:
    def test_one(self):
        x = "this"
        assert "" in x

    def test_two(self):
        x = "hello"
        assert x in 'hello'


    • 通过标记执行用例

cd 进入pytest.ini文件存在目录下

# 终端或者控制台输入
pytest --markers	#可以查看到刚刚定义的标记

pytest	-m hello   #可以运行test_one用例

pytest -m "not hello"	#运行不包含hello标记的用例

pytest 	-m webtest  # 可运行TestMyClass 类下的全部用例

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值