6
from contextlib import contextmanager
7
from mock import patch, MagicMock
9
patch('charmhelpers.contrib.openstack.utils.set_os_workload_status').start()
10
patch('charmhelpers.core.hookenv.status_set').start()
15
Walk backwords from __file__ looking for config.yaml, load and return the
21
d = os.path.dirname(f)
22
if os.path.isfile(os.path.join(d, 'config.yaml')):
23
config = os.path.join(d, 'config.yaml')
28
logging.error('Could not find config.yaml in any parent directory '
32
return yaml.safe_load(open(config).read())['options']
35
def get_default_config():
37
Load default charm config from config.yaml return as a dict.
38
If no default is set in config.yaml, its value is None.
41
config = load_config()
42
for k, v in config.iteritems():
44
default_config[k] = v['default']
46
default_config[k] = None
50
class CharmTestCase(unittest.TestCase):
52
def setUp(self, obj, patches):
53
super(CharmTestCase, self).setUp()
54
self.patches = patches
56
self.test_config = TestConfig()
57
self.test_relation = TestRelation()
60
def patch(self, method):
61
_m = patch.object(self.obj, method)
63
self.addCleanup(_m.stop)
67
for method in self.patches:
68
setattr(self, method, self.patch(method))
71
class TestConfig(object):
74
self.config = get_default_config()
76
def get(self, attr=None):
80
return self.config[attr]
87
def set(self, attr, value):
88
if attr not in self.config:
90
self.config[attr] = value
93
class TestRelation(object):
95
def __init__(self, relation_data={}):
96
self.relation_data = relation_data
98
def set(self, relation_data):
99
self.relation_data = relation_data
101
def get(self, attribute=None, unit=None, rid=None):
102
if attribute is None:
103
return self.relation_data
104
elif attribute in self.relation_data:
105
return self.relation_data[attribute]
111
'''Patch open() to allow mocking both open() itself and the file that is
114
Yields the mock for "open" and "file", respectively.'''
115
mock_open = MagicMock(spec=open)
116
mock_file = MagicMock(spec=file)
119
def stub_open(*args, **kwargs):
120
mock_open(*args, **kwargs)
123
with patch('__builtin__.open', stub_open):
124
yield mock_open, mock_file