Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created September 9, 2013 16:06
Show Gist options
  • Save podhmo/6497807 to your computer and use it in GitHub Desktop.
Save podhmo/6497807 to your computer and use it in GitHub Desktop.
# -*- coding:utf-8 -*-
from mock import patch
from target import whattime_is_it, notify
def greeting(name):
hour = whattime_is_it()
if 0 <= hour <= 4:
fmt = "{name}, Goto Bed!!"
notify(fmt.format(name=name))
@patch("__main__.notify") #patch
@patch("__main__.whattime_is_it") #patch
def test(m0,m1):
m0.return_value = 1 #mimic(fake)
greeting("Foo")
m1.assert_called_with("Foo, Goto Bed!!") # captured
# -*- coding:utf-8 -*-
def _dot_lookup(thing, comp, import_path):
try:
return getattr(thing, comp)
except AttributeError:
__import__(import_path)
return getattr(thing, comp)
def _importer(target):
components = target.split('.')
import_path = components.pop(0)
thing = __import__(import_path)
for comp in components:
import_path += ".%s" % comp
thing = _dot_lookup(thing,
comp, import_path)
return thing
# -*- coding:utf-8 -*-
class MyMock(object):
def __init__(self, name='*'):
self.name, self.call_args = name, None
def __getattr__(self, k):
c = self.__class__(name=k)
setattr(self, k, c)
return c
def __call__(self, *args, **kw):
if hasattr(self, "return_value"):
self.call_args = (args, kw)
return self.return_value
raise Exception("not callable")
def assert_called_with(self, *args, **kw):
vls = self.call_args
if vls is None:
raise AssertionError("not called")
if vls != (args, kw):
raise AssertionError("! {}".format(vls))
# -*- coding:utf-8 -*-
from importer import _importer
from mymock import MyMock
class Patch(object):
def __init__(self, target, new, attr):
self.target, self.attr = target, attr
self.new = new
def __enter__(self):
self._orig = getattr(self.target, self.attr)
new = self.new(name=self.attr)
setattr(self.target, self.attr, new)
return new
def __exit__(self, type, val, tb):
setattr(self.target, self.attr, self._orig)
del self._orig
def patch(namespace, new=MyMock):
target, attr = namespace.rsplit(".", 1)
return Patch(_importer(target), new, attr)
# -*- coding:utf-8 -*-
def whattime_is_it():
from datetime import datetime
return datetime.now()
def notify(message):
raise Exception(message)
# -*- coding:utf-8 -*-
from patch import patch
from target import whattime_is_it, notify
def greeting(name):
hour = whattime_is_it()
if 0 <= hour <= 4:
fmt = "{name}, Goto Bed!!"
notify(fmt.format(name=name))
# hmm.. not decorator
with patch("__main__.whattime_is_it") as m0:
m0.return_value = 1
with patch("__main__.notify") as m1:
greeting("Foo")
m1.assert_called_with("Foo, Goto Bed!!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment