PyHamcrest的使用

本文介绍如何在Python中使用Hamcrest库进行对象比较,包括equal_to、same_instance、close_to等关键匹配器。通过实例演示了如何验证学生信息、数字精度和对象唯一性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引用包:

from hamcrest import *

assert_that()

  '''
    assert_that(actual, matcher=None, reason=""):

    :param actual: 实际结果
    :param matcher: 匹配器,期望匹配的结果
    :param reason: 校验失败后输出的信息(可选项)

    The exception raised for an unmet assertion is an
    :py:exc:`AssertionError`, which PyUnit reports as a test failure.

    :exception AssertionError
    '''

需要两个必要参数:actual、matcher

可选参数:reason

失败后抛出异常:AssertionError


简单举例

信息:

students_info = [
     {"name": "Zhang", "age": "18", "cash":23.05},
    {"name": "Wang", "age": "12", "cash":8.65},
    {"name": "Zhang", "age": "18", "cash":23.05}
]

equal_to 匹配相等的对象

    def test_Name1(self):
        assert_that(students_info[2].get("name"), equal_to("Zhang"), reason="该学生信息不存在")


    def test_Name2(self):
        assert_that(students_info[0].get("name"), equal_to("Zhang"), reason="该学生信息不存在")

equal_to只比较值是否相等,第一个学生和第三个学生的name相同,但是是不同的对象,此处用equal_to来判断的话,均能通过

same_instance 匹配相同的对象

    def test_SameInstance1(self):
        assert_that(students_info[0], same_instance(students_info[0]),reason="不是同一个对象")


    def test_SameInstance2(self):
        assert_that(students_info[2], same_instance(students_info[0]),reason="不是同一个对象")

此处用例2会报错:

hamcrest_demo.py:79 (TestHamcrest.test_SameInstance)
self = <hamcrest_demo.TestHamcrest object at 0x000001E9E3D08070>

    def test_SameInstance(self):
>       assert_that(students_info[2], same_instance(students_info[0]),reason="不是同一个对象")
E       AssertionError: 不是同一个对象
E       Expected: same instance as 0x1e9e317ec00 <{'name': 'Zhang', 'age': '18', 'cash': 23.05}>
E            but: was 0x1e9e3182740 <{'name': 'Zhang', 'age': '18', 'cash': 23.05}>

hamcrest_demo.py:81: AssertionError

close_to 匹配接近的数字

 close_to(value, delta)
    :param value 匹配值
    :param delta 上下浮动的范围
    def test_Cash(self):
        assert_that(7.65, close_to(value=students_info[1].get("cash"),delta=1), reason="金额相差过大")

匹配器:

  '''
    匹配器:
    对象
        equal_to - 匹配相等的对象
        has_length - 匹配长度 len(item)
        has_property - 匹配属性值
        has_properties - 匹配包含所有属性值的对象
        has_string - 匹配字符串 str(item)
        instance_of - 匹配对象的类型
        none, not_none - 匹配None或not None
        same_instance - 匹配相同的对象
        calling, raises - calling和raise结合使用
    数字
        close_to - 匹配接近的数字
        greater_than, greater_than_or_equal_to, less_than, less_than_or_equal_to - 匹配数字大小
    文本
        contains_string - 匹配包含字符串
        ends_with - 匹配以字符串结尾
        equal_to_ignoring_case - 匹配完整字符串且忽略大小写
        equal_to_ignoring_whitespace - 匹配完整的字符串且忽略空白字符
        starts_with - 匹配以字符串开始
        string_contains_in_order- 在相对位置,匹配部分字符如string_contains_in_order("bc", "fg", "jkl")将会匹配abcdefghijklm
    逻辑
        all_of - 匹配所有指定的匹配项 and
        any_of - 匹配其中任意一个匹配项 or
        anything - 匹配任何条件,等效于true
        is_not - 匹配相反的条件,如assert_that(cheese, is_not(equal_to(smelly)))
        not_ - 等效于is_not 如 assert_that(alist, not_(has_item(item)))
    序列
        contains_exactly - 匹配完整的序列,排序也要一致
        contains_inanyorder - 匹配完整的序列,不要求排序一致
        has_item - 匹配序列中指定的元素
        has_items - 匹配序列中指定的多个元素,不要求排序
        is_in - 匹配元素是否在指定序列中
        only_contains - 匹配序列是否在指定list中出现
        empty - 匹配空序列
    字典 
        has_entries - 匹配字典多个键值对
        has_entry - 匹配字典键值对
        has_key - 匹配字典的key
        has_value - 匹配字典的value
    
    '''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值