Skip to main content

Utilities for spying on function calls in unit tests.

Project description

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 page.

Installing kgb

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

$ pip install kgb

or:

$ easy_install kgb

kgb supports Python 2.5 through 2.7 and 3.4 through 3.6.

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()
        self.spy_on(weather.start_raining)

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.
            bomb.explode()

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

agency.spy_on(obj.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

obj.function.unspy()

Do your job and get out.

Check the call history

for call in obj.function.calls:
    print(calls.args, calls.kwargs)

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

Check a specific call

# Check the latest call...
print obj.function.last_call.args
print obj.function.last_call.kwargs
print obj.function.last_call.return_value
print obj.function.last_call.exception

# For an older call...
print obj.function.calls[0].args
print obj.function.calls[0].kwargs
print obj.function.calls[0].return_value
print obj.function.calls[0].exception

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

self.assertTrue(obj.function.called)

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

Check if the function was ever called with certain arguments

# Check if it was ever called with these arguments...
self.assertTrue(obj.function.called_with('foo', bar='baz'))

# Check a specific call...
self.assertTrue(obj.function.calls[0].called_with('foo', bar='baz'))

# Check the last call...
self.assertTrue(obj.function.last_called_with('foo', bar='baz'))

The whole call history will be searched. You can provide the entirety of the arguments passed to the function, or you can provide a subset. You can pass positional arguments as-is, or pass them by name using keyword arguments.

Recorded calls always follow the function’s original signature, so even if a keyword argument was passed a positional value, it will be recorded as a keyword argument.

Check if the function ever returned a certain value

# Check if the function ever returned a certain value...
self.assertTrue(obj.function.returned(42))

# Check a specific call...
self.assertTrue(obj.function.calls[0].returned(42))

# Check the last call...
self.assertTrue(obj.function.last_returned(42))

Handy for checking if some function ever returned what you expected it to, when you’re not calling that function yourself.

Check if a function ever raised a certain type of exception

# Check if the function ever raised a certain exception...
self.assertTrue(obj.function.raised(TypeError))

# Check a specific call...
self.assertTrue(obj.function.calls[0].raised(TypeError))

# Check the last call...
self.assertTrue(obj.function.last_raised(TypeError))

You can also go a step further by checking the exception’s message.

# Check if the function ever raised an exception with a given message...
self.assertTrue(obj.function.raised_with_message(
    TypeError,
    "'type' object is not iterable"))

# Check a specific call...
self.assertTrue(obj.function.calls[0].raised_with_message(
    TypeError,
    "'type' object is not iterable"))

# Check the last call...
self.assertTrue(obj.function.last_raised_with_message(
    TypeError,
    "'type' object is not iterable"))

Reset all the calls

obj.function.reset_calls()

Wipe away the call history. Nobody will know.

FAQ

Doesn’t this just do what mock does?

kgb’s spies and mock’s patching are very different from each other. When patching using mock, you’re simply replacing a method on a class with something that looks like a method, and that works great except you’re limited to methods on classes. You can’t override something a top-level function, like urllib2.urlopen.

kgb spies leave the function or method where it is. What it does do is replace the bytecode of the function, intercepting calls on a very low level, recording everything about it, and then passing on the call to the original function or your replacement function. It’s pretty powerful, and allows you to listen to or override calls you normally would have no control over.

What?! There’s no way that’s stable.

It is! It really is! We’ve been using it for years across a wide variety of codebases. It’s pretty amazing.

Python actually allows this. We’re not scanning your RAM and doing terrible things with it, or something like that. Every function or method in Python has a func_code (Python 2) or __code__ (Python 3) attribute, which is mutable. We can go in and replace the bytecode with something compatible with the original function.

How we actually do that, well, that’s complicated, and you may not want to know.

Does this work with PyPy?

I’m going to level with you, I was going to say “hell no!”, and then decided to give it a try.

Hell yes! (But only accidentally. YMMV… We’ll try to officially support this later.)

What else do you build?

Lots of things. Check out some of our other open source projects.

Project details


Download files

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

Source Distribution

kgb-2.0.tar.gz (26.2 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

kgb-2.0-py3.6.egg (50.5 kB view details)

Uploaded Egg

kgb-2.0-py3.5.egg (51.3 kB view details)

Uploaded Egg

kgb-2.0-py3.4.egg (51.4 kB view details)

Uploaded Egg

kgb-2.0-py3-none-any.whl (26.9 kB view details)

Uploaded Python 3

kgb-2.0-py2.7.egg (49.0 kB view details)

Uploaded Egg

kgb-2.0-py2.6.egg (49.1 kB view details)

Uploaded Egg

kgb-2.0-py2-none-any.whl (26.9 kB view details)

Uploaded Python 2

File details

Details for the file kgb-2.0.tar.gz.

File metadata

  • Download URL: kgb-2.0.tar.gz
  • Upload date:
  • Size: 26.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for kgb-2.0.tar.gz
Algorithm Hash digest
SHA256 af92a7c0fa1ba11feea98534563a25c2a07e67f0ef9d8cf11df56b2b2e55c7ad
MD5 059752bed793862db9571eaf5841f042
BLAKE2b-256 66956a3e101e078d08af23e516ac5802e9ef03887abef8fec179225fa22eb251

See more details on using hashes here.

File details

Details for the file kgb-2.0-py3.6.egg.

File metadata

  • Download URL: kgb-2.0-py3.6.egg
  • Upload date:
  • Size: 50.5 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for kgb-2.0-py3.6.egg
Algorithm Hash digest
SHA256 deba5c8a41e4ff3c05ea79da7181e2c6febd2a05ff1c917f5f8b44a2a34f937d
MD5 44ac2265c87c30c6ba6dd9abefbe8ee7
BLAKE2b-256 66aae769452bac2d566f51fc896aebe7e73cdd3c3ef849125572405824b811a0

See more details on using hashes here.

File details

Details for the file kgb-2.0-py3.5.egg.

File metadata

  • Download URL: kgb-2.0-py3.5.egg
  • Upload date:
  • Size: 51.3 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for kgb-2.0-py3.5.egg
Algorithm Hash digest
SHA256 8293b1269896c9680594f5f6eef7d65f8a9971ab14d309cdcca8fbe36c8bb6b0
MD5 75b7ea09e91b5d9c134f3680b7bfe487
BLAKE2b-256 a75f1f3b85d58df5f8442ee3fc306723712c5bcb8cfbbf0ecb18a97a89632a63

See more details on using hashes here.

File details

Details for the file kgb-2.0-py3.4.egg.

File metadata

  • Download URL: kgb-2.0-py3.4.egg
  • Upload date:
  • Size: 51.4 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for kgb-2.0-py3.4.egg
Algorithm Hash digest
SHA256 63c4b72e46849e6d43379eaddca30119f8dc3e0c539ed634a225666c845743e9
MD5 0fd9ca7f67b51f4bf656a5f8dd905883
BLAKE2b-256 6ef146acd764bdee1d24452d1a033753a29201c17a0a8654c8df0e47be94af21

See more details on using hashes here.

File details

Details for the file kgb-2.0-py3-none-any.whl.

File metadata

  • Download URL: kgb-2.0-py3-none-any.whl
  • Upload date:
  • Size: 26.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for kgb-2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 02e5772f8876e3fe287c8b54fdb782d639a1907e11c4d76ec3bf5536a3918cf6
MD5 304801f33a4d11852dd4a1513bc10185
BLAKE2b-256 9f4ba5cc4e7446002afbd01aeef05bb65f16b55b4a8215ca12c113e08d5f1727

See more details on using hashes here.

File details

Details for the file kgb-2.0-py2.7.egg.

File metadata

  • Download URL: kgb-2.0-py2.7.egg
  • Upload date:
  • Size: 49.0 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for kgb-2.0-py2.7.egg
Algorithm Hash digest
SHA256 6041fdff8d58a450424d23177bd3e47cc579f73321169e085de1c08729a71092
MD5 050b89d5651805f82db7859b33b7bbf8
BLAKE2b-256 e50dc0b3d5ebc85fb6d8810b151d63f8d16a36a61981976b8c6438c395a123cd

See more details on using hashes here.

File details

Details for the file kgb-2.0-py2.6.egg.

File metadata

  • Download URL: kgb-2.0-py2.6.egg
  • Upload date:
  • Size: 49.1 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for kgb-2.0-py2.6.egg
Algorithm Hash digest
SHA256 14f28779eb90dc7a6202c23565b1bca79dfd13636307309e22c8447397bcda65
MD5 f5590f0d3dda2c9c48ea364eea182d0b
BLAKE2b-256 d85f39ebee9dec6612677a3688747986cce67fd71fa7baf2f5957dff6ef0e47a

See more details on using hashes here.

File details

Details for the file kgb-2.0-py2-none-any.whl.

File metadata

  • Download URL: kgb-2.0-py2-none-any.whl
  • Upload date:
  • Size: 26.9 kB
  • Tags: Python 2
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for kgb-2.0-py2-none-any.whl
Algorithm Hash digest
SHA256 6b8d7414a60d233958b1210f416c317640fb42a55951e9f871518d3e2dd81638
MD5 c1b3ab9a35d1bef415f5f8184d1cc8b2
BLAKE2b-256 ef84269f012839f14554e11bebed57b4315f564a34e5a627bc5e4c4b6cddfad3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page