Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@richlanc
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richlanc/9c0472f00aeb4c3a7237 to your computer and use it in GitHub Desktop.
Save richlanc/9c0472f00aeb4c3a7237 to your computer and use it in GitHub Desktop.
QueryMock
class QueryMock(object):
""" Beats having to mock query.return_all.filter...
Usage:
>>> qm = QueryMock([("all", "ERROR")])
>>> getDatabaseSession = MagicMock(return_value=qm)
>>> errors = (
... getDatabaseSession()
... .query(ShowTime)
... .filter(ShowTime.start >= start)
... .filter(ShowTime.end < end)
... .all()
... )
>>> print errors
ERROR
"""
def __init__(self, func_mock):
"""
:param func_mock: Iterable of tuples, where the first element
is the name of the function name that should return the value
of the second element. See the example in the class doc for more
information.
"""
self.func_mock = func_mock
def __getattribute__(self, item):
if "func_mock" == item:
return object.__getattribute__(self, item)
for (func, func_return) in self.func_mock:
if item == func:
return lambda: func_return
else:
return self
def __call__(self, *args, **kwargs):
return self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment