kgb is a Python library that provides utilities for creating function spies in unit tests, offering a powerful alternative to traditional mocking. It intercepts and records calls to functions, tracking arguments and return values, and can modify function behavior at the bytecode level. Unlike some mocking frameworks, kgb can spy on top-level functions in addition to class methods. It supports popular testing frameworks like unittest, pytest, nose, and nose2, and maintains an active release cadence, with recent versions adding support for the latest Python releases.
pip install kgbVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `kgb` within a `unittest.TestCase` to spy on a method, mock its return value, and then assert that the method was called with specific arguments. The `SpyAgency` is mixed into the test class, and `spy_on` is used to intercept calls.
Upgrade Python to 3.6+ or pin `kgb<7.0` in your dependencies. Python 3.13 and 3.14 are supported in later 7.x releases.
Update assertion calls from `assertSpyCalledWith` to `assert_spy_called_with`, `assertHasSpy` to `assert_has_spy`, etc.
Directly use assertion methods on the spied function/method, e.g., `func.called_with()`. All spy interactions now behave consistently.
When using `spy_on`, provide the original function's name via the `func_name` argument (e.g., `spy_agency.spy_on(BadClass.good_func, owner=BadClass, func_name='good_func')`).
Install the kgb library using pip: `pip install kgb`
Import 'SpyAgency' (the primary way to manage spies) from the 'kgb' module: `from kgb import SpyAgency`
Remove the '.spy' attribute from your calls. For example, change `my_func.spy.called` to `my_func.called`, and `my_func.spy.assert_called_with()` to `my_func.assert_called_with()`. Alternatively, if using a `SpyAgency`, you'd use its assertion methods like `spy_agency.assert_spy_called(my_func)`.