Debian Codegraph @

tests/unit/factory/test_cfgtable.py

raw ◀ ▶
1 Debian patch touch this file
1 __author__ = "Rick Sherman, Nitin Kumar"
2 __credits__ = "Jeremy Schulman"
3
4 import unittest
5 import os
6 import sys
7
8 import nose2
9 import yaml
10
11 from jnpr.junos import Device
12
13 from ncclient.manager import Manager, make_device_handler
14 from ncclient.transport import SSHSession
15 from lxml import etree
16 from unittest.mock import MagicMock, patch
17
18 from jnpr.junos.factory import loadyaml
19 from jnpr.junos.factory.factory_loader import FactoryLoader
20
21 try:
22 _YAML_ = loadyaml("lib/jnpr/junos/cfgro/srx")
23 except:
24 # Try to load the template relative to test base
25 try:
26 _YAML_ = loadyaml(
27 os.path.join(
28 os.path.dirname(__file__), "../../..", "lib/jnpr/junos/cfgro/srx.yml"
29 )
30 )
31 except:
•32 _YAML_ = dict()
33
34 globals().update(_YAML_)
35
36 yaml_data = """---
37 UserTable:
38 get: system/login/user
39 required_keys:
40 user: name
41 view: userView
42
43 userView:
44 groups:
45 auth: authentication
46 fields:
47 uid: uid
48 class: class
49 uidgroup: { uid: group }
50 fullgroup: { full-name: group }
51 fields_auth:
52 pass: encrypted-password
53
54 GroupTable:
55 get: groups
56 item:
57 args_key: name
58 options: {}
59 """
60 globals().update(FactoryLoader().load(yaml.load(yaml_data, Loader=yaml.FullLoader)))
61
62 yaml_bgp_data = """---
63 BgpTable:
64 set: protocols/bgp/group
65 key-field:
66 - bgp_name
67 view: BgpView
68
69 BgpView:
70 groups:
71 neigh : neighbor
72 fields:
73 bgp_name : { 'name' :
74 { 'type' : 'str', 'minValue' : 3, 'maxValue': 12 } }
75 bgp_type : {'type' :
76 {'type': { 'enum': ['external', 'internal'] },
77 'default': 'external' } }
78 local_addr : local-address
79 peer : { 'peer-as' :
80 { 'type' : 'int', 'minValue': 0, 'maxValue': 200} }
81 fields_neigh:
82 neigh : name
83 """
84
85 globals().update(FactoryLoader().load(yaml.load(yaml_bgp_data, Loader=yaml.FullLoader)))
86
87
•88 @unittest.skipIf(True, "will try again in January")
89 class TestFactoryCfgTable(unittest.TestCase):
90 @patch("ncclient.manager.connect")
91 def setUp(self, mock_connect):
92 mock_connect.side_effect = self._mock_manager
93 self.dev = Device(
94 host="1.1.1.1", user="rick", password="password123", gather_facts=False
95 )
96 self.dev.open()
97 self.zit = ZoneIfsTable(self.dev)
98 self.ut = UserTable(self.dev)
99 self.bgp = BgpTable(self.dev)
100
101 def test_cfgtable_path(self):
102 fname = "user.xml"
103 path = os.path.join(os.path.dirname(__file__), "rpc-reply", fname)
104 ut = UserTable(path=path)
105 ut.get()
106 self.assertEqual(ut[0].uid, "2000")
107
108 def test_cfgtable_xml(self):
109 fname = "user.xml"
110 xml = self._read_file(fname)
111 ut = UserTable(xml=xml)
112 ut.get()
113 self.assertEqual(ut[0].uid, "2000")
114
115 @patch("jnpr.junos.Device.execute")
116 def test_cfgtable_junos(self, mock_execute):
117 mock_execute.side_effect = self._mock_manager
118 self.dev.ON_JUNOS = True
119 self.ut.get(user="test")
120 self.assertEqual(self.ut[0]["uidgroup"], "global")
121
122 @patch("jnpr.junos.Device.execute")
123 @patch("jnpr.junos.jxml.conf_transform")
124 def test_cfgtable_junos1(self, mock_jxml, mock_execute):
125 mock_execute.side_effect = self._mock_manager
126 mock_jxml.result_value = None
127 with patch.dict("sys.modules", junos=MagicMock()):
128 import junos
129
130 self.dev.ON_JUNOS = True
131 self.bgp.get()
132 self.assertEqual(self.bgp.bgp_type, "external")
133
134 @patch("jnpr.junos.Device.execute")
135 @patch("jnpr.junos.jxml.conf_transform")
136 def test_cfgtable_junos2(self, mock_jxml, mock_execute):
137 mock_execute.side_effect = self._mock_manager
138 mock_jxml.result_value = None
139 with patch.dict("sys.modules", junos=MagicMock()):
140 import junos
141
142 junos.Junos_Configuration = None
143 self.dev.ON_JUNOS = True
144 self.bgp.get()
145 self.assertEqual(self.bgp.bgp_type, "external")
146
147 @patch("jnpr.junos.Device.execute")
148 def test_cfgtable_get(self, mock_execute):
149 mock_execute.side_effect = self._mock_manager
150 self.zit.get(security_zone="untrust")
151 self.assertEqual(len(self.zit), 1)
152
153 @patch("jnpr.junos.Device.execute")
154 def test_cfgtable_get_group(self, mock_execute):
155 mock_execute.side_effect = self._mock_manager
156 self.ut.get(user="test")
157 self.assertEqual(self.ut[0]["uidgroup"], "global")
158
159 @patch("jnpr.junos.Device.execute")
160 def test_cfgtable_get_namesonly(self, mock_execute):
161 mock_execute.side_effect = self._mock_manager
162 self.zit.get(security_zone="untrust", namesonly=True)
163 self.assertEqual(self.zit._get_cmd.xpath("//@recurse")[0], "false")
164
165 @patch("jnpr.junos.Device.execute")
166 def test_cfgtable_get_options(self, mock_execute):
167 mock_execute.side_effect = self._mock_manager
168 self.zit.get(
169 security_zone="untrust", options={"inherit": "defaults", "groups": "groups"}
170 )
171 self.assertEqual(self.zit._get_opt, {"inherit": "defaults", "groups": "groups"})
172
173 @patch("jnpr.junos.Device.execute")
174 def test_cfgtable_table_options(self, mock_execute):
175 mock_execute.side_effect = self._mock_manager
176 gt = GroupTable(self.dev)
177 gt.get()
178 self.assertEqual(gt._get_opt, {})
179
180 def test_optable_get_key_required_error(self):
181 self.assertRaises(ValueError, self.zit.get)
182
183 @patch("jnpr.junos.Device.execute")
184 def test_cfgtable_get_caller_provided_kvargs(self, mock_execute):
185 mock_execute.side_effect = self._mock_manager
186 self.zit.get(security_zone="untrust", key="test")
187 self.assertTrue(mock_execute.called)
188
189 def test_cfgtable_key_value_none(self):
190 self.assertRaises(ValueError, self.zit.get, securityzone="untrust")
191
192 @patch("jnpr.junos.Device.execute")
193 def test_cfgtable_get_fields(self, mock_execute):
194 mock_execute.side_effect = self._mock_manager
195 self.zit._data_dict["get_fields"] = ["system-services"]
196 self.zit.get(security_zone="untrust", key="host-inbound-traffic")
197 self.assertTrue("get_fields" in self.zit._data_dict)
198
199 def test_cfgtable_dot_none_RuntimeError(self):
200 ret_val = (
201 "<configuration><security><zones><test-zone>"
202 '<interfaces recurse="false"/></test-zone></zones>'
203 "</security></configuration>"
204 )
205 self.zit._buildxml = MagicMock(return_value=etree.fromstring(ret_val))
206 self.assertRaises(RuntimeError, self.zit.get, security_zone="abc")
207
208 @patch("jnpr.junos.Device.execute")
209 def test_cfgtable_set(self, mock_execute):
210 self.bgp.rpc.lock_configuration = MagicMock()
211 self.bgp.bgp_name = "external_1"
212 self.bgp.append()
213 self.bgp.set()
214 xml = self.bgp.get_table_xml()
215 self.assertEqual(xml.xpath("protocols/bgp/group/name")[0].text, "external_1")
216
217 @patch("jnpr.junos.Device.execute")
218 def test_cfgtable_set_inactive(self, mock_execute):
219 yaml_auto_data = """---
220 UserConfigTable1:
221 set: system/login
222 key-field:
223 - username
224 view: UserConfigView1
225
226 UserConfigView1:
227 groups:
228 auth: authentication
229 fields:
230 user: user
231 username: user/name
232 classname: { user/class : { 'type' : { 'enum' : ['operator', 'read-only', 'super-user'] } } }
233 uid: { user/uid : { 'type' : 'int', 'minValue' : 100, 'maxValue' : 64000 } }
234 fields_auth:
235 password: user/encrypted-password
236 """
237 globals().update(
238 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
239 )
240 at = UserConfigTable1(self.dev)
241 at.rpc.lock_configuration = MagicMock()
242 at.username = "user1"
243 at.user = {"inactive": "inactive"}
244 at.append()
245 at.set()
246 xml = at.get_table_xml()
247 self.assertEqual(
248 xml.xpath('system/login/user[@inactive="inactive"]/name')[0].text, "user1"
249 )
250
251 @patch("jnpr.junos.Device.execute")
252 def test_cfgtable_set_bool(self, mock_execute):
253 yaml_auto_data = """---
254 UserConfigTable1:
255 set: system/login
256 key-field:
257 - username
258 view: UserConfigView1
259
260 UserConfigView1:
261 groups:
262 auth: authentication
263 fields:
264 user: user
265 username: user/name
266 classname: { user/class : { 'type' : { 'enum' : ['operator', 'read-only', 'super-user'] } } }
267 uid: { user/uid : { 'type' : bool , 'default' :False} }
268 fields_auth:
269 password: user/encrypted-password
270 """
271 globals().update(
272 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
273 )
274 at = UserConfigTable1(self.dev)
275 at.rpc.lock_configuration = MagicMock()
276 at.username = True
277 at.user = {"inactive": "inactive"}
278 at.append()
279 at.set()
280 xml = at.get_table_xml()
281 self.assertNotEqual(xml.xpath("system/login/user/name")[0].text, "user1")
282
283 @patch("jnpr.junos.Device.execute")
284 def test_cfgtable_load(self, mock_execute):
285 self.bgp.rpc.lock_configuration = MagicMock()
286 self.bgp.bgp_name = "external_1"
287 self.bgp.append()
288 self.bgp.bgp_name = "external_2"
289 self.bgp.append()
290 self.bgp.load()
291 xml = self.bgp.get_table_xml()
292 self.assertEqual(xml.xpath("protocols/bgp/group/name")[0].text, "external_1")
293 self.assertEqual(xml.xpath("protocols/bgp/group/name")[1].text, "external_2")
294
295 @patch("jnpr.junos.Device.execute")
296 def test_cfgtable_set_group(self, mock_execute):
297 self.bgp.rpc.lock_configuration = MagicMock()
298 self.bgp.bgp_name = "external_1"
299 self.bgp.neigh = ["30.30.10.10"]
300 self.bgp.bgp_type = "external"
301 self.bgp.append()
302 self.bgp.set()
303 xml = self.bgp.get_table_xml()
304 self.assertEqual(xml.xpath("protocols/bgp/group/name")[0].text, "external_1")
305 self.assertEqual(
306 xml.xpath("protocols/bgp/group/neighbor/name")[0].text, "30.30.10.10"
307 )
308 self.assertEqual(xml.xpath("protocols/bgp/group/type")[0].text, "external")
309
310 @patch("jnpr.junos.Device.execute")
311 def test_cfgtable_dict_set(self, mock_execute):
312 self.bgp.rpc.lock_configuration = MagicMock()
313 self.bgp["bgp_name"] = "external_3"
314 self.bgp.append()
315 self.bgp.set()
316 xml = self.bgp.get_table_xml()
317 self.assertEqual(xml.xpath("protocols/bgp/group/name")[0].text, "external_3")
318
319 @patch("jnpr.junos.Device.execute")
320 def test_cfgtable_invalid_field_error(self, mock_execute):
321 def invalid_field():
322 self.bgp.xyz = "bad"
323
324 self.assertRaises(ValueError, invalid_field)
325
326 @patch("jnpr.junos.Device.execute")
327 def test_cfgtable_invalid_field_dict_error(self, mock_execute):
328 def invalid_field_dict():
329 self.bgp["xyz"] = "bad"
330
331 self.assertRaises(ValueError, invalid_field_dict)
332
333 @patch("jnpr.junos.Device.execute")
334 def test_cfgtable_set_no_key_error(self, mock_execute):
335 self.assertRaises(ValueError, self.bgp.append)
336
337 @patch("jnpr.junos.Device.execute")
338 def test_cfgtable_enum_error(self, mock_execute):
339 self.bgp.bgp_name = "external_1"
340 self.bgp.bgp_type = "abc"
341 self.assertRaises(ValueError, self.bgp.append)
342
343 @patch("jnpr.junos.Device.execute")
344 def test_cfgtable_str_min_max_value_error(self, mock_execute):
345 self.bgp.bgp_name = "ex"
346 self.assertRaises(ValueError, self.bgp.append)
347
348 @patch("jnpr.junos.Device.execute")
349 def test_cfgtable_int_min_max_value_error(self, mock_execute):
350 self.bgp.bgp_name = "external_1"
351 self.bgp.peer = 300
352 self.assertRaises(ValueError, self.bgp.append)
353
354 @patch("jnpr.junos.Device.execute")
355 def test_cfgtable_invalid_field_value_error(self, mock_execute):
356 self.bgp.bgp_name = "external_1"
357 self.bgp.peer = [[100]]
358 self.assertRaises(ValueError, self.bgp.append)
359
360 @patch("jnpr.junos.Device.execute")
361 def test_cfgtable_str_key_field(self, mock_execute):
362 yaml_auto_data = """---
363 AutoSysTable:
364 set: routing-options/autonomous-system
365 key-field:
366 as_num
367 view: AutoSysView
368
369 AutoSysView:
370 fields:
371 as_num: as-number
372 """
373 globals().update(
374 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
375 )
376 at = AutoSysTable(self.dev)
377 at.rpc.lock_configuration = MagicMock()
378 at.as_num = 100
379 at.append()
380 at.set()
381 xml = at.get_table_xml()
382 self.assertEqual(
383 xml.xpath("routing-options/autonomous-system/as-number")[0].text, "100"
384 )
385
386 @patch("jnpr.junos.Device.execute")
387 def test_cfgtable_field_value_xpath(self, mock_execute):
388 yaml_auto_data = """---
389 AutoSysTable:
390 set: routing-options
391 key-field:
392 as_num
393 view: AutoSysView
394
395 AutoSysView:
396 fields:
397 as_num: autonomous-system/as-number
398 """
399 globals().update(
400 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
401 )
402 at = AutoSysTable(self.dev)
403 at.rpc.lock_configuration = MagicMock()
404 at.as_num = 150
405 at.append()
406 at.set()
407 xml = at.get_table_xml()
408 self.assertEqual(
409 xml.xpath("routing-options/autonomous-system/as-number")[0].text, "150"
410 )
411
412 @patch("jnpr.junos.Device.execute")
413 def test_cfgtable_user_defined_type_error(self, mock_execute):
414 yaml_auto_data = """---
415 AutoSysTable:
416 set: routing-options/autonomous-system
417 key-field:
418 - as_num
419 view: AutoSysView
420
421 AutoSysView:
422 fields:
423 as_num: {'as-number': {'type': {'UserDefined': ''}}}
424 """
425 globals().update(
426 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
427 )
428 at = AutoSysTable(self.dev)
429 at.rpc.lock_configuration = MagicMock()
430 at.as_num = 100
431 self.assertRaises(TypeError, at.append)
432
433 @patch("jnpr.junos.Device.execute")
434 def test_cfgtable_wrong_type_error(self, mock_execute):
435 yaml_auto_data = """---
436 AutoSysTable:
437 set: routing-options/autonomous-system
438 key-field:
439 - as_num
440 view: AutoSysView
441
442 AutoSysView:
443 fields:
444 as_num: {'as-number' : { 'type' : 'int'} }
445 """
446 globals().update(
447 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
448 )
449 at = AutoSysTable(self.dev)
450 at.as_num = "100"
451 self.assertRaises(TypeError, at.append)
452
453 @patch("jnpr.junos.Device.execute")
454 def test_cfgtable_unsupported_type_error(self, mock_execute):
455 yaml_auto_data = """---
456 AutoSysTable:
457 set: routing-options/autonomous-system
458 key-field:
459 - as_num
460 view: AutoSysView
461
462 AutoSysView:
463 fields:
464 as_num: {'as-number' : { 'type' : 'interger'} }
465 """
466 globals().update(
467 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
468 )
469 at = AutoSysTable(self.dev)
470 at.as_num = 100
471 self.assertRaises(TypeError, at.append)
472
473 @patch("jnpr.junos.Device.execute")
474 def test_cfgtable_enum_value_str_error(self, mock_execute):
475 yaml_auto_data = """---
476 AutoSysTable:
477 set: routing-options/autonomous-system
478 key-field:
479 - as_num
480 view: AutoSysView
481
482 AutoSysView:
483 fields:
484 as_num: {'as-number' : {'type' : {'enum': '100'}}}
485 """
486 globals().update(
487 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
488 )
489 at = AutoSysTable(self.dev)
490 at.as_num = 100
491 self.assertRaises(ValueError, at.append)
492
493 @patch("jnpr.junos.Device.execute")
494 def test_cfgtable_enum_value_type_error(self, mock_execute):
495 yaml_auto_data = """---
496 AutoSysTable:
497 set: routing-options/autonomous-system
498 key-field:
499 - as_num
500 view: AutoSysView
501
502 AutoSysView:
503 fields:
504 as_num: {'as-number' : {'type' : {'enum': {'100': ''}}}}
505 """
506 globals().update(
507 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
508 )
509 at = AutoSysTable(self.dev)
510 at.as_num = 100
511 self.assertRaises(TypeError, at.append)
512
513 @patch("jnpr.junos.Device.execute")
514 def test_cfgtable_invalid_type_error(self, mock_execute):
515 yaml_auto_data = """---
516 AutoSysTable:
517 set: routing-options/autonomous-system
518 key-field:
519 - as_num
520 view: AutoSysView
521
522 AutoSysView:
523 fields:
524 as_num: {'as-number': {'type': ['abc']}}
525 """
526 globals().update(
527 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
528 )
529 at = AutoSysTable(self.dev)
530 at.as_num = 100
531 self.assertRaises(TypeError, at.append)
532
533 @patch("jnpr.junos.Device.execute")
534 def test_cfgtable_invalid_key_field_type_error(self, mock_execute):
535 yaml_auto_data = """---
536 AutoSysTable:
537 set: routing-options/autonomous-system
538 key-field:
539 as_num : as-number
540 view: AutoSysView
541
542 AutoSysView:
543 fields:
544 as_num: as-number
545 """
546 globals().update(
547 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
548 )
549 self.assertRaises(TypeError, AutoSysTable, self.dev)
550
551 @patch("jnpr.junos.Device.execute")
552 def test_cfgtable_invalid_key_field_not_defined_error(self, mock_execute):
553 yaml_auto_data = """---
554 AutoSysTable:
555 set: routing-options/autonomous-system
556 view: AutoSysView
557
558 AutoSysView:
559 fields:
560 as_num: as-number
561 """
562 globals().update(
563 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
564 )
565 self.assertRaises(ValueError, AutoSysTable, self.dev)
566
567 @patch("jnpr.junos.Device.execute")
568 def test_cfgtable_invalid_view_not_defined_type_error(self, mock_execute):
569 yaml_auto_data = """---
570 AutoSysTable:
571 set: routing-options/autonomous-system
572 """
573 globals().update(
574 FactoryLoader().load(yaml.load(yaml_auto_data, Loader=yaml.FullLoader))
575 )
576 self.assertRaises(ValueError, AutoSysTable, self.dev)
577
578 @patch("jnpr.junos.Device.execute")
579 def test_cfgtable_set_append_not_call_error(self, mock_execute):
580 self.bgp.rpc.lock_configuration = MagicMock()
581 self.bgp["bgp_name"] = "external_3"
582 self.assertRaises(RuntimeError, self.bgp.set)
583
584 @patch("jnpr.junos.Device.execute")
585 def test_cfgtable_load_append_not_call_error(self, mock_execute):
586 self.bgp["bgp_name"] = "external_3"
587 self.assertRaises(RuntimeError, self.bgp.load)
588
589 @patch("jnpr.junos.Device.execute")
590 def test_cfgtable_unfreeze(self, mock_execute):
591 self.bgp._unfreeze()
592 self.assertEqual(self.bgp._CfgTable__isfrozen, False)
593
594 @patch("jnpr.junos.Device.execute")
595 @patch("jnpr.junos.utils.config.Config.lock")
596 @patch("jnpr.junos.utils.config.Config.unlock")
597 def test_cfgtable_with_block(self, mock_execute, mock_unlock, mock_lock):
598 with BgpTable(self.dev, mode="exclusive") as bgp:
599 bgp.rpc.lock_configuration = MagicMock()
600 bgp.bgp_name = "external_1"
601 bgp.append()
602 bgp.load()
603 self.assertTrue(mock_lock.called and mock_unlock.called)
604
605 def _read_file(self, fname):
606 from ncclient.xml_ import NCElement
607
608 fpath = os.path.join(os.path.dirname(__file__), "rpc-reply", fname)
609
610 foo = open(fpath).read()
611
612 if fname == "user.xml":
613 return etree.fromstring(foo)
614
615 rpc_reply = NCElement(
616 foo, self.dev._conn._device_handler.transform_reply()
617 )._NCElement__doc[0]
618 return rpc_reply
619
620 def _mock_manager(self, *args, **kwargs):
621 if kwargs:
622 device_params = kwargs["device_params"]
623 device_handler = make_device_handler(device_params)
624 session = SSHSession(device_handler)
625 return Manager(session, device_handler)
626
627 if args:
628 if args[0].xpath("//configuration/system/login/user"):
629 return self._read_file("get-configuration-user.xml")
630 else:
631 return self._read_file(args[0].tag + ".xml")