Debian Codegraph @

tests/unit/test_decorators.py

raw
1 try:
2 import unittest2 as unittest
3 except ImportError:
4 import unittest
5 import nose2
6
7 from lxml.etree import XML
8
9 from jnpr.junos.device import Device
10 from jnpr.junos.utils.config import Config
11 from jnpr.junos.exception import RpcError, ConfigLoadError
12 from jnpr.junos.decorators import timeoutDecorator, normalizeDecorator
13 from jnpr.junos.decorators import ignoreWarnDecorator
14
15 from unittest.mock import patch, MagicMock, PropertyMock, call
16
17 from ncclient.operations.rpc import RPCError
18 from ncclient.manager import Manager, make_device_handler
19 from ncclient.transport import SSHSession
20 from ncclient.xml_ import qualify
21
22 __author__ = "Rick Sherman"
23
24
25 class Test_Decorators(unittest.TestCase):
26 @patch("ncclient.manager.connect")
27 def setUp(self, mock_connect):
28 mock_connect.side_effect = self._mock_manager_setup
29 self.dev = Device(
30 host="1.1.1.1", user="rick", password="password123", gather_facts=False
31 )
32 self.dev.open()
33
34 def test_timeout(self):
35 with patch(
36 "jnpr.junos.Device.timeout", new_callable=PropertyMock
37 ) as mock_timeout:
38 mock_timeout.return_value = 30
39
40 def function(x):
41 return x
42
43 decorator = timeoutDecorator(function)
44 decorator(self.dev, dev_timeout=10)
45 calls = [call(), call(10), call(30)]
46 mock_timeout.assert_has_calls(calls)
47
48 def test_timeout_except(self):
49 with patch(
50 "jnpr.junos.Device.timeout", new_callable=PropertyMock
51 ) as mock_timeout:
52 mock_timeout.return_value = 30
53
54 def function(*args, **kwargs):
55 raise Exception()
56
57 decorator = timeoutDecorator(function)
58 # test to ensure the exception is raised
59 with self.assertRaises(Exception):
60 decorator(self.dev, dev_timeout=10)
61 calls = [call(), call(10), call(30)]
62 # verify timeout was set/reset
63 mock_timeout.assert_has_calls(calls)
64
65 # Test default of true and passing true keyword
66 def test_normalize_true_true(self):
67 with patch(
68 "jnpr.junos.Device.transform", new_callable=PropertyMock
69 ) as mock_transform:
70 self.dev._normalize = True
71
72 def function(x):
73 return x
74
75 decorator = normalizeDecorator(function)
76 decorator(self.dev, normalize=True)
77 self.assertFalse(mock_transform.called)
78
79 # Test default of true and passing true keyword and a func exception
80 def test_normalize_true_true_except(self):
81 with patch(
82 "jnpr.junos.Device.transform", new_callable=PropertyMock
83 ) as mock_transform:
84 self.dev._normalize = True
85
86 def function(*args, **kwargs):
87 raise Exception()
88
89 decorator = normalizeDecorator(function)
90 with self.assertRaises(Exception):
91 decorator(self.dev, normalize=True)
92 self.assertFalse(mock_transform.called)
93
94 # Test default of True and passing false keyword
95 def test_normalize_true_false(self):
96 with patch(
97 "jnpr.junos.Device.transform", new_callable=PropertyMock
98 ) as mock_transform:
99 mock_transform.return_value = "o.g."
100 self.dev._normalize = True
101
102 def function(x):
103 return x
104
105 decorator = normalizeDecorator(function)
106 decorator(self.dev, normalize=False)
107 calls = [call(), call(self.dev._nc_transform), call("o.g.")]
108 mock_transform.assert_has_calls(calls)
109
110 # Test default of True and passing false keyword and a func exception
111 def test_normalize_true_false_except(self):
112 with patch(
113 "jnpr.junos.Device.transform", new_callable=PropertyMock
114 ) as mock_transform:
115 mock_transform.return_value = "o.g."
116 self.dev._normalize = True
117
118 def function(*args, **kwargs):
119 raise Exception()
120
121 decorator = normalizeDecorator(function)
122 with self.assertRaises(Exception):
123 decorator(self.dev, normalize=False)
124 calls = [call(), call(self.dev._nc_transform), call("o.g.")]
125 mock_transform.assert_has_calls(calls)
126
127 # Test default of false and passing true keyword
128 def test_normalize_false_true(self):
129 with patch(
130 "jnpr.junos.Device.transform", new_callable=PropertyMock
131 ) as mock_transform:
132 mock_transform.return_value = "o.g."
133 self.dev._normalize = False
134
135 def function(x):
136 return x
137
138 decorator = normalizeDecorator(function)
139 decorator(self.dev, normalize=True)
140 calls = [call(), call(self.dev._norm_transform), call("o.g.")]
141 # print mock_transform.call_args_list
142 mock_transform.assert_has_calls(calls)
143
144 # Test default of false and passing true keyword and a func exception
145 def test_normalize_false_true_except(self):
146 with patch(
147 "jnpr.junos.Device.transform", new_callable=PropertyMock
148 ) as mock_transform:
149 mock_transform.return_value = "o.g."
150 self.dev._normalize = False
151
152 def function(*args, **kwargs):
153 raise Exception()
154
155 decorator = normalizeDecorator(function)
156 with self.assertRaises(Exception):
157 decorator(self.dev, normalize=True)
158 calls = [call(), call(self.dev._norm_transform), call("o.g.")]
159 # print mock_transform.call_args_list
160 mock_transform.assert_has_calls(calls)
161
162 # Test default of false and passing false keyword
163 def test_normalize_false_false(self):
164 with patch(
165 "jnpr.junos.Device.transform", new_callable=PropertyMock
166 ) as mock_transform:
167 self.dev._normalize = False
168
169 def function(x):
170 return x
171
172 decorator = normalizeDecorator(function)
173 decorator(self.dev, normalize=False)
174 self.assertFalse(mock_transform.called)
175
176 # Test default with ignore_warning not present.
177 def test_ignore_warning_missing(self):
178 def method(self, x):
179 return x
180
181 decorator = ignoreWarnDecorator(method)
182 response = decorator(self.dev, "foo")
183 self.assertEqual("foo", response)
184
185 # Test default with ignore_warning=False.
186 def test_ignore_warning_false(self):
187 def method(self, x):
188 return x
189
190 decorator = ignoreWarnDecorator(method)
191 response = decorator(self.dev, "foo", ignore_warning=False)
192 self.assertEqual("foo", response)
193
194 # Test with ignore_warning=True and only warnings.
195 def test_ignore_warning_true_3snf_warnings(self):
196 self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager_3snf_warnings)
197 cu = Config(self.dev)
198 config = """
199 delete interfaces ge-0/0/0
200 delete protocols ospf
201 delete policy-options prefix-list foo
202 """
203 self.assertTrue(cu.load(config, ignore_warning=True))
204
205 # Test with ignore_warning='statement not found' and 3 snf warnings.
206 def test_ignore_warning_string_3snf_warnings(self):
207 self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager_3snf_warnings)
208 cu = Config(self.dev)
209 config = """
210 delete interfaces ge-0/0/0
211 delete protocols ospf
212 delete policy-options prefix-list foo
213 """
214 self.assertTrue(cu.load(config, ignore_warning="statement not found"))
215
216 # Test with ignore_warning='statement not found', 1 snf warning,
217 # and 1 error.
218 def test_ignore_warning_string_1snf_warning_1err(self):
219 self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager_1snf_warning_1err)
220 cu = Config(self.dev)
221 config = """
222 delete interfaces ge-0/0/0
223 delete protcols ospf
224 delete policy-options prefix-list foo
225 """
226 with self.assertRaises(ConfigLoadError):
227 cu.load(config, ignore_warning="statement not found")
228
229 # Test with ignore_warning=True, RpcError with no errs attribute.
230 # I haven't seen this from an actual device, so this is a very contrived
231 # test.
232 def test_ignore_warning_string_1snf_warning_1err(self):
233 def method(self, x):
234 rpc_error = RPCError(XML("<foo/>"), errs=None)
235 raise rpc_error
236
237 decorator = ignoreWarnDecorator(method)
238 with self.assertRaises(RPCError):
239 decorator(self.dev, "foo", ignore_warning=True)
240
241 # Test with ignore_warning=['foo', 'statement not found'] and
242 # three statement not found warnings.
243 def test_ignore_warning_list_3snf_warnings(self):
244 self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager_3snf_warnings)
245 cu = Config(self.dev)
246 config = """
247 delete interfaces ge-0/0/0
248 delete protocols ospf
249 delete policy-options prefix-list foo
250 """
251 self.assertTrue(cu.load(config, ignore_warning=["foo", "statement not found"]))
252
253 # Test with ignore_warning='foo', and three statement not found warnings.
254 def test_ignore_warning_string_3snf_no_match(self):
255 self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager_3snf_warnings)
256 cu = Config(self.dev)
257 config = """
258 delete interfaces ge-0/0/0
259 delete protcols ospf
260 delete policy-options prefix-list foo
261 """
262 with self.assertRaises(ConfigLoadError):
263 cu.load(config, ignore_warning="foo")
264
265 # Test with ignore_warning=['foo', 'bar], and
266 # three statement not found warnings.
267 def test_ignore_warning_list_3snf_no_match(self):
268 self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager_3snf_warnings)
269 cu = Config(self.dev)
270 config = """
271 delete interfaces ge-0/0/0
272 delete protcols ospf
273 delete policy-options prefix-list foo
274 """
275 with self.assertRaises(ConfigLoadError):
276 cu.load(config, ignore_warning=["foo", "bar"])
277
278 # Test with ignore_warning=['foo', 'bar], and
279 # three warnings which are 'foo boom', 'boom bar', and 'foo bar'
280 def test_ignore_warning_list_3warn_match(self):
281 self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager_3foobar_warnings)
282 cu = Config(self.dev)
283 config = """
284 delete interfaces ge-0/0/0
285 delete protcols ospf
286 delete policy-options prefix-list foo
287 """
288 self.assertTrue(cu.load(config, ignore_warning=["foo", "bar"]))
289
290 # Test with ignore_warning=['foo', 'foo bar], and
291 # three warnings which are 'foo boom', 'boom bar', and 'foo bar'
292 def test_ignore_warning_list_3warn_no_match(self):
293 self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager_3foobar_warnings)
294 cu = Config(self.dev)
295 config = """
296 delete interfaces ge-0/0/0
297 delete protcols ospf
298 delete policy-options prefix-list foo
299 """
300 with self.assertRaises(ConfigLoadError):
301 cu.load(config, ignore_warning=["foo", "foo bar"])
302
303 def _mock_manager_setup(self, *args, **kwargs):
304 if kwargs:
305 device_params = kwargs["device_params"]
306 device_handler = make_device_handler(device_params)
307 session = SSHSession(device_handler)
308 return Manager(session, device_handler)
309
310 def _mock_manager_3snf_warnings(self, *args, **kwargs):
311 cmd = """
312 <load-configuration action="set" format="text">
313 <configuration-set>
314 delete interfaces ge-0/0/0
315 delete protocols ospf
316 delete policy-options prefix-list foo
317 </configuration-set>
318 </load-configuration>
319 """
320 rsp_string = """
321 <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/16.1R4/junos" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:1f3dfa00-3434-414a-8aa8-0073590c5812">
322 <load-configuration-results>
323 <rpc-error>
324 <error-severity>warning</error-severity>
325 <error-message>
326 statement not found
327 </error-message>
328 </rpc-error>
329 <rpc-error>
330 <error-severity>warning</error-severity>
331 <error-message>
332 statement not found
333 </error-message>
334 </rpc-error>
335 <rpc-error>
336 <error-severity>warning</error-severity>
337 <error-message>
338 statement not found
339 </error-message>
340 </rpc-error>
341 <ok/>
342 </load-configuration-results>
343 </rpc-reply>
344 """
345 rsp = XML(rsp_string)
346 errors = []
347 for err in rsp.findall(".//" + qualify("rpc-error")):
348 errors.append(RPCError(err))
349 raise RPCError(rsp, errs=errors)
350
351 def _mock_manager_3foobar_warnings(self, *args, **kwargs):
352 cmd = """
353 <load-configuration action="set" format="text">
354 <configuration-set>
355 delete interfaces ge-0/0/0
356 delete protocols ospf
357 delete policy-options prefix-list foo
358 </configuration-set>
359 </load-configuration>
360 """
361 rsp_string = """
362 <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/16.1R4/junos" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:1f3dfa00-3434-414a-8aa8-0073590c5812">
363 <load-configuration-results>
364 <rpc-error>
365 <error-severity>warning</error-severity>
366 <error-message>
367 foo boom
368 </error-message>
369 </rpc-error>
370 <rpc-error>
371 <error-severity>warning</error-severity>
372 <error-message>
373 boom bar
374 </error-message>
375 </rpc-error>
376 <rpc-error>
377 <error-severity>warning</error-severity>
378 <error-message>
379 foo bar
380 </error-message>
381 </rpc-error>
382 <ok/>
383 </load-configuration-results>
384 </rpc-reply>
385 """
386 rsp = XML(rsp_string)
387 errors = []
388 for err in rsp.findall(".//" + qualify("rpc-error")):
389 errors.append(RPCError(err))
390 raise RPCError(rsp, errs=errors)
391
392 def _mock_manager_1snf_warning_1err(self, *args, **kwargs):
393 cmd = """
394 <load-configuration action="set" format="text">
395 <configuration-set>
396 delete interfaces ge-0/0/0
397 delete protcols ospf
398 delete policy-options prefix-list foo
399 </configuration-set>
400 </load-configuration>
401 """
402 rsp_string = """
403 <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/16.1R4/junos" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:1f3dfa00-3434-414a-8aa8-0073590c5812">
404 <load-configuration-results>
405 <rpc-error>
406 <error-severity>warning</error-severity>
407 <error-message>
408 statement not found
409 </error-message>
410 </rpc-error>
411 <rpc-error>
412 <error-type>protocol</error-type>
413 <error-tag>operation-failed</error-tag>
414 <error-severity>error</error-severity>
415 <error-message>syntax error</error-message>
416 <error-info>
417 <bad-element>protcols</bad-element>
418 </error-info>
419 </rpc-error>
420 <ok/>
421 </load-configuration-results>
422 </rpc-reply>
423 """
424 rsp = XML(rsp_string)
425 errors = []
426 for err in rsp.findall(".//" + qualify("rpc-error")):
427 errors.append(RPCError(err))
428 raise RPCError(rsp, errs=errors)