Expects: Expressive TDD/BDD Assertion Library
Expects is an expressive and extensible TDD/BDD assertion library for Python, designed to make test assertions clear and readable in a TDD/BDD style. It supports a wide range of built-in matchers and allows for defining custom ones. The current stable version is 0.9.0, released in October 2018. Given the age of the last release, the library is in a maintenance state rather than active development.
Common errors
-
NameError: name 'expect' is not defined
cause The `expect` callable was not imported into the current scope.fixAdd `from expects import *` or `from expects import expect` at the top of your test file. -
IndentationError: expected an indented block
cause This usually occurs when copy-pasting code, and Python's strict indentation rules are violated.fixEnsure consistent indentation (typically 4 spaces) throughout your Python code, especially after colons for code blocks (e.g., function definitions, `if` statements). -
TypeError: 'Matcher' object is not callable
cause Attempting to call a matcher directly (e.g., `expect(value).to(be_empty())` instead of `expect(value).to(be_empty)`). Matchers are properties, not functions, when used with `.to()`.fixRemove the parentheses when using matchers with `.to()`, unless the matcher explicitly expects arguments (e.g., `equal(5)`). Correct: `expect(value).to(be_empty)`.
Warnings
- gotcha The primary recommended import, `from expects import *`, pollutes the global namespace with `expect` and all matcher functions (e.g., `equal`, `be_empty`). While convenient for small tests, this can lead to name collisions in larger codebases.
- gotcha The `expects` library has not seen a new release since October 2018 (version 0.9.0). While functional, it might not be actively maintained, which could lead to compatibility issues with newer Python versions, lack of bug fixes for modern environments, or unaddressed security vulnerabilities.
- gotcha Despite its 2018 release date, version 0.9.0 of `expects` explicitly states compatibility with Python 2.7. However, mixing Python 2 and 3 environments with libraries released around the 2.x to 3.x transition (e.9., some `0.9.0` releases like `cmd2` v0.9.0) has historically led to `pip` installing incorrect versions. Verify your Python interpreter version and `expects` installation if encountering unexpected behavior, especially in older Python 2.7 environments.
Install
-
pip install expects
Imports
- expect
import expects expects.expect([])
from expects import expect, be_empty, equal
- * (all matchers)
from expects import *
Quickstart
from expects import *
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# Example assertions
expect(5).to(equal(5))
expect([]).to(be_empty)
expect(False).not_to(be_true)
expect(lambda: divide(1, 0)).to(raise_error(ValueError, 'Cannot divide by zero'))
expect({'name': 'Alice'}).to(have_key('name'))
print("All assertions passed!")