Expecttest

0.3.0 · active · verified Sat Apr 11

Expecttest is a Python library that implements 'expect tests' (also known as 'golden tests' or 'snapshot tests'). Unlike traditional asserts, it automatically populates the expected output of a test. When the test output changes, the library facilitates updating the expected output directly within the Python source file by modifying it in-place. The current version is 0.3.0, released in December 2024, indicating active development with a fairly rapid release cadence.

Warnings

Install

Imports

Quickstart

To use `expecttest`, define your test using `TestCase` (for `unittest`) or directly call `assert_expected_inline` (for Pytest or standalone). Initially, provide an empty triple-quoted string as the expected value. Run your tests normally; they will fail if the expected string is empty or differs. To automatically populate or update the expected string in your source file, run your tests with the `EXPECTTEST_ACCEPT=1` environment variable set. This modifies your Python file directly.

import unittest
import os
from expecttest import TestCase, assert_expected_inline

# Example for unittest integration
class TestMyFunction(TestCase):
    def test_basic_output(self):
        result = f"Hello, {1 + 2}!\nMultiline output." # Simulate some function output
        # On first run, leave expected blank. Run with EXPECTTEST_ACCEPT=1 to populate.
        # self.assertExpectedInline(result, """)"""
        self.assertExpectedInline(result, """Hello, 3!\nMultiline output.""")

# Example for pytest or general use
def test_another_function():
    data = {'key': 'value', 'number': 123}
    result = str(data)
    # On first run, leave expected blank. Run with EXPECTTEST_ACCEPT=1 to populate.
    # assert_expected_inline(result, """)"""
    assert_expected_inline(result, """{'key': 'value', 'number': 123}""")

if __name__ == '__main__':
    # To update the expected values in the source file, run:
    # EXPECTTEST_ACCEPT=1 python your_test_file.py
    # or EXPECTTEST_ACCEPT=1 pytest your_test_file.py
    if os.environ.get('EXPECTTEST_ACCEPT') == '1':
        print("Running in ACCEPT mode. Expected values will be updated.")
    unittest.main()

view raw JSON →