Last active
December 23, 2015 17:39
-
-
Save jakab922/6670760 to your computer and use it in GitHub Desktop.
Declarative mock definitions for tests on a Test class.
This file contains hidden or 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
from unittest import TestCase | |
from mock import patch | |
class IDontNeedTheRest(Exception): | |
pass | |
DEBUG = False | |
def make_patches(owner, names): | |
patches = [] | |
for name in names: | |
if DEBUG: | |
print name | |
p = patch(name) | |
patches.append(p) | |
postfix = "" | |
counter = 0 | |
base_name = name.split(".")[-1] | |
while hasattr(owner, base_name + postfix): | |
counter += 1 | |
postfix = "_" + str(counter) | |
setattr(owner, base_name + postfix, p.start()) | |
return patches | |
class PatchingTestCase(TestCase): | |
to_patch = [] | |
main_function = None | |
def _run(self, *args, **kwargs): | |
try: | |
return self.main_function(*args, **kwargs) | |
except IDontNeedTheRest: | |
pass | |
return | |
def setUp(self): | |
to_patch = [] | |
for base_module, objects in self.to_patch: | |
for obj in objects: | |
to_patch.append("%s.%s" % (base_module, obj)) | |
self.patches = make_patches(self, to_patch) | |
def tearDown(self): | |
for p in self.patches: | |
p.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment