Skip to content

Instantly share code, notes, and snippets.

@gurunars
Last active May 26, 2017 10:52
Show Gist options
  • Save gurunars/c9206c9eb9e5e90bac3bedab3df4261b to your computer and use it in GitHub Desktop.
Save gurunars/c9206c9eb9e5e90bac3bedab3df4261b to your computer and use it in GitHub Desktop.
Python unit test with multipatching
from abc import ABCMeta, abstractproperty
import unittest
import mock
class BaseTest(unittest.TestCase):
__metaclass__ = ABCMeta
@abstractproperty
def MODULE_NAME(self):
pass
@classmethod
def with_module(cls, module_name):
class ModuledBaseTest(cls):
MODULE_NAME = module_name
return ModuledBaseTest
def patch(self, what, with_what=None):
target = mock.patch(self.MODULE_NAME + "." + what, with_what or mock.Mock())
patch = target.start()
self.addCleanup(target.stop)
return patch
from base_test import BaseTest
class SampleTest(BaseTest.with_module("some.module.name")):
def setUp(self):
super(SampleTest, self).setUp()
self.patch("requests")
self.patch("sys")
def test_sth(self):
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment