ApprovalTests
ApprovalTests.Python is a powerful assertion/verification library for Python, aiding in test-driven development by comparing generated output to a pre-approved baseline. It is currently at version 17.4.3 and maintains a fairly active release cadence, with several minor releases and occasional major updates.
Common errors
-
ModuleNotFoundError: No module named 'approvaltests'
cause If this occurs after `pip install approvaltests`, it's likely due to a packaging error in version 17.4.2.fixUpgrade to the latest version: `pip install --upgrade approvaltests` (to get 17.4.3 or newer). -
No reporter found for file: your_test_name.received.txt
cause ApprovalTests could not find or launch a suitable diff tool to display the comparison between the received and approved files.fixInstall a supported diff tool (e.g., Beyond Compare, Meld, VS Code) and ensure it's configured correctly according to the ApprovalTests documentation (e.g., in your PATH or via `reporters.json`). -
ImportError: cannot import name 'BeyondCompareReporter' from 'approvaltests.reporters'
cause You are attempting to import a reporter class using an old path or name that was changed in v17.0.0.fixUpdate your import statement and reporter usage. For Beyond Compare, use `from approvaltests.reporters.diff_reporters.report_with_beyond_compare import ReportWithBeyondCompare` and pass it to `Options().with_reporters(...)`.
Warnings
- breaking Prior to v17.0.0, diff reporters were configured differently, often relying on `reporters.json` or direct imports of reporter classes that no longer exist or have been renamed. This can lead to `ImportError` or unexpected reporter behavior when upgrading.
- gotcha ApprovalTests relies on external diff tools (like Beyond Compare, Meld, KDiff3, VS Code diff) to compare received and approved files. If no diff tool is detected or configured, approval tests might not open a comparison window, or fail with a 'no reporter found' message, potentially leading to unnoticed changes or manual file comparison.
- breaking Version 17.4.2 had a packaging error that prevented it from being imported, leading to an `ImportError` or `ModuleNotFoundError` immediately after installation, making the library unusable.
Install
-
pip install approvaltests
Imports
- verify
from approvaltests import verify
- Options
from approvaltests import Options
- ReportWithBeyondCompare
from approvaltests.reporters import BeyondCompareReporter
from approvaltests.reporters.diff_reporters.report_with_beyond_compare import ReportWithBeyondCompare
Quickstart
from approvaltests import verify, Options
def generate_report_content():
return (
"User Report:\n"
"- ID: 123\n"
"- Name: Alice Wonderland\n"
"- Email: alice@example.com\n"
)
# This will generate a .received.txt file and attempt to open a diff tool.
# The first run will likely show a diff, subsequent runs pass if content matches.
verify(generate_report_content())