Skip to main content

Fluent assertion library for Python with composable matchers, structural matching, and full type safety

Project description

assertpy2

Fluent assertion library for Python with composable matchers, structural matching, and full type safety.
A modern, batteries-included fork of assertpy.

CI PyPI version Downloads Python Coverage
Documentation Ruff uv ty OpenSSF Scorecard OpenSSF Best Practices
public overloads type-checked by ty, mypy --strict, and pyright with zero suppressions


Quick start

pip install assertpy2  # drop-in replacement for assertpy, just change the import
from assertpy2 import assert_that

def test_user():
    user = {"name": "Alice", "age": 30, "roles": ["viewer", "editor"]}

    assert_that(user).contains_key("name", "age")
    assert_that(user["age"]).is_between(18, 120)
    assert_that(user["roles"]).contains("viewer").does_not_contain("admin")
    assert_that(user).has_name("Alice")

Browse the full documentation for every assertion, matcher, and integration.

Why fluent assertions?

A fluent chain reads as one intent and replaces several bare asserts - and your IDE offers only the methods that fit the value's type:

# bare - three statements, no autocomplete help
assert isinstance(items, list)
assert len(items) == 3
assert "admin" in items

# assertpy2 - one chain, type-aware autocomplete
assert_that(items).is_type_of(list).is_length(3).contains("admin")

The real difference shows up when a test fails. Here a nested response has two wrong fields. Plain assert dumps both structures and leaves you to find them:

assert response == expected
E   AssertionError: assert {'id': 1, ...} == {'id': 1, ...}
E     Omitting 1 identical items, use -vv to show
E     Differing items:
E     {'user': {'name': 'Alice', 'role': 'superadmin'}} != {'user': {'name': 'Alice', 'role': 'admin'}}
E     {'status': 'active'} != {'status': 'disabled'}

assertpy2 reports the exact path to every difference, in color:

assert_that(response).is_equal_to(expected)
Structured diff in the terminal: user.role shown with its path, removal in red and addition in green

Recursive diffs work for dicts, dataclasses, namedtuples, attrs, and Pydantic models. For responses with dynamic fields (IDs, timestamps), validate a subset with matches_structure() instead of exact equality.

The same path-level treatment for dicts, lists, sets, and matcher predicates:

Structured diffs in the terminal: dict path, list element, set extra/missing, and structural-matcher predicate diffs, side by side

Type-aware autocomplete

assert_that() uses @overload to return type-specific Protocols. Your IDE shows only methods relevant to the value you're testing, not all 100+:

  • assert_that("hello"). → string methods: starts_with, matches, is_alpha, ...
  • assert_that(42). → numeric methods: is_positive, is_between, is_close_to, ...
  • assert_that(Path("/tmp")). → path methods: exists, is_file, is_readable, ...
  • assert_that(my_dict). → dict methods: contains_key, contains_entry, has_json_path, ...
  • assert_that(b"\x89PNG"). → bytes methods: starts_with_bytes, is_valid_utf8, decoded_as, ...

9 type-specific Protocols instead of one Any. Works in PyCharm, VS Code, and any LSP-compatible editor.

See the Type Safety guide for the full walkthrough.


Features

Fluent API

  • Composable matchers: match.greater_than(5), match.is_uuid(), combine with &, |, ~. Also work with plain assert ==.
  • Structural matching: matches_structure() for declarative dict/API response validation, reporting the exact path to each mismatch on failure.
  • Universal negation: .not_ inverts any assertion without dedicated is_not_* methods.
  • Collection pipeline: filtered_on(), mapped(), flat_mapped(), first(), last(), element(), single().
  • Fluent chaining: write assertions as readable one-liners that chain naturally.

Built-in types

Testing

  • Soft assertions: thread-safe, async-safe via contextvars. Group errors with sa.group(), or use assert_all().
  • Async assertions: eventually() with polling/retry for eventual consistency.
  • Structured errors: AssertionFailure with .actual, .expected, .diff attributes.
  • Rich pytest diffs: recursive structural diffs for lists, sets, strings, dicts, dataclasses, namedtuples, Pydantic models, and matcher-based assertions (matches_structure(), satisfies(), each()). Circular reference protection.
  • Snapshot testing: store and compare data structures in JSON format.
  • Property-based tested: comparison, selective-diff, matcher algebra, and collection logic are checked with Hypothesis against reference semantics, on top of 100% branch coverage.

Type safety

Extensibility

  • Custom matchers: register_matcher() for domain-specific matchers, composable with &, |, ~.
  • Regex group extraction: extracting_group() and matches_with_groups() for regex captures.
  • Extensions: add_extension() for custom assertion methods.

Integrations

  • Allure: auto-attach structured diff and actual/expected data to reports. pip install assertpy2[allure].
  • Behave: ready-made parameter types for step definitions. pip install assertpy2[behave].

See the full documentation for all assertion methods, examples, and advanced features.


Integrations

Allure

When allure-pytest is installed, the pytest plugin auto-attaches structured failure data to Allure reports as JSON attachments.

pip install assertpy2[allure]

Three modes controlled via pytest.ini (or pyproject.toml):

Mode What is attached
diff (default) Structured Diff JSON (path-level breakdown)
full Structured Diff + actual/expected JSON
off Nothing
# pyproject.toml
[tool.pytest.ini_options]
assertpy2_allure = "full"

Behave

Ready-made parameter types for Behave step definitions:

pip install assertpy2[behave]
# in environment.py or steps/conftest.py
from assertpy2.behave_matchers import register_assertpy_types
register_assertpy_types()

Then use in step definitions:

@given('a user aged {age:PositiveInt}')
def step_impl(context, age):
    context.age = age  # already validated as int > 0

Available types: PositiveInt, NonNegativeInt, PositiveFloat, NonEmptyString, BoolLike.

See the Integrations guide for attachment modes, configuration, and full examples.


BSD 3-Clause License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

assertpy2-2.10.0.tar.gz (392.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

assertpy2-2.10.0-py3-none-any.whl (70.9 kB view details)

Uploaded Python 3

File details

Details for the file assertpy2-2.10.0.tar.gz.

File metadata

  • Download URL: assertpy2-2.10.0.tar.gz
  • Upload date:
  • Size: 392.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for assertpy2-2.10.0.tar.gz
Algorithm Hash digest
SHA256 f7aaf07655944c55f9db852028df3dc730912edea2876dfeb8702857a25ad30a
MD5 3d472b9a43019ec6ec2cf91ba1f515ef
BLAKE2b-256 19a5449570261d2d7ee4df0e540937df5798a9fd2c3201f4e716ae6099d22303

See more details on using hashes here.

Provenance

The following attestation bundles were made for assertpy2-2.10.0.tar.gz:

Publisher: publish.yml on Solganis/assertpy2

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file assertpy2-2.10.0-py3-none-any.whl.

File metadata

  • Download URL: assertpy2-2.10.0-py3-none-any.whl
  • Upload date:
  • Size: 70.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for assertpy2-2.10.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4ba2874865ca3652b1ab36e7e97f15b0091b81c3c3cdde6a499d9e015db1d295
MD5 a235e8edca6e648ba4f5734479706c54
BLAKE2b-256 bb364a91d3f439a8e26046af567fc49a016bb7647f32cc78a48a568c2e40c51c

See more details on using hashes here.

Provenance

The following attestation bundles were made for assertpy2-2.10.0-py3-none-any.whl:

Publisher: publish.yml on Solganis/assertpy2

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page