Last active
August 29, 2015 14:11
-
-
Save richlanc/9c0472f00aeb4c3a7237 to your computer and use it in GitHub Desktop.
QueryMock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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