Hamcrest 断言

Hamcrest 是一个为了测试为目的,能组成灵活表达式的匹配器类库。用于编写断言的框架,提高可读性以及开发效率。

安装
pip install pyhamcrest

导入
from hamcrest import *

常用方法
equal_to(obj): 比较两个对象

close_to(value, delta): 比较两个值是否接近,范围:[value-delta, value+delta]

contains_string(substring: str):包含某个字符

    assert_that("this is a string", equal_to("this is a string"))
    assert_that(1.0, close_to(0.5, 0.5))
    assert_that('abc', contains_string('a'))

参数化用例

import pytest
from hamcrest import *


@pytest.mark.parametrize("price, expect_price, delta", [
    (96.0, 100, 0.05), (101, 96, 0.1), (90, 100, 0.05)
])
def test_demo(price, expect_price, delta):
    print(price, ",", round(expect_price * delta, 2), ",", expect_price - expect_price * delta, ",",
          expect_price + expect_price * delta)
    assert_that(price, close_to(expect_price, round(expect_price * delta, 2)))

结果:

PASSED                            [ 33%]96.0 , 5.0 , 95.0 , 105.0
PASSED                               [ 66%]101 , 9.6 , 86.4 , 105.6
FAILED                              [100%]90 , 5.0 , 95.0 , 105.0

demo_test.py:4 (test_demo[90-100-0.05])
price = 90, expect_price = 100, delta = 0.05

    @pytest.mark.parametrize("price, expect_price, delta", [
        (96.0, 100, 0.05), (101, 96, 0.1), (90, 100, 0.05)
    ])
    def test_demo(price, expect_price, delta):
        print(price, ",", round(expect_price * delta, 2), ",", expect_price - expect_price * delta,",",
              expect_price + expect_price * delta)
>       assert_that(price, close_to(expect_price, round(expect_price * delta, 2)))
E       AssertionError: 
E       Expected: a numeric value within <5.0> of <100>
E            but: <90> differed by <10.0>

demo_test.py:11: AssertionError


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值