ccsession_test.py 52 KB
Newer Older
Jelte Jansen's avatar
Jelte Jansen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Copyright (C) 2010  Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
# DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#
# Tests for the ConfigData and MultiConfigData classes
#

import unittest
import os
from isc.config.ccsession import *
23
from isc.config.config_data import BIND10_CONFIG_DATA_VERSION
24
from unittest_fakesession import FakeModuleCCSession, WouldBlockForever
25
import bind10_config
26
import isc.log
27

Jelte Jansen's avatar
Jelte Jansen committed
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
class TestHelperFunctions(unittest.TestCase):
    def test_parse_answer(self):
        self.assertRaises(ModuleCCSessionError, parse_answer, 1)
        self.assertRaises(ModuleCCSessionError, parse_answer, { 'just a dict': 1 })
        self.assertRaises(ModuleCCSessionError, parse_answer, { 'result': 1 })
        self.assertRaises(ModuleCCSessionError, parse_answer, { 'result': [] })
        self.assertRaises(ModuleCCSessionError, parse_answer, { 'result': [ 'not_an_rcode' ] })
        self.assertRaises(ModuleCCSessionError, parse_answer, { 'result': [ 1, 2 ] })
        
        rcode, val = parse_answer({ 'result': [ 0 ] })
        self.assertEqual(0, rcode)
        self.assertEqual(None, val)
        rcode, val = parse_answer({ 'result': [ 0, "something" ] })
        self.assertEqual(0, rcode)
        self.assertEqual("something", val)
        rcode, val = parse_answer({ 'result': [ 1, "some error" ] })
        self.assertEqual(1, rcode)
        self.assertEqual("some error", val)

    def test_create_answer(self):
        self.assertRaises(ModuleCCSessionError, create_answer, 'not_an_int')
        self.assertRaises(ModuleCCSessionError, create_answer, 1, 2)
        self.assertRaises(ModuleCCSessionError, create_answer, 1)
        self.assertEqual({ 'result': [ 0 ] }, create_answer(0))
        self.assertEqual({ 'result': [ 1, 'something bad' ] }, create_answer(1, 'something bad'))
        self.assertEqual({ 'result': [ 0, 'something good' ] }, create_answer(0, 'something good'))
        self.assertEqual({ 'result': [ 0, ['some', 'list' ] ] }, create_answer(0, ['some', 'list']))
        self.assertEqual({ 'result': [ 0, {'some': 'map' } ] }, create_answer(0, {'some': 'map'}))

    def test_parse_command(self):
        cmd, arg = parse_command(1)
        self.assertEqual(None, cmd)
        self.assertEqual(None, arg)

        cmd, arg = parse_command({})
        self.assertEqual(None, cmd)
        self.assertEqual(None, arg)

        cmd, arg = parse_command({ 'not a command': 1})
        self.assertEqual(None, cmd)
        self.assertEqual(None, arg)

        cmd, arg = parse_command({ 'command': 1})
        self.assertEqual(None, cmd)
        self.assertEqual(None, arg)

        cmd, arg = parse_command({ 'command': []})
        self.assertEqual(None, cmd)
        self.assertEqual(None, arg)

        cmd, arg = parse_command({ 'command': [ 1 ]})
        self.assertEqual(None, cmd)
        self.assertEqual(None, arg)

        cmd, arg = parse_command({ 'command': [ 'command' ]})
        self.assertEqual('command', cmd)
        self.assertEqual(None, arg)

        cmd, arg = parse_command({ 'command': [ 'command', 1 ]})
        self.assertEqual('command', cmd)
        self.assertEqual(1, arg)

        cmd, arg = parse_command({ 'command': [ 'command', ['some', 'argument', 'list'] ]})
        self.assertEqual('command', cmd)
        self.assertEqual(['some', 'argument', 'list'], arg)

    def test_create_command(self):
        self.assertRaises(ModuleCCSessionError, create_command, 1)
        self.assertEqual({'command': [ 'my_command' ]}, create_command('my_command'))
        self.assertEqual({'command': [ 'my_command', 1 ]}, create_command('my_command', 1))
        self.assertEqual({'command': [ 'my_command', [ 'some', 'list' ] ]}, create_command('my_command', [ 'some', 'list' ]))
        self.assertEqual({'command': [ 'my_command', { 'some': 'map' } ]}, create_command('my_command', { 'some': 'map' }))

class TestModuleCCSession(unittest.TestCase):
    def setUp(self):
        if 'CONFIG_TESTDATA_PATH' in os.environ:
            self.data_path = os.environ['CONFIG_TESTDATA_PATH']
        else:
            self.data_path = "../../../testdata"

    def spec_file(self, file):
        return self.data_path + os.sep + file
        
111
112
113
114
115
    def create_session(self, spec_file_name, config_handler = None,
                       command_handler = None, cc_session = None):
        return ModuleCCSession(self.spec_file(spec_file_name),
                               config_handler, command_handler,
                               cc_session, False)
Jelte Jansen's avatar
Jelte Jansen committed
116
117
118
119
120
121
122
123
124
125

    def test_init(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        self.assertEqual(isc.config.module_spec_from_file(self.spec_file("spec1.spec"))._module_spec, mccs.specification._module_spec)
        self.assertEqual(None, mccs._config_handler)
        self.assertEqual(None, mccs._command_handler)

    def test_start1(self):
        fake_session = FakeModuleCCSession()
126
        self.assertFalse("Spec1" in fake_session.subscriptions)
Jelte Jansen's avatar
Jelte Jansen committed
127
        mccs = self.create_session("spec1.spec", None, None, fake_session)
128
129
        self.assertTrue("Spec1" in fake_session.subscriptions)

Jelte Jansen's avatar
Jelte Jansen committed
130
        self.assertEqual(len(fake_session.message_queue), 0)
131
132
        fake_session.group_sendmsg(None, 'Spec1')
        fake_session.group_sendmsg(None, 'Spec1')
Jelte Jansen's avatar
Jelte Jansen committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
        self.assertRaises(ModuleCCSessionError, mccs.start)
        self.assertEqual(len(fake_session.message_queue), 2)
        self.assertEqual({'command': ['module_spec', {'module_name': 'Spec1'}]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec1'}]},
                         fake_session.get_message('ConfigManager', None))

        self.assertEqual(len(fake_session.message_queue), 0)
        fake_session.group_sendmsg({'result': [ 0 ]}, "Spec1")
        fake_session.group_sendmsg({'result': [ 0 ]}, "Spec1")
        mccs.start()
        self.assertEqual(len(fake_session.message_queue), 2)

        self.assertEqual({'command': ['module_spec', {'module_name': 'Spec1'}]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec1'}]},
                         fake_session.get_message('ConfigManager', None))

151
152
153
        mccs = None
        self.assertFalse("Spec1" in fake_session.subscriptions)

154
155
156
157
    def test_start2(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        self.assertEqual(len(fake_session.message_queue), 0)
158
159
        fake_session.group_sendmsg(None, 'Spec2')
        fake_session.group_sendmsg(None, 'Spec2')
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
        self.assertRaises(ModuleCCSessionError, mccs.start)
        self.assertEqual(len(fake_session.message_queue), 2)
        self.assertEqual({'command': ['module_spec', mccs.specification._module_spec]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))

        self.assertEqual(len(fake_session.message_queue), 0)
        fake_session.group_sendmsg({'result': [ 0 ]}, "Spec2")
        fake_session.group_sendmsg({'result': [ 0, {} ]}, "Spec2")
        mccs.start()
        self.assertEqual(len(fake_session.message_queue), 2)

        self.assertEqual({'command': ['module_spec', mccs.specification._module_spec]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))

    def test_start3(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        self.assertEqual(len(fake_session.message_queue), 0)
183
184
        fake_session.group_sendmsg(None, 'Spec2')
        fake_session.group_sendmsg(None, 'Spec2')
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
        self.assertRaises(ModuleCCSessionError, mccs.start)
        self.assertEqual(len(fake_session.message_queue), 2)
        self.assertEqual({'command': ['module_spec', mccs.specification._module_spec]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))

        self.assertEqual(len(fake_session.message_queue), 0)
        fake_session.group_sendmsg({'result': [ 0 ]}, "Spec2")
        fake_session.group_sendmsg({'result': [ 0, {} ]}, "Spec2")
        mccs.start()
        self.assertEqual(len(fake_session.message_queue), 2)

        self.assertEqual({'command': ['module_spec', mccs.specification._module_spec]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))

    def test_start4(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        self.assertEqual(len(fake_session.message_queue), 0)
208
209
        fake_session.group_sendmsg(None, 'Spec2')
        fake_session.group_sendmsg(None, 'Spec2')
210
211
212
213
214
215
216
217
218
219
220
221
        self.assertRaises(ModuleCCSessionError, mccs.start)
        self.assertEqual(len(fake_session.message_queue), 2)
        self.assertEqual({'command': ['module_spec', mccs.specification._module_spec]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))

        self.assertEqual(len(fake_session.message_queue), 0)
        fake_session.group_sendmsg({'result': [ 0 ]}, "Spec2")
        fake_session.group_sendmsg({'result': [ 1, "just an error" ]}, "Spec2")
        mccs.start()
        self.assertEqual(len(fake_session.message_queue), 2)
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

        self.assertEqual({'command': ['module_spec', mccs.specification._module_spec]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))

    def test_start5(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        self.assertEqual(len(fake_session.message_queue), 0)
        fake_session.group_sendmsg(None, 'Spec2')
        fake_session.group_sendmsg(None, 'Spec2')
        self.assertRaises(ModuleCCSessionError, mccs.start)
        self.assertEqual(len(fake_session.message_queue), 2)
        self.assertEqual({'command': ['module_spec', mccs.specification._module_spec]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))

        self.assertEqual(len(fake_session.message_queue), 0)
        fake_session.group_sendmsg({'result': [ 0 ]}, "Spec2")
        fake_session.group_sendmsg({'result': [ 0, {"Wrong": True} ]}, "Spec2")
        self.assertRaises(ModuleCCSessionError, mccs.start)
        self.assertEqual(len(fake_session.message_queue), 2)
247
248
249
250
251
252

        self.assertEqual({'command': ['module_spec', mccs.specification._module_spec]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))

253
254
255
256
257
258
259
    def test_stop(self):
        fake_session = FakeModuleCCSession()
        self.assertFalse("Spec1" in fake_session.subscriptions)
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        self.assertTrue("Spec1" in fake_session.subscriptions)

        self.assertEqual(len(fake_session.message_queue), 0)
Jelte Jansen's avatar
Jelte Jansen committed
260
        mccs.send_stopping()
261
262
263
264
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'command': ['stopping', {'module_name': 'Spec1'}]},
                         fake_session.get_message('ConfigManager', None))

Jelte Jansen's avatar
Jelte Jansen committed
265
266
267
268
269
270
271
272
    def test_get_socket(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        self.assertNotEqual(None, mccs.get_socket())

    def test_get_session(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
273
        self.assertEqual(fake_session, mccs._session)
Jelte Jansen's avatar
Jelte Jansen committed
274
275
276
277
278

    def test_close(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        mccs.close()
279
        self.assertEqual(None, fake_session._socket)
Jelte Jansen's avatar
Jelte Jansen committed
280

281
    def test_del_opened(self):
282
283
284
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        mccs.__del__() # with opened fake_session
285
286
287
288

    def test_del_closed(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
289
290
291
        fake_session.close()
        mccs.__del__() # with closed fake_session

292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    def my_config_handler_ok(self, new_config):
        return isc.config.ccsession.create_answer(0)

    def my_config_handler_err(self, new_config):
        return isc.config.ccsession.create_answer(1, "just an error")

    def my_config_handler_exc(self, new_config):
        raise Exception("just an exception")

    def my_command_handler_ok(self, command, args):
        return isc.config.ccsession.create_answer(0)

    def my_command_handler_no_answer(self, command, args):
        pass

    def test_check_command1(self):
Jelte Jansen's avatar
Jelte Jansen committed
308
309
310
311
312
313
314
315
316
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)

        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 0)

        fake_session.group_sendmsg({'result': [ 0 ]}, "Spec1")
        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 0)
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343

        cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, { 'Spec1': 'a' })

        fake_session.group_sendmsg(cmd, 'Spec1')
        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [2, 'Spec1 has no config handler']},
                         fake_session.get_message('Spec1', None))

    def test_check_command2(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        self.assertEqual(len(fake_session.message_queue), 0)
        cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, { 'Spec1': 'a' })
        fake_session.group_sendmsg(cmd, 'Spec1')
        self.assertEqual(len(fake_session.message_queue), 1)
        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [1, 'No config_data specification']},
                         fake_session.get_message('Spec1', None))
        
    def test_check_command3(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        self.assertEqual(len(fake_session.message_queue), 0)
344
        cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, { 'item1': 2 })
345
346
347
348
349
350
351
352
353
354
355
356
        fake_session.group_sendmsg(cmd, 'Spec2')
        self.assertEqual(len(fake_session.message_queue), 1)
        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [0]},
                         fake_session.get_message('Spec2', None))
        
    def test_check_command4(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_err)
        self.assertEqual(len(fake_session.message_queue), 0)
357
        cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, { 'item1': 'aaa' })
358
359
360
361
        fake_session.group_sendmsg(cmd, 'Spec2')
        self.assertEqual(len(fake_session.message_queue), 1)
        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 1)
362
        self.assertEqual({'result': [1, 'aaa should be an integer']},
363
364
365
366
367
368
369
                         fake_session.get_message('Spec2', None))
        
    def test_check_command5(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_exc)
        self.assertEqual(len(fake_session.message_queue), 0)
370
        cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, { 'item1': 'aaa' })
371
372
373
374
        fake_session.group_sendmsg(cmd, 'Spec2')
        self.assertEqual(len(fake_session.message_queue), 1)
        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 1)
375
        self.assertEqual({'result': [1, 'aaa should be an integer']},
376
377
378
379
380
381
382
383
384
385
386
387
388
                         fake_session.get_message('Spec2', None))
        
    def test_check_command6(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        self.assertEqual(len(fake_session.message_queue), 0)
        cmd = isc.config.ccsession.create_command("print_message", "just a message")
        fake_session.group_sendmsg(cmd, 'Spec2')
        self.assertEqual(len(fake_session.message_queue), 1)
        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [2, 'Spec2 has no command handler']},
                         fake_session.get_message('Spec2', None))
389
390
391
392

    """Many check_command tests look too similar, this is common body."""
    def common_check_command_check(self, cmd_handler,
            cmd_check=lambda mccs, _: mccs.check_command()):
393
394
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
395
        mccs.set_command_handler(cmd_handler)
396
397
398
399
        self.assertEqual(len(fake_session.message_queue), 0)
        cmd = isc.config.ccsession.create_command("print_message", "just a message")
        fake_session.group_sendmsg(cmd, 'Spec2')
        self.assertEqual(len(fake_session.message_queue), 1)
400
401
402
403
404
405
        cmd_check(mccs, fake_session)
        return fake_session

    def test_check_command7(self):
        fake_session = self.common_check_command_check(
            self.my_command_handler_ok)
406
407
408
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [0]},
                         fake_session.get_message('Spec2', None))
409

410
    def test_check_command8(self):
411
412
        fake_session = self.common_check_command_check(
            self.my_command_handler_no_answer)
413
        self.assertEqual(len(fake_session.message_queue), 0)
414
415
416
417
418
419

    def test_check_command_block(self):
        """See if the message gets there even in blocking mode."""
        fake_session = self.common_check_command_check(
            self.my_command_handler_ok,
            lambda mccs, _: mccs.check_command(False))
420
        self.assertEqual(len(fake_session.message_queue), 1)
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
        self.assertEqual({'result': [0]},
                         fake_session.get_message('Spec2', None))

    def test_check_command_block_timeout(self):
        """Check it works if session has timeout and it sets it back."""
        def cmd_check(mccs, session):
            session.set_timeout(1)
            mccs.check_command(False)
        fake_session = self.common_check_command_check(
            self.my_command_handler_ok, cmd_check)
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [0]},
                         fake_session.get_message('Spec2', None))
        self.assertEqual(fake_session.get_timeout(), 1)

    def test_check_command_blocks_forever(self):
        """Check it would wait forever checking a command."""
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_command_handler(self.my_command_handler_ok)
        self.assertRaises(WouldBlockForever, lambda: mccs.check_command(False))

    def test_check_command_blocks_forever_timeout(self):
        """Like above, but it should wait forever even with timeout here."""
        fake_session = FakeModuleCCSession()
        fake_session.set_timeout(1)
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_command_handler(self.my_command_handler_ok)
        self.assertRaises(WouldBlockForever, lambda: mccs.check_command(False))
450

451
452
453
454
455
456
457
458
459
460
461
462
    def test_check_command_without_recvmsg1(self):
        "copied from test_check_command2"
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        self.assertEqual(len(fake_session.message_queue), 0)
        cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, { 'Spec1': 'abcd' })
        env = { 'group': 'Spec1', 'from':None };
        mccs.check_command_without_recvmsg(cmd, env)
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [1, 'No config_data specification']},
                         fake_session.get_message('Spec1', None))
463
 
464
465
466
467
468
469
    def test_check_command_without_recvmsg2(self):
        "copied from test_check_command3"
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        self.assertEqual(len(fake_session.message_queue), 0)
470
        cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, { 'item1': 2 })
471
472
473
474
475
        self.assertEqual(len(fake_session.message_queue), 0)
        env = { 'group':'Spec2', 'from':None }
        mccs.check_command_without_recvmsg(cmd, env)
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [0]},
476
477
                          fake_session.get_message('Spec2', None))
 
478
479
480
481
482
483
484
485
486
487
488
489
    def test_check_command_without_recvmsg3(self):
        "copied from test_check_command7"
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_command_handler(self.my_command_handler_ok)
        self.assertEqual(len(fake_session.message_queue), 0)
        cmd = isc.config.ccsession.create_command("print_message", "just a message")
        env = { 'group':'Spec2', 'from':None }
        self.assertEqual(len(fake_session.message_queue), 0)
        mccs.check_command_without_recvmsg(cmd, env)
        self.assertEqual({'result': [0]},
                         fake_session.get_message('Spec2', None))
490
 
Jelte Jansen's avatar
Jelte Jansen committed
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
    def test_check_command_block_timeout(self):
        """Check it works if session has timeout and it sets it back."""
        def cmd_check(mccs, session):
            session.set_timeout(1)
            mccs.check_command(False)
        fake_session = self.common_check_command_check(
            self.my_command_handler_ok, cmd_check)
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [0]},
                         fake_session.get_message('Spec2', None))
        self.assertEqual(fake_session.get_timeout(), 1)

    def test_check_command_blocks_forever(self):
        """Check it would wait forever checking a command."""
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_command_handler(self.my_command_handler_ok)
        self.assertRaises(WouldBlockForever, lambda: mccs.check_command(False))
509

510
511
512
513
514
515
516
517
    def test_check_command_blocks_forever_timeout(self):
        """Like above, but it should wait forever even with timeout here."""
        fake_session = FakeModuleCCSession()
        fake_session.set_timeout(1)
        mccs = self.create_session("spec2.spec", None, None, fake_session)
        mccs.set_command_handler(self.my_command_handler_ok)
        self.assertRaises(WouldBlockForever, lambda: mccs.check_command(False))

518
519
520
521
522
523
524
525
    # Now there's a group of tests testing both add_remote_config and
    # add_remote_config_by_name. Since they are almost the same (they differ
    # just in the parameter and that the second one asks one more question over
    # the bus), the actual test code is shared.
    #
    # These three functions are helper functions to easy up the writing of them.
    # To write a test, there need to be 3 functions. First, the function that
    # does the actual test. It looks like:
JINMEI Tatuya's avatar
JINMEI Tatuya committed
526
    # def _internal_test(self, function_lambda, param, fill_other_messages):
527
528
    #
    # The function_lambda provides the tested function if called on the
JINMEI Tatuya's avatar
JINMEI Tatuya committed
529
    # ccsession. The param is the parameter to pass to the function (either
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
    # the module name or the spec file name. The fill_other_messages fills
    # needed messages (the answer containing the module spec in case of add by
    # name, no messages in the case of adding by spec file) into the fake bus.
    # So, the code would look like:
    #
    # * Create the fake session and tested ccsession object
    # * function = function_lambda(ccsession object)
    # * fill_other_messages(fake session)
    # * Fill in answer to the get_module_config command
    # * Test by calling function(param)
    #
    # Then you need two wrappers that do launch the tests. There are helpers
    # for that, so you can just call:
    # def test_by_spec(self)
    #     self._common_remote_module_test(self._internal_test)
    # def test_by_name(self)
    #     self._common_remote_module_by_name_test(self._internal_test)
    def _common_remote_module_test(self, internal_test):
        internal_test(lambda ccs: ccs.add_remote_config,
                      self.spec_file("spec2.spec"),
                      lambda session: None)

    def _prepare_spec_message(self, session, spec_name):
        # It could have been one command, but the line would be way too long
        # to even split it
        spec_file = self.spec_file(spec_name)
        spec = isc.config.module_spec_from_file(spec_file)
        session.group_sendmsg({'result': [0, spec.get_full_spec()]}, "Spec1")

    def _common_remote_module_by_name_test(self, internal_test):
        internal_test(lambda ccs: ccs.add_remote_config_by_name, "Spec2",
                      lambda session: self._prepare_spec_message(session,
                                                                 "spec2.spec"))

564
565
    def _internal_remote_module(self, function_lambda, parameter,
                                fill_other_messages):
566
567
568
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        mccs.remove_remote_config("Spec2")
569
        function = function_lambda(mccs)
570
571
572

        self.assertRaises(ModuleCCSessionError, mccs.get_remote_config_value, "Spec2", "item1")

573
        self.assertFalse("Spec2" in fake_session.subscriptions)
574
        fill_other_messages(fake_session)
575
        fake_session.group_sendmsg(None, 'Spec2')
576
        rmodname = function(parameter)
577
        self.assertTrue("Spec2" in fake_session.subscriptions)
578
579
580
581
582
583
584
        self.assertEqual("Spec2", rmodname)
        self.assertRaises(isc.cc.data.DataNotFoundError, mccs.get_remote_config_value, rmodname, "asdf")
        value, default = mccs.get_remote_config_value(rmodname, "item1")
        self.assertEqual(1, value)
        self.assertEqual(True, default)

        mccs.remove_remote_config(rmodname)
585
        self.assertFalse("Spec2" in fake_session.subscriptions)
586
        self.assertRaises(ModuleCCSessionError, mccs.get_remote_config_value, "Spec2", "item1")
587

JINMEI Tatuya's avatar
JINMEI Tatuya committed
588
        # test if unsubscription is also sent when object is deleted
589
        fill_other_messages(fake_session)
590
        fake_session.group_sendmsg({'result' : [0]}, 'Spec2')
591
        rmodname = function(parameter)
592
593
        self.assertTrue("Spec2" in fake_session.subscriptions)
        mccs = None
594
        function = None
595
        self.assertFalse("Spec2" in fake_session.subscriptions)
596

597
    def test_remote_module(self):
598
599
600
601
        """
        Test we can add a remote config and get the configuration.
        Remote module specified by the spec file name.
        """
602
603
604
        self._common_remote_module_test(self._internal_remote_module)

    def test_remote_module_by_name(self):
605
606
607
608
        """
        Test we can add a remote config and get the configuration.
        Remote module specified its name.
        """
609
610
611
612
613
        self._common_remote_module_by_name_test(self._internal_remote_module)

    def _internal_remote_module_with_custom_config(self, function_lambda,
                                                   parameter,
                                                   fill_other_messages):
614
615
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
616
        function = function_lambda(mccs)
617
618
        # override the default config value for "item1". add_remote_config[_by_name]()
        # should incorporate the overridden value, and we should be able to
619
        # get it via get_remote_config_value().
620
        fill_other_messages(fake_session)
621
        fake_session.group_sendmsg({'result': [0, {"item1": 10}]}, 'Spec2')
622
        rmodname = function(parameter)
623
624
625
626
        value, default = mccs.get_remote_config_value(rmodname, "item1")
        self.assertEqual(10, value)
        self.assertEqual(False, default)

627
    def test_remote_module_with_custom_config(self):
628
629
630
631
632
        """
        Test the config of module will load non-default values on
        initialization.
        Remote module specified by the spec file name.
        """
633
634
635
636
        self._common_remote_module_test(
            self._internal_remote_module_with_custom_config)

    def test_remote_module_by_name_with_custom_config(self):
637
638
639
640
641
        """
        Test the config of module will load non-default values on
        initialization.
        Remote module its name.
        """
642
643
644
645
646
        self._common_remote_module_by_name_test(
            self._internal_remote_module_with_custom_config)

    def _internal_ignore_command_remote_module(self, function_lambda, param,
                                               fill_other_messages):
647
648
649
650
        # Create a Spec1 module and subscribe to remote config for Spec2
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        mccs.set_command_handler(self.my_command_handler_ok)
651
652
        function = function_lambda(mccs)
        fill_other_messages(fake_session)
653
        fake_session.group_sendmsg(None, 'Spec2')
654
        rmodname = function(param)
655

656
657
658
        # remove the commands from queue
        while len(fake_session.message_queue) > 0:
            fake_session.get_message("ConfigManager")
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674

        # check if the command for the module itself is received
        cmd = isc.config.ccsession.create_command("just_some_command", { 'foo': 'a' })
        fake_session.group_sendmsg(cmd, 'Spec1')
        self.assertEqual(len(fake_session.message_queue), 1)
        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 1)
        self.assertEqual({'result': [ 0 ]},
                         fake_session.get_message('Spec1', None))

        # check if the command for the other module is ignored
        cmd = isc.config.ccsession.create_command("just_some_command", { 'foo': 'a' })
        fake_session.group_sendmsg(cmd, 'Spec2')
        self.assertEqual(len(fake_session.message_queue), 1)
        mccs.check_command()
        self.assertEqual(len(fake_session.message_queue), 0)
675

676
    def test_ignore_commant_remote_module(self):
677
678
679
680
        """
        Test that commands for remote modules aren't handled.
        Remote module specified by the spec file name.
        """
681
682
683
684
        self._common_remote_module_test(
            self._internal_ignore_command_remote_module)

    def test_ignore_commant_remote_module_by_name(self):
685
686
687
688
        """
        Test that commands for remote modules aren't handled.
        Remote module specified by its name.
        """
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
        self._common_remote_module_by_name_test(
            self._internal_ignore_command_remote_module)

    def _internal_check_command_without_recvmsg_remote_module(self,
                                                              function_lambda,
                                                              param,
                                                              fill_other_messages):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        function = function_lambda(mccs)
        self.assertEqual(len(fake_session.message_queue), 0)

        fill_other_messages(fake_session)
        fake_session.group_sendmsg(None, 'Spec2')
        rmodname = function(param)
        if (len(fake_session.message_queue) == 2):
            self.assertEqual({'command': ['get_module_spec',
                                          {'module_name': 'Spec2'}]},
                             fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual(len(fake_session.message_queue), 0)

        cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, { 'Spec2': { 'item1': 2 }})
        env = { 'group':'Spec2', 'from':None }
        self.assertEqual(len(fake_session.message_queue), 0)
        mccs.check_command_without_recvmsg(cmd, env)
        self.assertEqual(len(fake_session.message_queue), 0)

    def test_check_command_without_recvmsg_remote_module(self):
720
721
722
723
        """
        Test updates on remote module.
        The remote module is specified by the spec file name.
        """
724
725
726
727
        self._common_remote_module_test(
            self._internal_check_command_without_recvmsg_remote_module)

    def test_check_command_without_recvmsg_remote_module_by_name(self):
728
729
730
731
        """
        Test updates on remote module.
        The remote module is specified by its name.
        """
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
        self._common_remote_module_by_name_test(
            self._internal_check_command_without_recvmsg_remote_module)

    def _internal_check_command_without_recvmsg_remote_module2(self,
                                                               function_lambda,
                                                               param,
                                                               fill_other_messages):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        function = function_lambda(mccs)
        self.assertEqual(len(fake_session.message_queue), 0)

        fill_other_messages(fake_session)
        fake_session.group_sendmsg(None, 'Spec2')
        rmodname = function(param)
        if (len(fake_session.message_queue) == 2):
            self.assertEqual({'command': ['get_module_spec',
                                          {'module_name': 'Spec2'}]},
                             fake_session.get_message('ConfigManager', None))
        self.assertEqual({'command': ['get_config', {'module_name': 'Spec2'}]},
                         fake_session.get_message('ConfigManager', None))
        self.assertEqual(len(fake_session.message_queue), 0)

        cmd = isc.config.ccsession.create_command(isc.config.ccsession.COMMAND_CONFIG_UPDATE, { 'Spec3': { 'item1': 2 }})
        env = { 'group':'Spec3', 'from':None }
        self.assertEqual(len(fake_session.message_queue), 0)
        mccs.check_command_without_recvmsg(cmd, env)
        self.assertEqual(len(fake_session.message_queue), 0)

    def test_check_command_without_recvmsg_remote_module2(self):
763
764
765
766
        """
        Test updates on remote module.
        The remote module is specified by the spec file name.
        """
767
768
769
770
        self._common_remote_module_test(
            self._internal_check_command_without_recvmsg_remote_module2)

    def test_check_command_without_recvmsg_remote_module_by_name2(self):
771
772
773
774
        """
        Test updates on remote module.
        The remote module is specified by its name.
        """
775
776
777
        self._common_remote_module_by_name_test(
            self._internal_check_command_without_recvmsg_remote_module2)

Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
    def _internal_remote_module_bad_config(self, function_lambda, parameter,
                                           fill_other_messages):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        function = function_lambda(mccs)
        # Provide wrong config data. It should be rejected.
        fill_other_messages(fake_session)
        fake_session.group_sendmsg({'result': [0, {"bad_item": -1}]}, 'Spec2')
        self.assertRaises(isc.config.ModuleCCSessionError,
                          function, parameter)

    def test_remote_module_bad_config(self):
        """
        Test the remote module rejects bad config data.
        """
        self._common_remote_module_test(
            self._internal_remote_module_bad_config)

    def test_remote_module_by_name_bad_config(self):
        """
        Test the remote module rejects bad config data.
        """
        self._common_remote_module_by_name_test(
            self._internal_remote_module_bad_config)

    def _internal_remote_module_error_response(self, function_lambda,
                                               parameter, fill_other_messages):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        function = function_lambda(mccs)
        # Provide wrong config data. It should be rejected.
        fill_other_messages(fake_session)
        fake_session.group_sendmsg({'result': [1, "An error, and I mean it!"]},
                                   'Spec2')
        self.assertRaises(isc.config.ModuleCCSessionError,
                          function, parameter)

    def test_remote_module_bad_config(self):
        """
        Test the remote module complains if there's an error response."
        """
        self._common_remote_module_test(
            self._internal_remote_module_error_response)

    def test_remote_module_by_name_bad_config(self):
        """
        Test the remote module complains if there's an error response."
        """
        self._common_remote_module_by_name_test(
            self._internal_remote_module_error_response)

    def test_remote_module_bad_config(self):
        """
        Test the remote module rejects bad config data.
        """
        self._common_remote_module_by_name_test(
            self._internal_remote_module_bad_config)

836
837
838
839
840
841
842
    def test_module_name_mismatch(self):
        fake_session = FakeModuleCCSession()
        mccs = self.create_session("spec1.spec", None, None, fake_session)
        mccs.set_config_handler(self.my_config_handler_ok)
        self._prepare_spec_message(fake_session, 'spec1.spec')
        self.assertRaises(isc.config.ModuleCCSessionError,
                          mccs.add_remote_config_by_name, "Spec2")
843

844
845
846
847
848
849
850
    def test_logconfig_handler(self):
        # test whether default_logconfig_handler reacts nicely to
        # bad data. We assume the actual logger output is tested
        # elsewhere
        self.assertRaises(TypeError, default_logconfig_handler);
        self.assertRaises(TypeError, default_logconfig_handler, 1);

851
852
        spec = isc.config.module_spec_from_file(
            path_search('logging.spec', bind10_config.PLUGIN_PATHS))
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
        config_data = ConfigData(spec)

        self.assertRaises(TypeError, default_logconfig_handler, 1, config_data)

        default_logconfig_handler({}, config_data)

        # Wrong data should not raise, but simply not be accepted
        # This would log a lot of errors, so we may want to suppress that later
        default_logconfig_handler({ "bad_data": "indeed" }, config_data)
        default_logconfig_handler({ "bad_data": 1}, config_data)
        default_logconfig_handler({ "bad_data": 1123 }, config_data)
        default_logconfig_handler({ "bad_data": True }, config_data)
        default_logconfig_handler({ "bad_data": False }, config_data)
        default_logconfig_handler({ "bad_data": 1.1 }, config_data)
        default_logconfig_handler({ "bad_data": [] }, config_data)
        default_logconfig_handler({ "bad_data": [[],[],[[1, 3, False, "foo" ]]] },
                                  config_data)
        default_logconfig_handler({ "bad_data": [ 1, 2, { "b": { "c": "d" } } ] },
                                  config_data)

        # Try a correct config
        log_conf = {"loggers":
                       [{"name": "b10-xfrout", "output_options":
                           [{"output": "/tmp/bind10.log",
                                       "destination": "file",
                                       "flush": True}]}]}
        default_logconfig_handler(log_conf, config_data)
880

881
882
883
884
885
886
887
888
class fakeData:
    def decode(self):
        return "{}";

class fakeAnswer:
    def read(self):
        return fakeData();

889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
class fakeUIConn():
    def __init__(self):
        self.get_answers = {}
        self.post_answers = {}

    def set_get_answer(self, name, answer):
        self.get_answers[name] = answer
    
    def set_post_answer(self, name, answer):
        self.post_answers[name] = answer
    
    def send_GET(self, name, arg = None):
        if name in self.get_answers:
            return self.get_answers[name]
        else:
904
            return {}
905
906
907
908
909
    
    def send_POST(self, name, arg = None):
        if name in self.post_answers:
            return self.post_answers[name]
        else:
910
            return fakeAnswer()
911
912
913
914
915
916
917
918
919
920
921
    

class TestUIModuleCCSession(unittest.TestCase):
    def setUp(self):
        if 'CONFIG_TESTDATA_PATH' in os.environ:
            self.data_path = os.environ['CONFIG_TESTDATA_PATH']
        else:
            self.data_path = "../../../testdata"

    def spec_file(self, file):
        return self.data_path + os.sep + file
Jelte Jansen's avatar
Jelte Jansen committed
922
        
923
924
    def create_uccs2(self, fake_conn):
        module_spec = isc.config.module_spec_from_file(self.spec_file("spec2.spec"))
925
        fake_conn.set_get_answer('/module_spec', { module_spec.get_module_name(): module_spec.get_full_spec()})
926
        fake_conn.set_get_answer('/config_data', { 'version': BIND10_CONFIG_DATA_VERSION })
927
928
        return UIModuleCCSession(fake_conn)

929
    def create_uccs_named_set(self, fake_conn):
930
931
932
933
934
        module_spec = isc.config.module_spec_from_file(self.spec_file("spec32.spec"))
        fake_conn.set_get_answer('/module_spec', { module_spec.get_module_name(): module_spec.get_full_spec()})
        fake_conn.set_get_answer('/config_data', { 'version': BIND10_CONFIG_DATA_VERSION })
        return UIModuleCCSession(fake_conn)

935
936
937
938
939
940
    def create_uccs_listtest(self, fake_conn):
        module_spec = isc.config.module_spec_from_file(self.spec_file("spec39.spec"))
        fake_conn.set_get_answer('/module_spec', { module_spec.get_module_name(): module_spec.get_full_spec()})
        fake_conn.set_get_answer('/config_data', { 'version': BIND10_CONFIG_DATA_VERSION })
        return UIModuleCCSession(fake_conn)

941
942
    def test_init(self):
        fake_conn = fakeUIConn()
943
        fake_conn.set_get_answer('/module_spec', {})
944
        fake_conn.set_get_answer('/config_data', { 'version': BIND10_CONFIG_DATA_VERSION })
945
946
        uccs = UIModuleCCSession(fake_conn)
        self.assertEqual({}, uccs._specifications)
947
        self.assertEqual({ 'version': BIND10_CONFIG_DATA_VERSION}, uccs._current_config)
948
949

        module_spec = isc.config.module_spec_from_file(self.spec_file("spec2.spec"))
950
        fake_conn.set_get_answer('/module_spec', { module_spec.get_module_name(): module_spec.get_full_spec()})
951
        fake_conn.set_get_answer('/config_data', { 'version': BIND10_CONFIG_DATA_VERSION })
952
953
954
955
956
957
        uccs = UIModuleCCSession(fake_conn)
        self.assertEqual(module_spec._module_spec, uccs._specifications['Spec2']._module_spec)

        fake_conn.set_get_answer('/config_data', { 'version': 123123 })
        self.assertRaises(ModuleCCSessionError, UIModuleCCSession, fake_conn)

958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
    def test_request_specifications(self):
        module_spec1 = isc.config.module_spec_from_file(
                          self.spec_file("spec1.spec"))
        module_spec_dict1 = { "module_spec": module_spec1.get_full_spec() }
        module_spec2 = isc.config.module_spec_from_file(
                          self.spec_file("spec2.spec"))
        module_spec_dict2 = { "module_spec": module_spec2.get_full_spec() }

        fake_conn = fakeUIConn()
        # Set the first one in the answer
        fake_conn.set_get_answer('/module_spec', module_spec_dict1)
        fake_conn.set_get_answer('/config_data',
                                 { 'version': BIND10_CONFIG_DATA_VERSION })
        uccs = UIModuleCCSession(fake_conn)

        # We should now have the first one, but not the second.
        self.assertTrue("Spec1" in uccs._specifications)
        self.assertEqual(module_spec1.get_full_spec(),
                         uccs._specifications["Spec1"].get_full_spec())
        self.assertFalse("Spec2" in uccs._specifications)

        # Now set an answer where only the second one is present
        fake_conn.set_get_answer('/module_spec', module_spec_dict2)

        uccs.request_specifications()

        # Now Spec1 should have been removed, and spec2 should be there
        self.assertFalse("Spec1" in uccs._specifications)
        self.assertTrue("Spec2" in uccs._specifications)
        self.assertEqual(module_spec2.get_full_spec(),
                         uccs._specifications["Spec2"].get_full_spec())

990
991
992
    def test_add_remove_value(self):
        fake_conn = fakeUIConn()
        uccs = self.create_uccs2(fake_conn)
993

994
995
996
997
998
999
        self.assertRaises(isc.cc.data.DataNotFoundError, uccs.add_value, 1, "a")
        self.assertRaises(isc.cc.data.DataNotFoundError, uccs.add_value, "no_such_item", "a")
        self.assertRaises(isc.cc.data.DataNotFoundError, uccs.add_value, "Spec2/item1", "a")
        self.assertRaises(isc.cc.data.DataNotFoundError, uccs.remove_value, 1, "a")
        self.assertRaises(isc.cc.data.DataNotFoundError, uccs.remove_value, "no_such_item", "a")
        self.assertRaises(isc.cc.data.DataNotFoundError, uccs.remove_value, "Spec2/item1", "a")
1000

1001
1002
1003
1004
1005
1006
1007
1008
1009
        self.assertEqual({}, uccs._local_changes)
        uccs.add_value("Spec2/item5", "foo")
        self.assertEqual({'Spec2': {'item5': ['a', 'b', 'foo']}}, uccs._local_changes)
        uccs.remove_value("Spec2/item5", "foo")
        self.assertEqual({'Spec2': {'item5': ['a', 'b']}}, uccs._local_changes)
        uccs._local_changes = {'Spec2': {'item5': []}}
        uccs.remove_value("Spec2/item5", "foo")
        uccs.add_value("Spec2/item5", "foo")
        self.assertEqual({'Spec2': {'item5': ['foo']}}, uccs._local_changes)
1010
1011
        self.assertRaises(isc.cc.data.DataAlreadyPresentError,
                          uccs.add_value, "Spec2/item5", "foo")
1012
        self.assertEqual({'Spec2': {'item5': ['foo']}}, uccs._local_changes)
1013
1014
        self.assertRaises(isc.cc.data.DataNotFoundError,
                          uccs.remove_value, "Spec2/item5[123]", None)
1015
1016
        uccs.remove_value("Spec2/item5[0]", None)
        self.assertEqual({'Spec2': {'item5': []}}, uccs._local_changes)
1017
1018
        uccs.add_value("Spec2/item5", None);
        self.assertEqual({'Spec2': {'item5': ['']}}, uccs._local_changes)
1019
1020
1021
        # Intending to empty a list element, but forget specifying the index.
        self.assertRaises(isc.cc.data.DataTypeError,
                          uccs.remove_value, "Spec2/item5", None)
1022

1023
1024
1025
1026
1027
1028
1029
1030
    def test_add_dup_value(self):
        fake_conn = fakeUIConn()
        uccs = self.create_uccs_listtest(fake_conn)

        uccs.add_value("Spec39/list")
        self.assertRaises(isc.cc.data.DataAlreadyPresentError, uccs.add_value,
                          "Spec39/list")

1031
    def test_add_remove_value_named_set(self):
1032
        fake_conn = fakeUIConn()
1033
1034
        uccs = self.create_uccs_named_set(fake_conn)
        value, status = uccs.get_value("/Spec32/named_set_item")
1035
        self.assertEqual({'a': 1, 'b': 2}, value)
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046

        # make sure that removing from default actually removes it
        uccs.remove_value("/Spec32/named_set_item", "a")
        value, status = uccs.get_value("/Spec32/named_set_item")
        self.assertEqual({'b': 2}, value)
        self.assertEqual(uccs.LOCAL, status)

        # ok, put it back now
        uccs.add_value("/Spec32/named_set_item", "a")
        uccs.set_value("/Spec32/named_set_item/a", 1)

1047
1048
        uccs.add_value("/Spec32/named_set_item", "foo")
        value, status = uccs.get_value("/Spec32/named_set_item")
1049
1050
        self.assertEqual({'a': 1, 'b': 2, 'foo': 3}, value)

1051
1052
1053
        uccs.remove_value("/Spec32/named_set_item", "a")
        uccs.remove_value("/Spec32/named_set_item", "foo")
        value, status = uccs.get_value("/Spec32/named_set_item")
1054
        self.assertEqual({'b': 2}, value)
1055

1056
1057
1058
1059
        uccs.set_value("/Spec32/named_set_item/c", 5)
        value, status = uccs.get_value("/Spec32/named_set_item")
        self.assertEqual({"b": 2, "c": 5}, value)

1060
1061
        self.assertRaises(isc.cc.data.DataNotFoundError,
                          uccs.set_value,
1062
                          "/Spec32/named_set_item/no_such_item/a",
1063
                          4)
1064
        self.assertRaises(isc.cc.data.DataNotFoundError,
1065
                          uccs.remove_value, "/Spec32/named_set_item",
1066
                          "no_such_item")
1067
1068
        self.assertRaises(isc.cc.data.DataAlreadyPresentError,
                          uccs.add_value, "/Spec32/named_set_item", "c")
1069

1070
1071
1072
1073
1074
1075
1076
1077
    def test_set_value_named_set(self):
        fake_conn = fakeUIConn()
        uccs = self.create_uccs_named_set(fake_conn)
        value, status = uccs.get_value("/Spec32/named_set_item2")
        self.assertEqual({}, value)
        self.assertEqual(status, uccs.DEFAULT)

        # Try setting a value that is optional but has no default
1078
1079
1080
1081
        uccs.add_value("/Spec32/named_set_item2", "new1")
        uccs.set_value("/Spec32/named_set_item2/new1/first", 3)
        # Different method to add a new element
        uccs.set_value("/Spec32/named_set_item2/new2", { "second": 4 })
1082
1083

        value, status = uccs.get_value("/Spec32/named_set_item2")
1084
1085
        self.assertEqual({ "new1": {"first": 3 }, "new2": {"second": 4}},
                         value)
1086
1087
        self.assertEqual(status, uccs.LOCAL)

1088
        uccs.set_value("/Spec32/named_set_item2/new1/second", "foo")
1089
1090

        value, status = uccs.get_value("/Spec32/named_set_item2")
1091
1092
1093
        self.assertEqual({ "new1": {"first": 3, "second": "foo" },
                           "new2": {"second": 4}},
                         value)
1094
1095
        self.assertEqual(status, uccs.LOCAL)

Jelte Jansen's avatar
Jelte Jansen committed
1096
1097
1098
1099
1100
        # make sure using a bad name still fails
        self.assertRaises(isc.cc.data.DataNotFoundError, uccs.set_value,
                          "/Spec32/named_set_item2/doesnotexist/first", 3)


1101

1102
1103
1104
1105
1106
1107
1108
    def test_commit(self):
        fake_conn = fakeUIConn()
        uccs = self.create_uccs2(fake_conn)
        uccs.commit()
        uccs._local_changes = {'Spec2': {'item5': [ 'a' ]}}
        uccs.commit()

Jelte Jansen's avatar
Jelte Jansen committed
1109
if __name__ == '__main__':
1110
    isc.log.init("bind10")
Jelte Jansen's avatar
Jelte Jansen committed
1111
1112
    unittest.main()