kgb 4.0 – Enhanced Function Spies for Python Unit Tests

Today, we’ve released kgb 4.0, the latest in our handy Python module for creating function spies in unit tests.

For those new to kgb, function spies allow unit tests to track when functions or methods are called (how many times, and with what parameters and results), and allow functions or methods to be overridden (for instance, to simulate an HTTP result using urllib2). JavaScript developers have Jasmine, and Python developers have kgb. See how documentation for more info there.

So what’s new in kgb 4.0?

Calling a spy’s original function

When spying on a function, a caller (or the spy’s replacement function) can now invoke the original behavior for the function. Unlike a call to the spy’s version, this call will not be logged. It’s really useful for keeping the original functionality intact but adding some parameter manipulation or additional tracking.

For example:

stored_results = []

def my_fake_function(*args, **kwargs):
    kwargs['bar'] = 'baz'
    result = obj.function.call_original(*args, **kwargs)
    stored_results.append(result)

    return result

agency.spy_on(obj.function, call_fake=my_fake_function)

Better Python 3 support

We’ve steadily been improving Python 3 support. It works well, but kgb 3.x would trigger some deprecation warnings when setting up a spy. We’ve fixed this up, future-proofed things some.

To learn more about kgb…

Visit the documentation to see all the way that kgb spies can work for you.

Installation is simple:

$ pip install kgb

If you find kgb useful, we’d love to hear it!

Christian Hammond

President/CEO of Beanbag. Developer of Review Board and RBCommons. Lover of sushi and bees. Not at the same time.