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):
48
def setUp(self, obj, patches):
49
super(CharmTestCase, self).setUp()
50
self.patches = patches
52
self.test_config = TestConfig()
53
self.test_relation = TestRelation()
56
def patch(self, method):
57
_m = patch.object(self.obj, method)
59
self.addCleanup(_m.stop)
63
for method in self.patches:
64
setattr(self, method, self.patch(method))
67
class TestConfig(object):
69
self.config = get_default_config()
71
def get(self, attr=None):
75
return self.config[attr]
82
def set(self, attr, value):
83
if attr not in self.config:
85
self.config[attr] = value
88
class TestRelation(object):
89
def __init__(self, relation_data={}):
90
self.relation_data = relation_data
92
def set(self, relation_data):
93
self.relation_data = relation_data
95
def get(self, attr=None, unit=None, rid=None):
97
return self.relation_data
98
elif attr in self.relation_data:
99
return self.relation_data[attr]
105
'''Patch open() to allow mocking both open() itself and the file that is
108
Yields the mock for "open" and "file", respectively.'''
109
mock_open = MagicMock(spec=open)
110
mock_file = MagicMock(spec=file)
113
def stub_open(*args, **kwargs):
114
mock_open(*args, **kwargs)
117
with patch('__builtin__.open', stub_open):
118
yield mock_open, mock_file