AssertPy
AssertPy is a simple assertion library for Python unit testing with a fluent API, inspired by AssertJ for Java. It allows for highly readable and chainable assertions. The current version is 1.1, and it has an active release cadence with frequent updates.
Warnings
- breaking The `assert_soft()` function was renamed to `assert_warn()`.
- breaking The `extract()` helper function was renamed to `extracting()`.
- gotcha Older versions of AssertPy supported Python 2.x, but modern versions are Python 3.x only. Specific older Python 3 versions (e.g., 3.3, 2.6) have also been dropped over time.
- gotcha When using `matches()` for regular expression assertions, be aware that it performs a partial match (like `re.match`). For exact full string matches, include anchors (e.g., `^...$`) in your regex pattern.
- gotcha For `dict` equality comparisons with `is_equal_to()`, you can control which keys are included or ignored. If not specified, all keys are compared.
- gotcha Snapshot testing (`.snapshot()`) requires Python 3.x and saves artifacts to disk (e.g., `__snapshots` directory by default). These artifacts should be committed to version control.
Install
-
pip install assertpy
Imports
- assert_that
from assertpy import assert_that
- soft_assertions
from assertpy import soft_assertions
- assert_warn
from assertpy import assert_warn
Quickstart
from assertpy import assert_that, soft_assertions
def test_basic_assertions():
assert_that(1 + 2).is_equal_to(3)
assert_that('foobar').is_length(6).starts_with('foo').ends_with('bar')
assert_that(['a', 'b', 'c']).contains('a').does_not_contain('x')
print('Basic assertions passed.')
def test_soft_assertions():
with soft_assertions():
assert_that(1).is_equal_to(2) # This will fail
assert_that('hello').is_length(10) # This will also fail
print('Soft assertions completed. Failures (if any) are collected.')
test_basic_assertions()
test_soft_assertions()