Name | kgb JSON |
Version |
7.2
JSON |
| download |
home_page | None |
Summary | Utilities for spying on function calls in unit tests. |
upload_time | 2024-11-04 02:57:30 |
maintainer | None |
docs_url | None |
author | None |
requires_python | !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,>=2.7 |
license | MIT |
keywords |
pytest
unit tests
spies
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
===============================
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.)
Spies are like mocks, but better. You're not mocking the world. You're
replacing very specific function logic, or listening to functions without
altering them. (See the FAQ below.)
.. _Jasmine: https://jasmine.github.io/
What test platforms are supported?
==================================
Anything Python-based:
* unittest_
* pytest_
* nose_
* nose2_
You can even use it outside of unit tests as part of your application. If you
really want to. (Probably don't do that.)
.. _unittest: https://docs.python.org/3/library/unittest.html
.. _pytest: https://pytest.org
.. _nose: https://nose.readthedocs.io/en/latest/
.. _nose2: https://docs.nose2.io/en/latest/
Where is kgb used?
==================
* `liveswot-api <https://github.com/imranariffin/liveswot-api>`_ --
REST API Backend for liveswot
* `phabricator-emails
<https://github.com/mozilla-conduit/phabricator-emails>`_ --
Mozilla's utilities for converting Phabricator feeds to e-mails
* `projector <https://github.com/brennie/projector>`_ --
Takes the overhead out of managing repositories and development environments
* `ynab-sdk-python <https://github.com/andreroggeri/ynab-sdk-python>`_ --
Python implementation of the YNAB API
Plus our own products:
* `Django Evolution <https://django-evolution.readthedocs.io/>`_ --
An alternative approach to Django database migrations
* `Djblets <https://github.com/djblets/djblets/>`_ --
An assortment of utilities and add-ons for managing large Django projects
* `Review Board <https://www.reviewboard.org/>`_ --
Our open source, extensible code review product
* `RBCommons <https://rbcommons.com>`_ --
Our hosted code review service
* `RBTools <https://www.reviewboard.org/downloads/rbtools/>`_ --
Command line tools for Review Board
* `Power Pack <https://www.reviewboard.org/powerpack/>`_ --
Document review, reports, and enterprise SCM integrations for Review Board
* `Review Bot <https://www.reviewboard.org/downloads/reviewbot/>`_ --
Automated code review add-on for Review Board
If you use kgb, let us know and we'll add you!
Installing kgb
==============
Before you can use kgb, you need to install it. You can do this by typing::
$ pip install kgb
kgb supports Python 2.7 and 3.6 through 3.11, both CPython and PyPy.
Spying for fun and profit
=========================
Spying is really easy. There are four main 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.
.. code-block:: python
from kgb import SpyAgency
def test_mind_control_device():
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 unittest_-based 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.")
.. code-block:: python
from kgb import SpyAgency
# Using Python's unittest:
class TopSecretTests(SpyAgency, unittest.TestCase):
def test_weather_control(self):
weather = WeatherControlDevice()
self.spy_on(weather.start_raining)
# Using pytest with the "spy_agency" fixture (kgb 7+):
def test_weather_control(spy_agency):
weather = WeatherControlDevice()
spy_agency.spy_on(weather.start_raining)
3. Using a decorator
--------------------
If you're creating a spy that calls a fake function, you can simplify some
things by using the ``spy_for`` decorator:
.. code-block:: python
from kgb import SpyAgency
# Using Python's unittest:
class TopSecretTests(SpyAgency, unittest.TestCase):
def test_doomsday_device(self):
dd = DoomsdayDevice()
@self.spy_for(dd.kaboom)
def _save_world(*args, **kwargs)
print('Sprinkles and ponies!')
# Give it your best shot, doomsday device.
dd.kaboom()
# Using pytest:
def test_doomsday_device(spy_agency):
dd = DoomsdayDevice()
@spy_agency.spy_for(dd.kaboom)
def _save_world(*args, **kwargs)
print('Sprinkles and ponies!')
# Give it your best shot, doomsday device.
dd.kaboom()
4. 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:
.. code-block:: python
from kgb import spy_on
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
-----------------------------------------------
.. code-block:: python
spy_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
--------------------------------------------
.. code-block:: python
spy_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
-----------------------------------------------
.. code-block:: python
def _my_fake_function(some_param, *args, **kwargs):
...
spy_agency.spy_on(obj.function, call_fake=my_fake_function)
# Or, in kgb 6+
@spy_agency.spy_for(obj.function)
def _my_fake_function(some_param, *args, **kwargs):
...
Fake the return values or operations without anybody knowing.
Stopping a spy operation
------------------------
.. code-block:: python
obj.function.unspy()
Do your job and get out.
Check the call history
----------------------
.. code-block:: python
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
---------------------
.. code-block:: python
# 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
-------------------------------------
Mixing in ``SpyAgency`` into a unittest_-based test suite:
.. code-block:: python
# Either one of these is fine.
self.assertSpyCalled(obj.function)
self.assertTrue(obj.function.called)
# Or the inverse:
self.assertSpyNotCalled(obj.function)
self.assertFalse(obj.function.called)
Or using the pytest_ ``spy_agency`` fixture on kgb 7+:
.. code-block:: python
spy_agency.assert_spy_called(obj.function)
spy_agency.assert_spy_not_called(obj.function)
Or using standalone assertion methods on kgb 7+:
.. code-block:: python
from kgb.asserts import (assert_spy_called,
assert_spy_not_called)
assert_spy_called(obj.function)
assert_spy_not_called(obj.function)
If the function was ever called at all, this will let you know.
Check if the function was ever called with certain arguments
------------------------------------------------------------
Mixing in ``SpyAgency`` into a unittest_-based test suite:
.. code-block:: python
# Check if it was ever called with these arguments...
self.assertSpyCalledWith(obj.function, 'foo', bar='baz')
self.assertTrue(obj.function.called_with('foo', bar='baz'))
# Check a specific call...
self.assertSpyCalledWith(obj.function.calls[0], 'foo', bar='baz')
self.assertTrue(obj.function.calls[0].called_with('foo', bar='baz'))
# Check the last call...
self.assertSpyLastCalledWith(obj.function, 'foo', bar='baz')
self.assertTrue(obj.function.last_called_with('foo', bar='baz'))
# Or the inverse:
self.assertSpyNotCalledWith(obj.function, 'foo', bar='baz')
self.assertFalse(obj.function.called)
Or using the pytest_ ``spy_agency`` fixture on kgb 7+:
.. code-block:: python
spy_agency.assert_spy_called_with(obj.function, 'foo', bar='baz')
spy_agency.assert_spy_last_called_with(obj.function, 'foo', bar='baz')
spy_agency.assert_spy_not_called_with(obj.function, 'foo', bar='baz')
Or using standalone assertion methods on kgb 7+:
.. code-block:: python
from kgb.asserts import (assert_spy_called_with,
assert_spy_last_called_with,
assert_spy_not_called_with)
assert_spy_called_with(obj.function, 'foo', bar='baz')
assert_spy_last_called_with(obj.function, 'foo', bar='baz')
assert_spy_not_called_with(obj.function, 'foo', bar='baz')
The whole callkhistory 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
---------------------------------------------------
Mixing in ``SpyAgency`` into a unittest_-based test suite:
.. code-block:: python
# Check if the function ever returned a certain value...
self.assertSpyReturned(obj.function, 42)
self.assertTrue(obj.function.returned(42))
# Check a specific call...
self.assertSpyReturned(obj.function.calls[0], 42)
self.assertTrue(obj.function.calls[0].returned(42))
# Check the last call...
self.assertSpyLastReturned(obj.function, 42)
self.assertTrue(obj.function.last_returned(42))
Or using the pytest_ ``spy_agency`` fixture on kgb 7+:
.. code-block:: python
spy_agency.assert_spy_returned(obj.function, 42)
spy_agency.assert_spy_returned(obj.function.calls[0], 42)
spy_agency.assert_spy_last_returned(obj.function, 42)
Or using standalone assertion methods on kgb 7+:
.. code-block:: python
from kgb.asserts import (assert_spy_last_returned,
assert_spy_returned)
assert_spy_returned(obj.function, 42)
assert_spy_returned(obj.function.calls[0], 42)
assert_spy_last_returned(obj.function, 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
-----------------------------------------------------------
Mixing in ``SpyAgency`` into a unittest_-based test suite:
.. code-block:: python
# Check if the function ever raised a certain exception...
self.assertSpyRaised(obj.function, TypeError)
self.assertTrue(obj.function.raised(TypeError))
# Check a specific call...
self.assertSpyRaised(obj.function.calls[0], TypeError)
self.assertTrue(obj.function.calls[0].raised(TypeError))
# Check the last call...
self.assertSpyLastRaised(obj.function, TypeError)
self.assertTrue(obj.function.last_raised(TypeError))
Or using the pytest_ ``spy_agency`` fixture on kgb 7+:
.. code-block:: python
spy_agency.assert_spy_raised(obj.function, TypeError)
spy_agency.assert_spy_raised(obj.function.calls[0], TypeError)
spy_agency.assert_spy_last_raised(obj.function, TypeError)
Or using standalone assertion methods on kgb 7+:
.. code-block:: python
from kgb.asserts import (assert_spy_last_raised,
assert_spy_raised)
assert_spy_raised(obj.function, TypeError)
assert_spy_raised(obj.function.calls[0], TypeError)
assert_spy_last_raised(obj.function, TypeError)
You can also go a step further by checking the exception's message.
.. code-block:: python
# Check if the function ever raised an exception with a given message...
self.assertSpyRaisedWithMessage(
obj.function,
TypeError,
"'type' object is not iterable")
self.assertTrue(obj.function.raised_with_message(
TypeError,
"'type' object is not iterable"))
# Check a specific call...
self.assertSpyRaisedWithMessage(
obj.function.calls[0],
TypeError,
"'type' object is not iterable")
self.assertTrue(obj.function.calls[0].raised_with_message(
TypeError,
"'type' object is not iterable"))
# Check the last call...
self.assertSpyLastRaisedWithMessage(
obj.function,
TypeError,
"'type' object is not iterable")
self.assertTrue(obj.function.last_raised_with_message(
TypeError,
"'type' object is not iterable"))
Reset all the calls
-------------------
.. code-block:: python
obj.function.reset_calls()
Wipe away the call history. Nobody will know.
Call the original function
--------------------------
.. code-block:: python
result = obj.function.call_original('foo', bar='baz')
Super, super useful if you want to use ``call_fake=`` or
``@spy_agency.spy_for`` to wrap a function and track or influence some part of
it, but still want the original function to do its thing. For instance:
.. code-block:: python
stored_results = []
@spy_agency.spy_for(obj.function)
def my_fake_function(*args, **kwargs):
kwargs['bar'] = 'baz'
result = obj.function.call_original(*args, **kwargs)
stored_results.append(result)
return result
Plan a spy operation
====================
Why start from scratch when setting up a spy? Let's plan an operation.
(Spy operations are only available in kgb 6 or higher.)
Raise an exception when called
------------------------------
.. code-block:: python
spy_on(pen.emit_poison, op=kgb.SpyOpRaise(PoisonEmptyError()))
Or go nuts, have a different exception for each call (in kgb 6.1+):
.. code-block:: python
spy_on(pen.emit_poison, op=kgb.SpyOpRaiseInOrder([
PoisonEmptyError(),
Kaboom(),
MissingPenError(),
]))
Or return a value
-----------------
.. code-block:: python
spy_on(our_agent.get_identity, op=kgb.SpyOpReturn('nobody...'))
Maybe a different value for each call (in kgb 6.1+)?
.. code-block:: python
spy_on(our_agent.get_identity, op=kgb.SpyOpReturnInOrder([
'nobody...',
'who?',
'not telling...',
]))
Now for something more complicated.
Handle a call based on the arguments used
-----------------------------------------
If you're dealing with many calls to the same function, you may want to return
different values or only call the original function depending on which
arguments were passed in the call. That can be done with a ``SpyOpMatchAny``
operation.
.. code-block:: python
spy_on(traps.trigger, op=kgb.SpyOpMatchAny([
{
'args': ('hallway_lasers',),
'call_fake': _send_wolves,
},
{
'args': ('trap_tile',),
'op': SpyOpMatchInOrder([
{
'call_fake': _spill_hot_oil,
},
{
'call_fake': _drop_torch,
},
]),
},
{
'args': ('infrared_camera',),
'kwargs': {
'sector': 'underground_passage',
},
'call_original': False,
},
]))
Any unexpected calls will automatically assert.
Or require those calls in a specific order
------------------------------------------
You can combine that with requiring the calls to be in the order you want
using ``SpyOpMatchInOrder``.
.. code-block:: python
spy_on(lockbox.enter_code, op=kgb.SpyOpMatchInOrder([
{
'args': (1, 2, 3, 4, 5, 6),
'call_original': False,
},
{
'args': (9, 0, 2, 1, 0, 0),
'call_fake': _start_countdown,
},
{
'args': (42, 42, 42, 42, 42, 42),
'op': kgb.SpyOpRaise(Kaboom()),
'call_original': True,
},
{
'args': (4, 8, 15, 16, 23, 42),
'kwargs': {
'secret_button_pushed': True,
},
'call_original': True,
}
]))
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 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.
.. _mock: https://pypi.python.org/pypi/mock
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`_.
.. _open source projects: https://www.beanbaginc.com/opensource/
Raw data
{
"_id": null,
"home_page": null,
"name": "kgb",
"maintainer": null,
"docs_url": null,
"requires_python": "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,>=2.7",
"maintainer_email": null,
"keywords": "pytest, unit tests, spies",
"author": null,
"author_email": "\"Beanbag, Inc.\" <questions@beanbaginc.com>",
"download_url": "https://files.pythonhosted.org/packages/80/69/a1968b8b0deb55c42efbab961736fd07047956c0c1981ea70faf70f8d8c8/kgb-7.2.tar.gz",
"platform": null,
"description": "===============================\nkgb - Function spies for Python\n===============================\n\nEver deal with a large test suite before, monkey patching functions to figure\nout whether it was called as expected? It's a dirty job. If you're not careful,\nyou can make a mess of things. Leave behind evidence.\n\nkgb's spies will take care of that little problem for you.\n\n\nWhat are spies?\n===============\n\nSpies intercept and record calls to functions. They can report on how many times\na function was called and with what arguments. They can allow the function call\nto go through as normal, to block it, or to reroute it to another function.\n\nSpies are awesome.\n\n(If you've used Jasmine_, you know this.)\n\nSpies are like mocks, but better. You're not mocking the world. You're\nreplacing very specific function logic, or listening to functions without\naltering them. (See the FAQ below.)\n\n\n.. _Jasmine: https://jasmine.github.io/\n\n\nWhat test platforms are supported?\n==================================\n\nAnything Python-based:\n\n* unittest_\n* pytest_\n* nose_\n* nose2_\n\nYou can even use it outside of unit tests as part of your application. If you\nreally want to. (Probably don't do that.)\n\n\n.. _unittest: https://docs.python.org/3/library/unittest.html\n.. _pytest: https://pytest.org\n.. _nose: https://nose.readthedocs.io/en/latest/\n.. _nose2: https://docs.nose2.io/en/latest/\n\n\nWhere is kgb used?\n==================\n\n* `liveswot-api <https://github.com/imranariffin/liveswot-api>`_ --\n REST API Backend for liveswot\n* `phabricator-emails\n <https://github.com/mozilla-conduit/phabricator-emails>`_ --\n Mozilla's utilities for converting Phabricator feeds to e-mails\n* `projector <https://github.com/brennie/projector>`_ --\n Takes the overhead out of managing repositories and development environments\n* `ynab-sdk-python <https://github.com/andreroggeri/ynab-sdk-python>`_ --\n Python implementation of the YNAB API\n\nPlus our own products:\n\n* `Django Evolution <https://django-evolution.readthedocs.io/>`_ --\n An alternative approach to Django database migrations\n* `Djblets <https://github.com/djblets/djblets/>`_ --\n An assortment of utilities and add-ons for managing large Django projects\n* `Review Board <https://www.reviewboard.org/>`_ --\n Our open source, extensible code review product\n* `RBCommons <https://rbcommons.com>`_ --\n Our hosted code review service\n* `RBTools <https://www.reviewboard.org/downloads/rbtools/>`_ --\n Command line tools for Review Board\n* `Power Pack <https://www.reviewboard.org/powerpack/>`_ --\n Document review, reports, and enterprise SCM integrations for Review Board\n* `Review Bot <https://www.reviewboard.org/downloads/reviewbot/>`_ --\n Automated code review add-on for Review Board\n\nIf you use kgb, let us know and we'll add you!\n\n\nInstalling kgb\n==============\n\nBefore you can use kgb, you need to install it. You can do this by typing::\n\n $ pip install kgb\n\nkgb supports Python 2.7 and 3.6 through 3.11, both CPython and PyPy.\n\n\nSpying for fun and profit\n=========================\n\nSpying is really easy. There are four main ways to initiate a spy.\n\n\n1. Creating a SpyAgency\n-----------------------\n\nA SpyAgency manages all your spies. You can create as many or as few as you\nwant. Generally, you'll create one per unit test run. Then you'll call\n``spy_on()``, passing in the function you want.\n\n.. code-block:: python\n\n from kgb import SpyAgency\n\n\n def test_mind_control_device():\n mcd = MindControlDevice()\n agency = SpyAgency()\n agency.spy_on(mcd.assassinate, call_fake=give_hugs)\n\n\n2. Mixing a SpyAgency into your tests\n-------------------------------------\n\nA ``SpyAgency`` can be mixed into your unittest_-based test suite, making\nit super easy to spy all over the place, discretely, without resorting to a\nseparate agency. (We call this the \"inside job.\")\n\n.. code-block:: python\n\n from kgb import SpyAgency\n\n\n # Using Python's unittest:\n class TopSecretTests(SpyAgency, unittest.TestCase):\n def test_weather_control(self):\n weather = WeatherControlDevice()\n self.spy_on(weather.start_raining)\n\n\n # Using pytest with the \"spy_agency\" fixture (kgb 7+):\n def test_weather_control(spy_agency):\n weather = WeatherControlDevice()\n spy_agency.spy_on(weather.start_raining)\n\n\n3. Using a decorator\n--------------------\n\nIf you're creating a spy that calls a fake function, you can simplify some\nthings by using the ``spy_for`` decorator:\n\n\n.. code-block:: python\n\n from kgb import SpyAgency\n\n\n # Using Python's unittest:\n class TopSecretTests(SpyAgency, unittest.TestCase):\n def test_doomsday_device(self):\n dd = DoomsdayDevice()\n\n @self.spy_for(dd.kaboom)\n def _save_world(*args, **kwargs)\n print('Sprinkles and ponies!')\n\n # Give it your best shot, doomsday device.\n dd.kaboom()\n\n\n # Using pytest:\n def test_doomsday_device(spy_agency):\n dd = DoomsdayDevice()\n\n @spy_agency.spy_for(dd.kaboom)\n def _save_world(*args, **kwargs)\n print('Sprinkles and ponies!')\n\n # Give it your best shot, doomsday device.\n dd.kaboom()\n\n\n4. Using a context manager\n--------------------------\n\nIf you just want a spy for a quick job, without all that hassle of a full\nagency, just use the ``spy_on`` context manager, like so:\n\n.. code-block:: python\n\n from kgb import spy_on\n\n\n def test_the_bomb(self):\n bomb = Bomb()\n\n with spy_on(bomb.explode, call_original=False):\n # This won't explode. Phew.\n bomb.explode()\n\n\nA spy's abilities\n=================\n\nA spy can do many things. The first thing you need to do is figure out how you\nwant to use the spy.\n\n\nCreating a spy that calls the original function\n-----------------------------------------------\n\n.. code-block:: python\n\n spy_agency.spy_on(obj.function)\n\n\nWhen your spy is called, the original function will be called as well.\nIt won't even know you were there.\n\n\nCreating a spy that blocks the function call\n--------------------------------------------\n\n.. code-block:: python\n\n spy_agency.spy_on(obj.function, call_original=False)\n\n\nUseful if you want to know that a function was called, but don't want the\noriginal function to actually get the call.\n\n\nCreating a spy that reroutes to a fake function\n-----------------------------------------------\n\n.. code-block:: python\n\n def _my_fake_function(some_param, *args, **kwargs):\n ...\n\n spy_agency.spy_on(obj.function, call_fake=my_fake_function)\n\n # Or, in kgb 6+\n @spy_agency.spy_for(obj.function)\n def _my_fake_function(some_param, *args, **kwargs):\n ...\n\n\nFake the return values or operations without anybody knowing.\n\n\nStopping a spy operation\n------------------------\n\n.. code-block:: python\n\n obj.function.unspy()\n\n\nDo your job and get out.\n\n\nCheck the call history\n----------------------\n\n.. code-block:: python\n\n for call in obj.function.calls:\n print(calls.args, calls.kwargs)\n\n\nSee how many times your spy's intercepted a function call, and what was passed.\n\n\nCheck a specific call\n---------------------\n\n.. code-block:: python\n\n # Check the latest call...\n print(obj.function.last_call.args)\n print(obj.function.last_call.kwargs)\n print(obj.function.last_call.return_value)\n print(obj.function.last_call.exception)\n\n # For an older call...\n print(obj.function.calls[0].args)\n print(obj.function.calls[0].kwargs)\n print(obj.function.calls[0].return_value)\n print(obj.function.calls[0].exception)\n\n\nAlso a good way of knowing whether it's even been called. ``last_call`` will\nbe ``None`` if nobody's called yet.\n\n\nCheck if the function was ever called\n-------------------------------------\n\nMixing in ``SpyAgency`` into a unittest_-based test suite:\n\n.. code-block:: python\n\n # Either one of these is fine.\n self.assertSpyCalled(obj.function)\n self.assertTrue(obj.function.called)\n\n # Or the inverse:\n self.assertSpyNotCalled(obj.function)\n self.assertFalse(obj.function.called)\n\n\nOr using the pytest_ ``spy_agency`` fixture on kgb 7+:\n\n.. code-block:: python\n\n spy_agency.assert_spy_called(obj.function)\n spy_agency.assert_spy_not_called(obj.function)\n\n\nOr using standalone assertion methods on kgb 7+:\n\n.. code-block:: python\n\n from kgb.asserts import (assert_spy_called,\n assert_spy_not_called)\n\n assert_spy_called(obj.function)\n assert_spy_not_called(obj.function)\n\n\nIf the function was ever called at all, this will let you know.\n\n\nCheck if the function was ever called with certain arguments\n------------------------------------------------------------\n\nMixing in ``SpyAgency`` into a unittest_-based test suite:\n\n.. code-block:: python\n\n # Check if it was ever called with these arguments...\n self.assertSpyCalledWith(obj.function, 'foo', bar='baz')\n self.assertTrue(obj.function.called_with('foo', bar='baz'))\n\n # Check a specific call...\n self.assertSpyCalledWith(obj.function.calls[0], 'foo', bar='baz')\n self.assertTrue(obj.function.calls[0].called_with('foo', bar='baz'))\n\n # Check the last call...\n self.assertSpyLastCalledWith(obj.function, 'foo', bar='baz')\n self.assertTrue(obj.function.last_called_with('foo', bar='baz'))\n\n # Or the inverse:\n self.assertSpyNotCalledWith(obj.function, 'foo', bar='baz')\n self.assertFalse(obj.function.called)\n\n\nOr using the pytest_ ``spy_agency`` fixture on kgb 7+:\n\n.. code-block:: python\n\n spy_agency.assert_spy_called_with(obj.function, 'foo', bar='baz')\n spy_agency.assert_spy_last_called_with(obj.function, 'foo', bar='baz')\n spy_agency.assert_spy_not_called_with(obj.function, 'foo', bar='baz')\n\n\nOr using standalone assertion methods on kgb 7+:\n\n.. code-block:: python\n\n from kgb.asserts import (assert_spy_called_with,\n assert_spy_last_called_with,\n assert_spy_not_called_with)\n\n assert_spy_called_with(obj.function, 'foo', bar='baz')\n assert_spy_last_called_with(obj.function, 'foo', bar='baz')\n assert_spy_not_called_with(obj.function, 'foo', bar='baz')\n\n\nThe whole callkhistory will be searched. You can provide the entirety of the\narguments passed to the function, or you can provide a subset. You can pass\npositional arguments as-is, or pass them by name using keyword arguments.\n\nRecorded calls always follow the function's original signature, so even if a\nkeyword argument was passed a positional value, it will be recorded as a\nkeyword argument.\n\n\nCheck if the function ever returned a certain value\n---------------------------------------------------\n\nMixing in ``SpyAgency`` into a unittest_-based test suite:\n\n.. code-block:: python\n\n # Check if the function ever returned a certain value...\n self.assertSpyReturned(obj.function, 42)\n self.assertTrue(obj.function.returned(42))\n\n # Check a specific call...\n self.assertSpyReturned(obj.function.calls[0], 42)\n self.assertTrue(obj.function.calls[0].returned(42))\n\n # Check the last call...\n self.assertSpyLastReturned(obj.function, 42)\n self.assertTrue(obj.function.last_returned(42))\n\n\nOr using the pytest_ ``spy_agency`` fixture on kgb 7+:\n\n.. code-block:: python\n\n spy_agency.assert_spy_returned(obj.function, 42)\n spy_agency.assert_spy_returned(obj.function.calls[0], 42)\n spy_agency.assert_spy_last_returned(obj.function, 42)\n\n\nOr using standalone assertion methods on kgb 7+:\n\n.. code-block:: python\n\n from kgb.asserts import (assert_spy_last_returned,\n assert_spy_returned)\n\n assert_spy_returned(obj.function, 42)\n assert_spy_returned(obj.function.calls[0], 42)\n assert_spy_last_returned(obj.function, 42)\n\n\nHandy for checking if some function ever returned what you expected it to, when\nyou're not calling that function yourself.\n\n\nCheck if a function ever raised a certain type of exception\n-----------------------------------------------------------\n\nMixing in ``SpyAgency`` into a unittest_-based test suite:\n\n.. code-block:: python\n\n # Check if the function ever raised a certain exception...\n self.assertSpyRaised(obj.function, TypeError)\n self.assertTrue(obj.function.raised(TypeError))\n\n # Check a specific call...\n self.assertSpyRaised(obj.function.calls[0], TypeError)\n self.assertTrue(obj.function.calls[0].raised(TypeError))\n\n # Check the last call...\n self.assertSpyLastRaised(obj.function, TypeError)\n self.assertTrue(obj.function.last_raised(TypeError))\n\n\nOr using the pytest_ ``spy_agency`` fixture on kgb 7+:\n\n.. code-block:: python\n\n spy_agency.assert_spy_raised(obj.function, TypeError)\n spy_agency.assert_spy_raised(obj.function.calls[0], TypeError)\n spy_agency.assert_spy_last_raised(obj.function, TypeError)\n\n\nOr using standalone assertion methods on kgb 7+:\n\n.. code-block:: python\n\n from kgb.asserts import (assert_spy_last_raised,\n assert_spy_raised)\n\n assert_spy_raised(obj.function, TypeError)\n assert_spy_raised(obj.function.calls[0], TypeError)\n assert_spy_last_raised(obj.function, TypeError)\n\n\nYou can also go a step further by checking the exception's message.\n\n.. code-block:: python\n\n # Check if the function ever raised an exception with a given message...\n self.assertSpyRaisedWithMessage(\n obj.function,\n TypeError,\n \"'type' object is not iterable\")\n self.assertTrue(obj.function.raised_with_message(\n TypeError,\n \"'type' object is not iterable\"))\n\n # Check a specific call...\n self.assertSpyRaisedWithMessage(\n obj.function.calls[0],\n TypeError,\n \"'type' object is not iterable\")\n self.assertTrue(obj.function.calls[0].raised_with_message(\n TypeError,\n \"'type' object is not iterable\"))\n\n # Check the last call...\n self.assertSpyLastRaisedWithMessage(\n obj.function,\n TypeError,\n \"'type' object is not iterable\")\n self.assertTrue(obj.function.last_raised_with_message(\n TypeError,\n \"'type' object is not iterable\"))\n\n\nReset all the calls\n-------------------\n\n.. code-block:: python\n\n obj.function.reset_calls()\n\n\nWipe away the call history. Nobody will know.\n\n\nCall the original function\n--------------------------\n\n.. code-block:: python\n\n result = obj.function.call_original('foo', bar='baz')\n\n\nSuper, super useful if you want to use ``call_fake=`` or\n``@spy_agency.spy_for`` to wrap a function and track or influence some part of\nit, but still want the original function to do its thing. For instance:\n\n.. code-block:: python\n\n stored_results = []\n\n @spy_agency.spy_for(obj.function)\n def my_fake_function(*args, **kwargs):\n kwargs['bar'] = 'baz'\n result = obj.function.call_original(*args, **kwargs)\n stored_results.append(result)\n\n return result\n\n\nPlan a spy operation\n====================\n\nWhy start from scratch when setting up a spy? Let's plan an operation.\n\n(Spy operations are only available in kgb 6 or higher.)\n\n\nRaise an exception when called\n------------------------------\n\n.. code-block:: python\n\n spy_on(pen.emit_poison, op=kgb.SpyOpRaise(PoisonEmptyError()))\n\nOr go nuts, have a different exception for each call (in kgb 6.1+):\n\n.. code-block:: python\n\n spy_on(pen.emit_poison, op=kgb.SpyOpRaiseInOrder([\n PoisonEmptyError(),\n Kaboom(),\n MissingPenError(),\n ]))\n\n\nOr return a value\n-----------------\n\n.. code-block:: python\n\n spy_on(our_agent.get_identity, op=kgb.SpyOpReturn('nobody...'))\n\nMaybe a different value for each call (in kgb 6.1+)?\n\n.. code-block:: python\n\n spy_on(our_agent.get_identity, op=kgb.SpyOpReturnInOrder([\n 'nobody...',\n 'who?',\n 'not telling...',\n ]))\n\n\nNow for something more complicated.\n\n\nHandle a call based on the arguments used\n-----------------------------------------\n\nIf you're dealing with many calls to the same function, you may want to return\ndifferent values or only call the original function depending on which\narguments were passed in the call. That can be done with a ``SpyOpMatchAny``\noperation.\n\n.. code-block:: python\n\n spy_on(traps.trigger, op=kgb.SpyOpMatchAny([\n {\n 'args': ('hallway_lasers',),\n 'call_fake': _send_wolves,\n },\n {\n 'args': ('trap_tile',),\n 'op': SpyOpMatchInOrder([\n {\n 'call_fake': _spill_hot_oil,\n },\n {\n 'call_fake': _drop_torch,\n },\n ]),\n },\n {\n 'args': ('infrared_camera',),\n 'kwargs': {\n 'sector': 'underground_passage',\n },\n 'call_original': False,\n },\n ]))\n\nAny unexpected calls will automatically assert.\n\n\nOr require those calls in a specific order\n------------------------------------------\n\nYou can combine that with requiring the calls to be in the order you want\nusing ``SpyOpMatchInOrder``.\n\n.. code-block:: python\n\n spy_on(lockbox.enter_code, op=kgb.SpyOpMatchInOrder([\n {\n 'args': (1, 2, 3, 4, 5, 6),\n 'call_original': False,\n },\n {\n 'args': (9, 0, 2, 1, 0, 0),\n 'call_fake': _start_countdown,\n },\n {\n 'args': (42, 42, 42, 42, 42, 42),\n 'op': kgb.SpyOpRaise(Kaboom()),\n 'call_original': True,\n },\n {\n 'args': (4, 8, 15, 16, 23, 42),\n 'kwargs': {\n 'secret_button_pushed': True,\n },\n 'call_original': True,\n }\n ]))\n\n\nFAQ\n===\n\nDoesn't this just do what mock does?\n------------------------------------\n\nkgb's spies and mock_'s patching are very different from each other. When\npatching using mock, you're simply replacing a method on a class with\nsomething that looks like a method, and that works great except you're limited\nto methods on classes. You can't override a top-level function, like\n``urllib2.urlopen``.\n\nkgb spies leave the function or method where it is. What it *does* do is\nreplace the *bytecode* of the function, intercepting calls on a very low\nlevel, recording everything about it, and then passing on the call to the\noriginal function or your replacement function. It's pretty powerful, and\nallows you to listen to or override calls you normally would have no control\nover.\n\n.. _mock: https://pypi.python.org/pypi/mock\n\n\nWhat?! There's no way that's stable.\n------------------------------------\n\nIt is! It really is! We've been using it for years across a wide variety of\ncodebases. It's pretty amazing.\n\nPython actually allows this. We're not scanning your RAM and doing terrible\nthings with it, or something like that. Every function or method in Python has\na ``func_code`` (Python 2) or ``__code__`` (Python 3) attribute, which is\nmutable. We can go in and replace the bytecode with something compatible with\nthe original function.\n\nHow we actually do that, well, that's complicated, and you may not want to\nknow.\n\n\nDoes this work with PyPy?\n-------------------------\n\nI'm going to level with you, I was going to say \"hell no!\", and then decided\nto give it a try.\n\nHell yes! (But only accidentally. YMMV... We'll try to officially support this\nlater.)\n\n\nWhat else do you build?\n-----------------------\n\nLots of things. Check out some of our other `open source projects`_.\n\n.. _open source projects: https://www.beanbaginc.com/opensource/\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Utilities for spying on function calls in unit tests.",
"version": "7.2",
"project_urls": {
"Documentation": "https://github.com/beanbaginc/kgb",
"Homepage": "https://github.com/beanbaginc/kgb",
"Repository": "https://github.com/beanbaginc/kgb"
},
"split_keywords": [
"pytest",
" unit tests",
" spies"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "a67d002c8de97a3f65ab7c006b815252b3fcb708961af538ceaead08815de79f",
"md5": "f8260b0f8c63f5180e094333d65d736c",
"sha256": "be444f6a2580f1749af06cf525a1fc7cbb86865785e3c84d304e379bd693672e"
},
"downloads": -1,
"filename": "kgb-7.2-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "f8260b0f8c63f5180e094333d65d736c",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,>=2.7",
"size": 58311,
"upload_time": "2024-11-04T02:57:28",
"upload_time_iso_8601": "2024-11-04T02:57:28.886969Z",
"url": "https://files.pythonhosted.org/packages/a6/7d/002c8de97a3f65ab7c006b815252b3fcb708961af538ceaead08815de79f/kgb-7.2-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "8069a1968b8b0deb55c42efbab961736fd07047956c0c1981ea70faf70f8d8c8",
"md5": "f52134255331d1b26e0d6627d43a0159",
"sha256": "58dcae53a843a7121829e187dfcc13b80785a8a66ca459705371cb74cff8f155"
},
"downloads": -1,
"filename": "kgb-7.2.tar.gz",
"has_sig": false,
"md5_digest": "f52134255331d1b26e0d6627d43a0159",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,>=2.7",
"size": 61228,
"upload_time": "2024-11-04T02:57:30",
"upload_time_iso_8601": "2024-11-04T02:57:30.866794Z",
"url": "https://files.pythonhosted.org/packages/80/69/a1968b8b0deb55c42efbab961736fd07047956c0c1981ea70faf70f8d8c8/kgb-7.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-04 02:57:30",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "beanbaginc",
"github_project": "kgb",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"tox": true,
"lcname": "kgb"
}