Hamcrest 断言
Posted CSR-kkk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于Hamcrest 断言的主要内容,如果未能解决你的问题,请参考以下文章
为什么我们的Hamcrest断言不被认为是规则S2699的有效断言?