【汇总】pytest简易教程

pytest作为python技术栈里面主流、火热的技术,非常有必要好好学一下,因为工作和面试都能用上;

它不仅简单易用,还很强大灵活,重点掌握fixture、parametrize参数化、allure-pytest插件等,这些在后续自动化框架里面都会用到。

如果文章不能访问,请联系处理,wx:ren168632201

pytest简易教程(01):pytest介绍及基本使用

pytest简易教程(02):用例查找规则

pytest简易教程(03):pytest固件、及用例执行顺序

pytest简易教程(04):fixture简介及调用

pytest简易教程(05):fixture实现自定义前置、后置

pytest简易教程(06):fixture作用域(scope)详解

pytest简易教程(07):fixture跨模块共享(conftest.py)

pytest简易教程(08):

  • 41
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
pytest是一个功能强大的Python测试框架,它支持参数化、fixture、mock、覆盖率等多种测试方式。以下是pytest的详细教程: 1.安装pytest ``` pip install pytest ``` 2.编写测试用例 pytest的测试用例文件以test_开头或以_test结尾,并且测试函数以test_开头。例如: ```python # test_demo.py def test_add(): assert 1 + 1 == 2 def test_sub(): assert 2 - 1 == 1 ``` 3.运行测试用例 在终端中进入测试用例所在的目录,运行pytest命令即可运行所有测试用例。 ``` pytest ``` 4.运行指定的测试用例 可以使用nodeid来运行指定的测试用例,nodeid由模块文件名、分隔符、类名、方法名、参数构成。例如: ``` pytest ./testcase/test_demo.py::test_add ``` 5.使用fixture fixture是pytest中的一个重要概念,它可以用来为测试用例提供前置条件和后置条件。例如: ```python # conftest.py import pytest @pytest.fixture() def login(): print("登录操作") yield print("退出登录") # test_demo.py def test_cart(login): print("购物车测试") ``` 6.参数化测试 pytest支持参数化测试,可以使用@pytest.mark.parametrize装饰器来实现。例如: ```python # test_demo.py import pytest @pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)]) def test_eval(test_input, expected): assert eval(test_input) == expected ``` 7.使用mock pytest可以与mock库一起使用,实现对被测代码的模拟。例如: ```python # test_demo.py from unittest import mock def test_demo(): with mock.patch("os.getcwd", return_value="/test"): assert os.getcwd() == "/test" ``` 8.覆盖率测试 pytest可以使用pytest-cov插件来进行覆盖率测试。例如: ``` pytest --cov=./ ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值