Skip to main content

Fluent assertion library for Python with full type safety and soft assertions

Project description

assertpy2

Fluent assertion library for Python with full type safety and soft assertions.
Maintained fork of assertpy.

CI PyPI version Downloads Python Coverage License Ruff

Quick start

pip install assertpy2
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")

When an assertion fails, the error message tells you exactly what went wrong:

assert_that(user["age"]).is_between(50, 120)
# AssertionError: Expected <30> to be between <50> and <120>, but was not.

assert_that(user["roles"]).contains("admin")
# AssertionError: Expected <['viewer', 'editor']> to contain <admin>, but did not.

Why fluent assertions?

# bare assert - passes, but failure message is useless
assert user["age"] >= 18
# AssertionError

# assertpy2 - same check, clear failure message
assert_that(user["age"]).is_greater_than_or_equal_to(18)
# AssertionError: Expected <16> to be greater than or equal to <18>, but was not.

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

# assertpy2 - one fluent chain
assert_that(items).is_type_of(list).is_length(3).contains("admin")

Features

  • Type safety: Self return types, py.typed (PEP 561).
  • IDE support: full autocomplete and chaining inference out of the box.
  • Soft assertions: collect all failures with soft_assertions(), plus soft_fail() for non-halting explicit failures.
  • Fluent chaining: write assertions as readable one-liners that chain naturally.
  • Dynamic assertions: has_<name>() for any attribute, property, or zero-argument method on objects and dicts.
  • Dict comparison: is_equal_to() with ignore and include for selective key matching.
  • Extracting: flatten collections on attributes with filter and sort support.
  • File assertions: exists(), is_file(), is_readable(), is_writable(), is_executable() with pathlib.Path support.
  • Snapshot testing: store and compare data structures in JSON format, inspired by Jest.
  • Extensions: add custom assertions via add_extension().
  • Strings, numbers, lists, tuples, sets, dicts, dates, booleans, objects, exceptions.

Soft assertions

Collect all failures instead of stopping at the first one:

from assertpy2 import assert_that, soft_assertions

def test_user_profile():
    with soft_assertions():
        assert_that(user.name).is_equal_to("Alice")
        assert_that(user.age).is_greater_than(0)
        assert_that(user.email).contains("@")

All failures are reported at the end of the block:

AssertionError: soft assertion failures:
1. Expected <Bob> to be equal to <Alice>, but was not.
2. Expected <-1> to be greater than <0>, but was not.
3. Expected <invalid> to contain <@>, but did not.

Use soft_fail("message") inside the block for non-halting explicit failures (unlike fail(), which stops immediately).

API highlights

Dict comparison with ignore/include

assert_that({"a": 1, "b": 2, "c": 3}).is_equal_to({"a": 1}, ignore=["b", "c"])
assert_that({"a": 1, "b": {"c": 2, "d": 3}}).is_equal_to({"b": {"d": 3}}, include=("b", "d"))

Extracting with filter and sort

users = [
    {"user": "Fred", "age": 36, "active": True},
    {"user": "Bob", "age": 40, "active": False},
    {"user": "Johnny", "age": 13, "active": True},
]

assert_that(users).extracting("user", filter="active").is_equal_to(["Fred", "Johnny"])
assert_that(users).extracting("user", sort="age").is_equal_to(["Johnny", "Fred", "Bob"])

Expected exceptions

assert_that(some_func).raises(RuntimeError).when_called_with("bad_arg")\
    .is_length(8).starts_with("some").is_equal_to("some err")

Snapshot testing

assert_that({"a": 1, "b": 2, "c": 3}).snapshot()

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

Migration from assertpy

assertpy2 is a drop-in replacement for Python 3.10+. Change the import, everything else works:

# before
from assertpy import assert_that, soft_assertions

# after
from assertpy2 import assert_that, soft_assertions
assertpy assertpy2
Maintained Last release 2020 Active
Python 2.7+ 3.10-3.15
Type safety No annotations Self return types, py.typed (PEP 561)
IDE support No type info Full autocomplete and chaining inference
Soft assertions Basic Stable, with soft_fail() support
Security CVE in snapshots Fixed
Open bugs 15+ unresolved All resolved

Contributing

Contributions are welcome. See CONTRIBUTING.md for details.

License

All files are licensed under the BSD 3-Clause License as follows:

Copyright (c) 2015-2019, Activision Publishing, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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.0.1.tar.gz (85.9 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.0.1-py3-none-any.whl (47.3 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for assertpy2-2.0.1.tar.gz
Algorithm Hash digest
SHA256 4f2ad7accd39aec62f0189a53eda29011f9a667a06a9a6defed15b680e723805
MD5 536cf9ac4128133957d30533b135fe35
BLAKE2b-256 7cb075fc3bc8b4575eabae79d31634b84d888a2801a3ae97b3e71166367c9017

See more details on using hashes here.

Provenance

The following attestation bundles were made for assertpy2-2.0.1.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.0.1-py3-none-any.whl.

File metadata

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

File hashes

Hashes for assertpy2-2.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 def409c8271ccfb7e363ab3250f735bcd1104a7e3fc2dd433348a8ca4add1c93
MD5 315e9e636105652b7d580ee4447e276c
BLAKE2b-256 8975c921571fca95191b7db0723089979924cf3b19b427303adcad7f961f6133

See more details on using hashes here.

Provenance

The following attestation bundles were made for assertpy2-2.0.1-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