Skip to main content

Utilities for spying on function calls in unit tests.

Project description

kgb - Function spies for Python

Ever deal with a large test suite before, monkey patching functions to figure
out whether it was called as expected? It's a dirty job. If you're not careful,
you can make a mess of things. Leave behind evidence.

kgb's spies will take care of that little problem for you.

What are spies?

Spies intercept and record calls to functions. They can report on how many times
a function was called and with what arguments. They can allow the function call
to go through as normal, to block it, or to reroute it to another function.

Spies are awesome.

(If you've used [Jasmine](, you know this.)

Where is kgb used?

We use kgb at [Beanbag]( for our
[Review Board]( and
[RBCommons]( products.

If you use kgb, let us know and we'll add you to a shiny new list on this

Installing kgb

Before you can use kgb, you need to install it. You can do this by typing:

$ easy_install kgb


$ pip install kgb

kgb supports Python 2.5 through 2.7.

Spying for fun and profit

Spying is really easy. There are three ways to initiate a spy.

### 1. Creating a SpyAgency

A SpyAgency manages all your spies. You can create as many or as few as you
want. Generally, you'll create one per unit test run. Then you'll call
`spy_on`, passing in the function you want.

from kgb import SpyAgency

class TopSecretTests(unittest.TestCase):
def test_mind_control_device(self):
mcd = MindControlDevice()
agency = SpyAgency()
agency.spy_on(mcd.assassinate, call_fake=give_hugs)

### 2. Mixing a SpyAgency into your tests

A SpyAgency can be mixed into your test suite, making it super easy to spy
all over the place, discretely, without resorting to a separate agency.
(We call this the "inside job.")

from kgb import SpyAgency

class TopSecretTests(SpyAgency, unittest.TestCase):
def test_weather_control(self):
weather = WeatherControlDevice()

### 3. Using a context manager

If you just want a spy for a quick job, without all that hassle of a full
agency, just use the `spy_on` context manager, like so:

from kgb import spy_on

class TopSecretTests(unittest.TestCase):
def test_the_bomb(self):
bomb = Bomb()

with spy_on(bomb.explode, call_original=False):
# This won't explode. Phew.

A word about functions

In Python, there are different types of functions. Spying on a bound method
on a class, or a classmethod, is easy. Internally, we just replace those,
and you don't know the difference.

Standard functions are a different matter. We do some evil tricks to make those
work, but we can't replace them with spies completely. For these functions,
you'll need to access the `spy` attribute on the function. We'll show that

For convenience, we also provide a `spy` on all function types, but you only
*need* to use them for standard functions.

A spy's abilities

A spy can do many things. The first thing you need to do is figure out how you
want to use the spy.

### Creating a spy that calls the original function


When your spy is called, the original function will be called as well.
It won't even know you were there.

### Creating a spy that blocks the function call

agency.spy_on(obj.function, call_original=False)

Useful if you want to know that a function was called, but don't want the
original function to actually get the call.

### Creating a spy that reroutes to a fake function

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

Fake return values or operations without anybody knowing.

### Stopping a spy operation

# For bound methods...

# For standard functions...

Do your job and get out.

### Check the call history

# For bound methods...
for call in obj.function.calls:
print calls.args, calls.kwargs

# For standard functions...
for call in function.spy.calls:
print calls.args, calls.kwargs

See how many times your spy's intercepted a function call, and what was passed.

### Check the last call

# For bound methods...
print obj.function.last_call.args
print obj.function.last_call.kwargs

# For standard functions...
print function.spy.last_call.args
print function.spy.last_call.kwargs

Also a good way of knowing whether it's even been called. last_call will be
`None` if nobody's called yet.

### Check if the function was ever called

# For bound methods...

# For standard functions...

If the function was ever called at all, this will let you know.

### Check if the function was ever called with certain arguments

# For bound methods...
self.assertTrue(obj.function.called_with('foo', bar='baz'))

# For standard functions...
self.assertTrue(function.spy.called_with('foo', bar='baz'))

The whole call history will be searched. The arguments provided must match
the call exactly. No mixing of args and kwargs.

### Check if the last call had certain arguments

# For bound methods...
self.assertTrue(obj.function.last_called_with('foo', bar='baz'))

# For standard functions...
self.assertTrue(function.spy.last_called_with('foo', bar='baz'))

Just like `called_with`, but only the most recent call be checked.

### Reset all the calls

# For bound methods...

# For standard functions...

Wipe away the call history. Nobody will know.

Project details

Release history Release notifications

History Node


History Node


History Node


History Node


History Node


History Node


This version
History Node


History Node


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, size & hash SHA256 hash help File type Python version Upload date
kgb-0.5.1-py2.5.egg (17.2 kB) Copy SHA256 hash SHA256 Egg 2.5 Jun 2, 2014
kgb-0.5.1-py2.6.egg (17.2 kB) Copy SHA256 hash SHA256 Egg 2.6 Jun 2, 2014
kgb-0.5.1-py2.7.egg (17.1 kB) Copy SHA256 hash SHA256 Egg 2.7 Jun 2, 2014
kgb-0.5.1.tar.gz (14.5 kB) Copy SHA256 hash SHA256 Source None Jun 2, 2014

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging CloudAMQP CloudAMQP RabbitMQ AWS AWS Cloud computing Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page