kgb

7.3 · active · verified Thu Apr 09

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.

Warnings

Install

Imports

Quickstart

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.

import unittest
from kgb import SpyAgency, SpyOpReturn

class MyService:
    def fetch_data(self, url):
        # In a real application, this might make a network request
        return f"Actual data from {url}"

class TestMyService(SpyAgency, unittest.TestCase):
    def test_fetch_data_called_and_mocked(self):
        service = MyService()
        
        # Spy on the fetch_data method and make it return a mocked value
        self.spy_on(service.fetch_data, op=SpyOpReturn("Mocked Data!"))
        
        # Call the method that is now spied upon
        result = service.fetch_data("https://example.com/api/v1/data")
        
        # Assertions using kgb's spy capabilities
        self.assertEqual(result, "Mocked Data!")
        self.assert_spy_called(service.fetch_data)
        self.assert_spy_called_with(service.fetch_data,
                                    "https://example.com/api/v1/data")

# To run this example (typically done via a test runner like `python -m unittest`):
# if __name__ == '__main__':
#     unittest.main()

view raw JSON →