欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

Hamcrest 断言

发布时间:2023/12/20 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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.0demo_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: AssertionErrorAssertion failed

总结

以上是生活随笔为你收集整理的Hamcrest 断言的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。