A quick and dirty way to turn your existing classes into spies.
I very often create spies for my tests by wrapping an interface around a list, eg.
class FakeEmailSender(list):
def send(self, address: str, message: str) -> None:
self.append((address, message))
def test_when_a_customer_signs_up():
sender = FakeEmailSender()
handler = SignupHandler(sender)
handler("[email protected]", "password")
assert (("[email protected]", "welcome to the website")) in sender
Sometimes this is a little fiddly, particularly if you need to spy on a hierarchy of objects. Spyfi, pronounced "spiffy", is a quick way to instrument a python object graph and capture calls made to it.
You can install Spyfi via pip from PyPI:
$ pip install spyfi
from spyfi import Spy
class Thing:
def __init__(self, colour):
self.colour = colour
def say_hello(self, message):
print(f"Hello, I am a {self.colour} thing: {message})
class ThingFactory:
def make_thing(self, colour:str) -> Thing:
return Thing(colour)
def test_thing_messages():
# Spiffy takes any old object and wraps its methods
# so that an arbitrary callback receives args and kwargs.
# In this case, we're appending all calls to a list.
spy = Spy(ThingFactory())
# The returned object is otherwise unchanged. `factory` is a real
# ThingFactory and behaves as normal.
factory = spy.target
factory.make_thing("blue").say_hello("I like python")
# Since we have access to the calls list, we can assert that
# particular methods were called with the right data.
assert len(spy.calls) == 2
assert calls[0].method == "make_thing"
assert calls[0].args == ("blue",)
# Spyfi includes a helper method to make assertions easier
assert spy.has("say_hello")
assert spy.has("say_hello", "I like python")
Contributions are very welcome. To learn more, see the Contributor Guide.
Distributed under the terms of the MIT license, Spyfi is free and open source software.
If you encounter any problems, please file an issue along with a detailed description.
This project was generated from @cjolowicz's Hypermodern Python Cookiecutter template.