6
from contextlib import contextmanager
7
from mock import patch, MagicMock
12
Walk backwords from __file__ looking for config.yaml, load and return the
18
d = os.path.dirname(f)
19
if os.path.isfile(os.path.join(d, 'config.yaml')):
20
config = os.path.join(d, 'config.yaml')
25
logging.error('Could not find config.yaml in any parent directory '
29
return yaml.safe_load(open(config).read())['options']
32
def get_default_config():
34
Load default charm config from config.yaml return as a dict.
35
If no default is set in config.yaml, its value is None.
38
config = load_config()
39
for k, v in config.iteritems():
41
default_config[k] = v['default']
43
default_config[k] = None
47
class CharmTestCase(unittest.TestCase):
49
def setUp(self, obj, patches):
50
super(CharmTestCase, self).setUp()
51
self.patches = patches
53
self.test_config = TestConfig()
54
self.test_relation = TestRelation()
57
def patch(self, method):
58
_m = patch.object(self.obj, method)
60
self.addCleanup(_m.stop)
64
for method in self.patches:
65
setattr(self, method, self.patch(method))
68
class TestConfig(object):
71
self.config = get_default_config()
73
def get(self, attr=None):
77
return self.config[attr]
84
def set(self, attr, value):
85
if attr not in self.config:
87
self.config[attr] = value
90
class TestRelation(object):
92
def __init__(self, relation_data={}):
93
self.relation_data = relation_data
95
def set(self, relation_data):
96
self.relation_data = relation_data
98
def get(self, attr=None, unit=None, rid=None):
100
return self.relation_data
101
elif attr in self.relation_data:
102
return self.relation_data[attr]
108
'''Patch open() to allow mocking both open() itself and the file that is
111
Yields the mock for "open" and "file", respectively.'''
112
mock_open = MagicMock(spec=open)
113
mock_file = MagicMock(spec=file)
116
def stub_open(*args, **kwargs):
117
mock_open(*args, **kwargs)
120
with patch('__builtin__.open', stub_open):
121
yield mock_open, mock_file