3d07e20e95
The mock third party library was needed for mock support in py2 runtimes. Since we now only support py36 and later, we can use the standard lib unittest.mock module instead. Note that https://github.com/openstack/charms.openstack is used during tests and he need `mock`, unfortunatelly it doesn't declare `mock` in its requirements so it retrieve mock from other charm project (cross dependency). So we depend on charms.openstack first and when Ib1ed5b598a52375e29e247db9ab4786df5b6d142 will be merged then CI will pass without errors. Depends-On: Ib1ed5b598a52375e29e247db9ab4786df5b6d142 Change-Id: I1d7de2bd4d704ffc331fdeacea725e903890f296 (cherry picked from commit1de27bc18f
) (cherry picked from commit946ae6b1d2
) (cherry picked from commitf1f2f405d4
)
55 lines
1.7 KiB
Python
55 lines
1.7 KiB
Python
from unittest import mock
|
|
import unittest
|
|
|
|
|
|
class CharmTestCase(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
self._patches = {}
|
|
self._patches_start = {}
|
|
|
|
def tearDown(self):
|
|
for k, v in self._patches.items():
|
|
v.stop()
|
|
setattr(self, k, None)
|
|
self._patches = None
|
|
self._patches_start = None
|
|
|
|
def _patch(self, method):
|
|
_m = unittest.mock.patch.object(self.obj, method)
|
|
mock = _m.start()
|
|
self.addCleanup(_m.stop)
|
|
return mock
|
|
|
|
def patch_all(self):
|
|
for method in self.patches:
|
|
setattr(self, method, self._patch(method))
|
|
|
|
def patch_object(self, obj, attr, return_value=None, name=None, new=None,
|
|
**kwargs):
|
|
if name is None:
|
|
name = attr
|
|
if new is not None:
|
|
mocked = mock.patch.object(obj, attr, new=new, **kwargs)
|
|
else:
|
|
mocked = mock.patch.object(obj, attr, **kwargs)
|
|
self._patches[name] = mocked
|
|
started = mocked.start()
|
|
if new is None:
|
|
started.return_value = return_value
|
|
self._patches_start[name] = started
|
|
setattr(self, name, started)
|
|
|
|
def patch(self, item, return_value=None, name=None, new=None, **kwargs):
|
|
if name is None:
|
|
raise RuntimeError("Must pass 'name' to .patch()")
|
|
if new is not None:
|
|
mocked = mock.patch(item, new=new, **kwargs)
|
|
else:
|
|
mocked = mock.patch(item, **kwargs)
|
|
self._patches[name] = mocked
|
|
started = mocked.start()
|
|
if new is None:
|
|
started.return_value = return_value
|
|
self._patches_start[name] = started
|