Fundamentals 4 min read

Using assertpy for Enhanced Python Assertions

The article introduces the assertpy library for Python, explains its purpose of enhancing assertions, and provides a comprehensive set of example code snippets demonstrating how to validate strings, collections, numbers, booleans, files, and more using readable assertpy methods.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using assertpy for Enhanced Python Assertions

assertpy is a Python library that enhances assertions by offering readable and expressive methods, especially useful when dealing with complex data structures.

The following code examples illustrate a variety of assertpy assertions covering strings, lists, dictionaries, sets, numbers, booleans, and files.

from assertpy import assert_that
# 示例1:断言字符串相等
assert_that('hello').is_equal_to('hello')

# 示例2:断言字符串不为空
assert_that('not empty').is_not_empty()

# 示例3:断言字符串长度
assert_that('short').has_length(5)

# 示例4:断言字符串包含子串
assert_that('long string').contains('string')

# 示例5:断言字符串不包含子串
assert_that('long string').does_not_contain('substring')

# 示例6:断言列表元素数量
assert_that([1, 2, 3]).has_length(3)

# 示例7:断言列表包含特定元素
assert_that([1, 2, 3]).contains_only(1, 2, 3)

# 示例8:断言列表包含所有指定元素(顺序无关)
assert_that([1, 2, 3, 4]).contains_exactly(½, 3, 2, 4)

# 示例9:断言字典包含特定键值对
assert_that({'key': 'value', 'another_key': 'another_value'}).contains_entry('key', 'value')

# 示例10:断言字典包含所有指定键值对(顺序无关)
assert_that({'key1': 'val1', 'key2': 'val2'}).contains_entries(
    {'key1': 'val1'}, {'key2': 'val2'}
)

# 示例11:断言集合包含特定元素
assert_that({1, 2, 3}).contains_only(1, 2, 3)

# 示例12:断言布尔值为真
assert_that(True).is_true()

# 示例13:断言布尔值为假
assert_that(False).is_false()

# 示例14:断言数值等于预期值
assert_that(42).is_equal_to(42)

# 示例15:断言数值在范围内
assert_that(42).is_between(40, 45)

# 示例16:断言浮点数近似相等(考虑浮点误差)
assert_that(3.14159).is_close_to(π, abs_tol=0.001)

# 示例17:断言两个列表元素一一对应相等
assert_that([1, 2, 3]).is_equal_to_ordered([1, 2, 3])

# 示例18:断言两个字典内容相同(忽略键值对顺序)
assert_that({'a': 1, 'b': 2}).is_equal_to_unordered({'b': 2, 'a': 1})

# 示例19:断言文件存在
assert_that('/path/to/file.txt').exists()

# 示例20:断言文件内容匹配正则表达式
assert_that('/path/to/file.txt').matches_regexp(r'^Some pattern$')

These examples demonstrate common assertpy methods for validating various data types; users should install the library via pip install assertpy before employing these assertions in their tests.

unit testingAssertionsassertpy
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.