This repository has been archived by the owner on Oct 3, 2019. It is now read-only.
/
test_bases_mappable.py
290 lines (225 loc) · 7.85 KB
/
test_bases_mappable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python
# pylint:disable=W0201,W0613,W0212,R,C
"""Unit tests for the `base.mappable` module."""
import pytest
import logging
from unittest.mock import Mock
import yorm
from yorm.bases import Mappable
from yorm.mapper import get_mapper, Mapper
from yorm.converters import String, Integer, Boolean, List, Dictionary
from . import strip
class MockMapper(Mapper):
"""Mapped file with stubbed file IO."""
def __init__(self, obj, path, attrs):
super().__init__(obj, path, attrs)
self._mock_file = None
self._mock_modified = True
self.exists = True
def _read(self):
text = self._mock_file
logging.debug("mock read:\n%s", text.strip())
return text
def _write(self, text):
logging.debug("mock write:\n%s", text.strip())
self._mock_file = text
self.modified = True
@property
def modified(self):
return self._mock_modified
@modified.setter
def modified(self, changes): # pylint: disable=W0221
self._mock_modified = changes
# sample classes #########################################################
@yorm.attr(all=Integer)
class IntegerList(List):
"""List of integers."""
@yorm.attr(status=Boolean)
class StatusDictionary(Dictionary):
"""Dictionary of statuses."""
class SampleMappable(Mappable):
"""Sample mappable class with hard-coded settings."""
def __init__(self):
self.yorm_mapper = None
logging.debug("initializing sample...")
self.var1 = None
self.var2 = None
self.var3 = None
self.var4 = None
self.var5 = None
logging.debug("sample initialized")
path = "mock/path/to/sample.yml"
attrs = {'var1': String,
'var2': Integer,
'var3': Boolean,
'var4': IntegerList,
'var5': StatusDictionary}
self.yorm_mapper = MockMapper(self, path, attrs)
self.yorm_mapper.store()
def __repr__(self):
return "<sample {}>".format(id(self))
# tests ##################################################################
class TestGetMapper:
"""Unit tests for the `get_mapper` function."""
def test_yorm_mapper_required(self):
sample = SampleMappable()
del sample.yorm_mapper
with pytest.raises(AttributeError):
print(get_mapper(sample))
class TestMappable:
"""Unit tests for the `Mappable` class."""
def setup_method(self, method):
"""Create an mappable instance for tests."""
self.sample = SampleMappable()
def test_init(self):
"""Verify files are created after initialized."""
text = self.sample.yorm_mapper._read()
assert strip("""
var1: ''
var2: 0
var3: false
var4: []
var5:
status: false
""") == text
def test_set(self):
"""Verify the file is written to after setting an attribute."""
self.sample.var1 = "abc123"
self.sample.var2 = 1
self.sample.var3 = True
self.sample.var4 = [42]
self.sample.var5 = {'status': True}
text = self.sample.yorm_mapper._read()
assert strip("""
var1: abc123
var2: 1
var3: true
var4:
- 42
var5:
status: true
""") == text
def test_set_converted(self):
"""Verify conversion occurs when setting attributes."""
self.sample.var1 = 42
self.sample.var2 = "1"
self.sample.var3 = 'off'
self.sample.var4 = None
self.sample.var5 = {'status': 1}
text = self.sample.yorm_mapper._read()
assert strip("""
var1: '42'
var2: 1
var3: false
var4: []
var5:
status: true
""") == text
def test_set_error(self):
"""Verify an exception is raised when a value cannot be converted."""
with pytest.raises(ValueError):
self.sample.var2 = "abc"
def test_get(self):
"""Verify the file is read from before getting an attribute."""
text = strip("""
var1: def456
var2: 42
var3: off
""")
self.sample.yorm_mapper._write(text)
assert"def456" == self.sample.var1
assert 42 == self.sample.var2
assert False is self.sample.var3
def test_error_invalid_yaml(self):
"""Verify an exception is raised on invalid YAML."""
text = strip("""
invalid: -
""")
self.sample.yorm_mapper._write(text)
with pytest.raises(ValueError):
print(self.sample.var1)
def test_error_unexpected_yaml(self):
"""Verify an exception is raised on unexpected YAML."""
text = strip("""
not a dictionary
""")
self.sample.yorm_mapper._write(text)
with pytest.raises(ValueError):
print(self.sample.var1)
def test_new(self):
"""Verify new attributes are added to the object."""
text = strip("""
new: 42
""")
self.sample.yorm_mapper._write(text)
assert 42 == self.sample.new
def test_new_unknown(self):
"""Verify an exception is raised on new attributes w/ unknown types"""
text = strip("""
new: !!timestamp 2001-12-15T02:59:43.1Z
""")
self.sample.yorm_mapper._write(text)
with pytest.raises(ValueError):
print(self.sample.var1)
class TestMappableTriggers:
class MockDict(Mappable, dict):
pass
class MockList:
def append(self, value):
print(value)
class Sample(MockDict, MockList):
yorm_mapper = Mock()
yorm_mapper.attrs = {}
yorm_mapper.fetch = Mock()
yorm_mapper.store = Mock()
def setup_method(self, method):
"""Create an mappable instance for tests."""
self.sample = self.Sample()
self.sample.yorm_mapper.fetch.reset_mock()
self.sample.yorm_mapper.store.reset_mock()
def test_getattribute(self):
with pytest.raises(AttributeError):
getattr(self.sample, 'foo')
assert 1 == self.sample.yorm_mapper.fetch.call_count
assert 0 == self.sample.yorm_mapper.store.call_count
def test_setattr(self):
self.sample.yorm_mapper.attrs['foo'] = Mock()
setattr(self.sample, 'foo', 'bar')
assert 0 == self.sample.yorm_mapper.fetch.call_count
assert 1 == self.sample.yorm_mapper.store.call_count
def test_getitem(self):
with pytest.raises(KeyError):
print(self.sample['foo'])
assert 1 == self.sample.yorm_mapper.fetch.call_count
assert 0 == self.sample.yorm_mapper.store.call_count
def test_setitem(self):
self.sample['foo'] = 'bar'
assert 0 == self.sample.yorm_mapper.fetch.call_count
assert 1 == self.sample.yorm_mapper.store.call_count
def test_delitem(self):
self.sample['foo'] = 'bar'
self.sample.yorm_mapper.store.reset_mock()
del self.sample['foo']
assert 0 == self.sample.yorm_mapper.fetch.call_count
assert 1 == self.sample.yorm_mapper.store.call_count
def test_append(self):
self.sample.append('foo')
assert 0 == self.sample.yorm_mapper.fetch.call_count
assert 1 == self.sample.yorm_mapper.store.call_count
def test_iter(self):
self.sample.append('foo')
self.sample.append('bar')
self.sample.yorm_mapper.fetch.reset_mock()
self.sample.yorm_mapper.store.reset_mock()
for item in self.sample:
print(item)
assert 1 == self.sample.yorm_mapper.fetch.call_count
assert 0 == self.sample.yorm_mapper.store.call_count
def test_handle_missing_mapper(self):
sample = self.MockDict()
sample.yorm_mapper = None
sample[0] = 0
print(sample[0])
assert None is sample.yorm_mapper
if __name__ == '__main__':
pytest.main()