-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathtest_plugin_generic.py
More file actions
1587 lines (1367 loc) · 59.3 KB
/
test_plugin_generic.py
File metadata and controls
1587 lines (1367 loc) · 59.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
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
720
721
722
723
724
725
726
727
728
729
730
731
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
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
990
991
992
993
994
995
996
997
998
999
1000
"""
Unittests for Generic plugin
"""
__author__ = "Dave Wapstra <dwapstra@cisco.com>"
import os
import re
import time
import logging
import unittest
from unittest.mock import Mock, call, patch
from concurrent.futures import ThreadPoolExecutor
multiprocessing = __import__('multiprocessing').get_context('fork')
from pyats.datastructures import AttrDict
import unicon
from unicon import Connection
from unicon.eal.dialogs import Dialog, Statement
from unicon.plugins.utils import sanitize
from unicon.plugins.tests.mock.mock_device_ios import MockDeviceTcpWrapperIOS
from unicon.mock.mock_device import MockDevice, MockDeviceTcpWrapper
from unicon.plugins.generic.statements import login_handler, password_handler, passphrase_handler
from unicon.plugins.generic.statemachine import config_transition
from pyats.topology import loader
from pyats.topology.credentials import Credentials
from unicon.core.errors import (SubCommandFailure, StateMachineError,
SpawnInitError, CredentialsExhaustedError, UniconAuthenticationError,
ConnectionError )
unicon.settings.Settings.POST_DISCONNECT_WAIT_SEC=0
unicon.settings.Settings.GRACEFUL_DISCONNECT_WAIT_SEC=0.2
class TestPasswordHandler(unittest.TestCase):
def setUp(self):
""" Prepare the mock objects for use with the tests
"""
self.session = AttrDict()
self.context = AttrDict({
'username': 'admin',
'tacacs_password': 'cisco',
'enable_password': "admin",
'line_password': "letmein"
})
class MockSpawn:
pass
def mock_sendline(*args, **kwargs):
print("Sendline called with: %s %s" % (args, kwargs))
self.spawn = MockSpawn()
self.spawn.buffer = ''
self.spawn.spawn_command = 'ssh -l cisco@router'
self.spawn.last_sent = 'ssh -l cisco@router'
self.spawn.sendline = Mock(side_effect=mock_sendline)
self.spawn.match = AttrDict()
self.spawn.match.match_output = ""
self.spawn.settings = Mock()
self.spawn.settings.PASSWORD_ATTEMPTS = 3
def _test_password_handler(self):
""" Execute password handler twice
"""
password_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
def test_ssh_password_handler_without_tacacs_with_l(self):
""" Check if password handler detects '-l' and sends tacacs password.
Send tacacs password only in retry attempt. Should not try enable passwd.
"""
self.session.tacacs_login = 0
self.spawn.spawn_command = 'ssh -l admin localhost'
self.spawn.last_sent = 'ssh -l admin localhost'
self._test_password_handler()
self.spawn.sendline.assert_has_calls([call('cisco'), call('cisco')])
def test_ssh_password_handler_without_tacacs_with_at(self):
""" Check if password handler detects 'user@host' and sends tacacs password.
Send tacacs password only in retry attempt. Should not try enable passwd.
"""
self.session.tacacs_login = 0
self.spawn.spawn_command = 'ssh admin@localhost'
self.spawn.last_sent = 'ssh admin@localhost'
self.spawn.match.match_output = """admin@locahost's password: """
self._test_password_handler()
self.spawn.sendline.assert_has_calls([call('cisco'), call('cisco')])
def test_ssh_password_handler_without_tacacs_without_indicator(self):
""" If last command is not username and start command does not contain username login
then send line password.
"""
self.session.tacacs_login = 0
self.spawn.spawn_command = 'ssh localhost'
self.spawn.last_sent = 'ssh localhost'
self._test_password_handler()
self.spawn.sendline.assert_has_calls([call('letmein'), call('letmein')])
def test_non_ssh_password_handler_without_tacacs(self):
""" Check if line password is sent, for first password prompt.
"""
self.session.tacacs_login = 0
self.spawn.spawn_command = 'telnet 127.0.0.1 2001'
self.spawn.last_sent = 'telnet 127.0.0.1 2001'
self._test_password_handler()
self.spawn.sendline.assert_has_calls([call('letmein'), call('letmein')])
def test_non_ssh_password_handler_with_tacacs(self):
""" Check if tacacs password is sent if last command sent is username.
"""
self.session.tacacs_login = 1
self.spawn.spawn_command = 'telnet 127.0.0.1 2001'
self.spawn.last_sent = self.context.username
self._test_password_handler()
self.spawn.sendline.assert_has_calls([call('cisco'), call('cisco')])
def test_enable_password(self):
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state console_test_enable'],
os='ios', enable_password='enpasswd', connection_timeout=15, mit=True)
d.connect()
def test_password_retries(self):
with self.assertRaises(UniconAuthenticationError):
for x in range(4):
password_handler(self.spawn, self.context, self.session)
class TestCredentialLoginPasswordHandlers(unittest.TestCase):
def setUp(self):
""" Prepare the mock objects for use with the tests
"""
self.session = AttrDict()
self.context = AttrDict({
'default_cred_name': 'default',
'credentials': Credentials({
'default': {
'username': 'defun',
'password': 'defpw',
'passphrase': 'this is a secret'
},
'mycred': {'username': 'admin', 'password': 'cisco'},
'enable': {'password': 'enpasswd'},
'ssh': {'passphrase': 'this is another secret'}
})
})
class MockSpawn:
pass
def mock_sendline(*args, **kwargs):
print("Sendline called with: %s %s" % (args, kwargs))
self.spawn = MockSpawn()
self.spawn.log = Mock()
self.spawn.spawn_command = 'ssh -l cisco@router'
self.spawn.last_sent = 'ssh -l cisco@router'
self.spawn.sendline = Mock(side_effect=mock_sendline)
self.spawn.match = AttrDict()
self.spawn.match.match_output = ""
self.spawn.settings = Mock()
def test_default_cred_sent_if_no_creds_given(self):
password_handler(self.spawn, self.context, self.session)
self.spawn.sendline.assert_has_calls([call('defpw')])
def test_default_cred_sent_if_no_creds_given_with_login(self):
login_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
self.spawn.sendline.assert_has_calls([call('defun'), call('defpw')])
def test_default_cred_sent_when_unknown_cred_given_with_login(self):
self.context['cred_list'] = ['badcred']
login_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
self.spawn.sendline.assert_has_calls([call('defun'), call('defpw')])
def test_unknown_cred_given_with_login(self):
self.context['cred_list'] = ['badcred']
self.context['credentials']['default'].pop('username')
with self.assertRaisesRegex(UniconAuthenticationError,
'.*No username.*badcred'):
login_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
def test_no_password_specified(self):
self.context['credentials']['default'].pop('password')
with self.assertRaisesRegex(UniconAuthenticationError,
'.*No password.*default'):
login_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
def test_alt_cred_send_login_password(self):
self.context['cred_list'] = ['mycred']
login_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
self.spawn.sendline.assert_has_calls([call('admin'), call('cisco')])
def test_default_cred_send_passphrase(self):
passphrase_handler(self.spawn, self.context, self.session)
self.spawn.sendline.assert_has_calls([call('this is a secret')])
def test_alt_cred_send_passphrase(self):
self.context['cred_list'] = ['ssh']
passphrase_handler(self.spawn, self.context, self.session)
self.spawn.sendline.assert_has_calls([call('this is another secret')])
def test_cred_seq_login_password(self):
self.context['cred_list'] = ['mycred', 'default']
login_handler(self.spawn, self.context, self.session)
login_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
login_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
self.spawn.sendline.assert_has_calls(
[call('admin'), call('cisco'),
call('defun'), call('defpw')])
def test_password_failed(self):
with self.assertRaisesRegex(CredentialsExhaustedError,
'.*tried without success.*default'):
login_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
password_handler(self.spawn, self.context, self.session)
def test_enable_password(self):
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state console_test_enable'],
os='ios', connection_timeout=15,
credentials=self.context.credentials,
mit=True)
d.connect()
def test_enable_password_default_cred_explicit(self):
credentials = Credentials({
'default': {'username': 'admin', 'password': 'cisco', 'enable_password': 'enpasswd'},
'enable': {'password': 'enpasswd2'},
})
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state console_test_enable'],
os='ios', connection_timeout=15,
credentials=credentials,
login_creds=None,
mit=True
)
d.connect()
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state login_enable'],
os='ios', connection_timeout=15,
credentials=credentials,
mit=True
)
d.connect()
def test_enable_password_default_cred_revert_enable(self):
credentials = Credentials({
'default': {'username': 'admin', 'password': 'cisco', },
'enable': {'password': 'enpasswd'},
})
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state console_test_enable'],
os='ios', connection_timeout=15,
credentials=credentials,
mit=True
)
d.connect()
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state login_enable'],
os='ios', connection_timeout=15,
credentials=credentials,
mit=True
)
d.connect()
def test_enable_password_default_cred_default_enable(self):
credentials = Credentials({
'default': {'username': 'admin', 'password': 'cisco', },
})
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state console_test_enable'],
os='ios',
connection_timeout=15,
credentials=credentials
)
with self.assertRaises(CredentialsExhaustedError):
d.connect()
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state login_enable'],
os='ios',
connection_timeout=15,
credentials=credentials
)
with self.assertRaises(CredentialsExhaustedError):
d.connect()
def test_enable_password_explicit(self):
credentials = Credentials({
'default': {'username': 'defun', 'password': 'defpw', 'enable_password': 'enpasswd2'},
'mycred': {'username': 'admin', 'password': 'cisco', 'enable_password': 'enpasswd'},
'enable': {'password': 'enpasswd3'},
})
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state console_test_enable'],
os='ios',
connection_timeout=15,
credentials=credentials,
login_creds='mycred')
d.connect()
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state login_enable'],
os='ios',
connection_timeout=15,
credentials=credentials,
login_creds='mycred')
d.connect()
def test_enable_password_explicit_revert_default(self):
credentials = Credentials({
'default': {'username': 'defun', 'password': 'defpw', 'enable_password': 'enpasswd'},
'mycred': {'username': 'admin', 'password': 'cisco', },
'enable': {'password': 'enpasswd2'},
})
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state console_test_enable'],
os='ios',
connection_timeout=15,
credentials=credentials,
login_creds='mycred')
d.connect()
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state login_enable'],
os='ios',
connection_timeout=15,
credentials=credentials,
login_creds='mycred')
d.connect()
def test_enable_password_explicit_revert_enable(self):
credentials = Credentials({
'default': {'username': 'defun', 'password': 'defpw', },
'mycred': {'username': 'admin', 'password': 'cisco', },
'enable': {'password': 'enpasswd'},
})
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state console_test_enable'],
os='ios',
connection_timeout=15,
credentials=credentials,
login_creds='mycred')
d.connect()
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state login_enable'],
os='ios',
connection_timeout=15,
credentials=credentials,
login_creds='mycred')
d.connect()
def test_enable_password_explicit_revert_default_enable(self):
credentials = Credentials({
'default': {'username': 'defun', 'password': 'defpw', },
'mycred': {'username': 'admin', 'password': 'cisco', },
})
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state console_test_enable'],
os='ios',
connection_timeout=15,
credentials=credentials,
login_creds='mycred')
with self.assertRaises(CredentialsExhaustedError):
d.connect()
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state login_enable'],
os='ios',
connection_timeout=15,
credentials=credentials,
login_creds='mycred')
with self.assertRaises(CredentialsExhaustedError):
d.connect()
def test_connect_ssh_passphrase(self):
credentials = Credentials({
'default': {'passphrase': 'this is a secret'}
})
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state connect_ssh_passphrase'],
os='ios',
connection_timeout=15,
credentials=credentials,
init_exec_commands=[],
init_config_commands=[])
d.connect()
d.disconnect()
def test_connect_ssh_no_passphrase(self):
credentials = Credentials({
'default': {'password': 'cisco'}
})
d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state connect_ssh_passphrase'],
os='ios',
connection_timeout=15,
credentials=credentials,
init_exec_commands=[],
init_config_commands=[])
with self.assertRaises(UniconAuthenticationError):
d.connect()
class TestGenericServices(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state exec'],
os='ios',
credentials=dict(default=dict(
username='cisco',
password='cisco',
)),
service_attributes=dict(ping=dict(timeout=2468)))
cls.d.connect()
cls.md = MockDevice(device_os='ios', state='exec')
cls.ha = MockDeviceTcpWrapperIOS(port=0, state='login,exec_standby')
# Add command output with 80K lines
cls.ha.mockdevice.mock_data['enable']['commands']['show ospf dummy'] = \
"123.123.123.123 123.123.123.123 1000 0x80000003 0x000000 0\n" * 80000
cls.ha.start()
cls.ha_device = Connection(hostname='Router',
start=['telnet 127.0.0.1 ' + str(cls.ha.ports[0]),
'telnet 127.0.0.1 ' + str(cls.ha.ports[1])],
os='ios',
credentials=dict(default=dict(
username='cisco',
password='cisco',
)),
init_config_commands=[],
init_exec_commands=[])
cls.ha_device.connect()
cls.logfile_testfile = '/tmp/test_log_file.log'
@classmethod
def tearDownClass(cls):
cls.d.disconnect()
cls.ha_device.disconnect()
cls.ha.stop()
try:
os.remove(cls.logfile_testfile)
except:
pass
def test_config_multiple_command_output(self):
cmd = 'do show version'
cmd_list = ['do show version', 'do show version']
ret = self.d.configure(cmd_list)
test_output = ret.replace('\r\n', '\n')
single_cmd_output = cmd + '\n' + self.md.mock_data['exec']['commands']['show version']
expected_output = single_cmd_output + single_cmd_output
self.assertEqual(expected_output, test_output)
def test_config_ha_multiple_command_output(self):
cmd = 'do show version'
cmd_list = ['do show version', 'do show version']
ret = self.ha_device.configure(cmd_list)
test_output = ret.replace('\r', '')
single_cmd_output = cmd + '\n' + self.md.mock_data['exec']['commands']['show version']
self.maxDiff = None
expected_output = single_cmd_output + single_cmd_output
self.assertEqual(expected_output, test_output)
def test_log_file(self):
self.assertIn('/tmp/', self.d.log_file())
org_file = self.d.logfile
self.d.log_file(self.logfile_testfile)
self.d.execute('show version')
with open(self.logfile_testfile) as fh:
self.assertIn('show version', fh.read())
self.d.log_file(org_file)
def test_sync_state(self):
try:
self.ha_device.sync_state()
result = True
except Exception as e:
print('Error in sync_state service: {}'.format(e))
result = False
self.assertTrue(result)
def test_execute_large_output(self):
self.ha_device.log_user(enable=False)
# If matching is slow, this command will take longer than 60 seconds
# (which is the default timeout)
self.ha_device.execute('show ospf dummy')
def test_expect_large_output(self):
self.ha_device.log_user(enable=False)
# If matching is slow, this command will take longer than 60 seconds
self.ha_device.sendline('show ospf dummy')
self.ha_device.expect('^(.*?)#', timeout=60)
def test_search_size(self):
self.assertEqual(self.d.spawn.search_size, self.d.settings.SEARCH_SIZE)
self.d.execute('', search_size=1234)
self.assertEqual(self.d.spawn.search_size, self.d.settings.SEARCH_SIZE)
def test_search_size_ha(self):
self.assertEqual(self.ha_device.active.spawn.search_size, self.ha_device.settings.SEARCH_SIZE)
self.ha_device.execute('', search_size=1234)
self.assertEqual(self.ha_device.active.spawn.search_size, self.ha_device.settings.SEARCH_SIZE)
def test_error_pattern(self):
with self.assertRaises(SubCommandFailure):
self.d.execute('unkown command', error_pattern=['^% '])
with self.assertRaises(SubCommandFailure):
self.ha_device.execute('unkown command', error_pattern=['^% '])
def test_append_error_pattern(self):
with self.assertRaises(SubCommandFailure):
self.d.execute('unkown command', append_error_pattern=['unkown command'])
with self.assertRaises(SubCommandFailure):
self.ha_device.execute('unkown command', append_error_pattern=['unkown command'])
def test_multi_thread_execute(self):
commands = ['show version'] * 3
with ThreadPoolExecutor(max_workers=3) as executor:
all_task = [executor.submit(self.d.execute, cmd)
for cmd in commands]
results = [task.result() for task in all_task]
def test_multi_process_execute(self):
class Child(multiprocessing.Process):
pass
commands = ['show version'] * 3
processes = [Child(target=self.d.execute, args=(cmd,))
for cmd in commands]
for process in processes:
process.start()
for process in processes:
process.join()
def test_execute_remove_backspace(self):
# output with a single backspae
r = self.d.execute('show command with backspace')
self.assertEqual(r, 'test')
# user sending ctrl-u to remove the command, this has multiple backspaces
self.d.send('abcdef\x15')
r = self.d.execute('show redundancy sta | in peer')
self.assertEqual(r, 'peer state = 8 -STANDBY HOT')
def test_service_attribute_patching(self):
self.assertEqual(self.d.ping.timeout, 2468)
self.assertEqual(self.ha_device.ping.timeout, 60)
class TestConfigureService(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.d = Connection(
hostname='Router',
start=['mock_device_cli --os ios --state enable'],
os='ios',
username='cisco',
tacacs_password='cisco',
enable_password='cisco',
mit=True,
log_buffer=True,
)
cls.d.connect()
cls.ha = MockDeviceTcpWrapperIOS(port=0, state='enable,exec_standby')
cls.ha.start()
cls.d_ha = Connection(
hostname='Router',
start=['telnet 127.0.0.1 ' + str(cls.ha.ports[0]),
'telnet 127.0.0.1 ' + str(cls.ha.ports[1])],
os='ios',
username='cisco',
tacacs_password='cisco',
enable_password='cisco',
log_buffer=True
)
cls.d_ha.connect()
def test_config(self):
out = self.d.configure('no logging console')
self.assertEqual(out.count('no logging console'), 1)
out = self.d.configure(['no logging console'] * 3)
self.assertEqual(out.count('no logging console'), 3)
def test_ha_config(self):
out = self.d_ha.configure('no logging console')
self.assertEqual(out.count('no logging console'), 1)
out = self.d_ha.configure(['no logging console'] * 3)
self.assertEqual(out.count('no logging console'), 3)
def test_bulk_config(self):
out = self.d.configure('no logging console', bulk=True)
self.assertEqual(out.count('no logging console'), 1)
out = self.d.configure(['no logging console'] * 3, bulk=True)
self.assertEqual(out.count('no logging console'), 3)
start = time.time()
out = self.d.configure(['no logging console'] * 3, bulk=True,
bulk_chunk_lines=2, bulk_chunk_sleep=4)
self.assertEqual(out.count('no logging console'), 3)
stop = time.time()
self.assertGreater(stop - start, 4)
self.d.configure.bulk = True
self.d.configure.bulk_chunk_lines = 2
self.d.configure.bulk_chunk_sleep = 3
start = time.time()
out = self.d.configure(['no logging console'] * 5)
self.assertEqual(out.count('no logging console'), 5)
stop = time.time()
self.assertGreater(stop - start, 6)
self.d.configure.bulk = False
def test_ha_bulk_config(self):
out = self.d_ha.configure('no logging console', bulk=True)
self.assertEqual(out.count('no logging console'), 1)
out = self.d_ha.configure(['no logging console'] * 3, bulk=True)
self.assertEqual(out.count('no logging console'), 3)
start = time.time()
out = self.d_ha.configure(['no logging console'] * 3, bulk=True,
bulk_chunk_lines=2, bulk_chunk_sleep=4)
self.assertEqual(out.count('no logging console'), 3)
stop = time.time()
self.assertGreater(stop - start, 4)
self.d_ha.configure.bulk = True
self.d_ha.configure.bulk_chunk_lines = 2
self.d_ha.configure.bulk_chunk_sleep = 3
start = time.time()
out = self.d_ha.configure(['no logging console'] * 5)
self.assertEqual(out.count('no logging console'), 5)
stop = time.time()
self.assertGreater(stop - start, 6)
self.d_ha.configure.bulk = False
def test_config_lock_retries_succeed(self):
self.d.settings.CONFIG_LOCK_RETRY_SLEEP = 1
self.d.execute('set config lock count 1')
self.d.configure('no logging console',
lock_retries=2, lock_retry_sleep=1)
self.d.configure('no logging console')
def test_config_lock_retries_fail(self):
self.d.settings.CONFIG_LOCK_RETRY_SLEEP = 1
self.d.execute('set config lock count 3')
with self.assertRaises(StateMachineError):
self.d.configure('no logging console', lock_retries=2)
def test_change_state(self):
with self.assertRaises(StateMachineError):
self.d.configure(['go to enable','go to config'], allow_state_change = False)
self.d.configure(['go to enable','go to config'], allow_state_change = True)
self.assertEqual(self.d.state_machine.current_state, 'enable')
def test_configure_error_pattern(self):
with self.assertRaises(SubCommandFailure):
self.d.configure('Not valid configuration',
error_pattern=[r'% Invalid command'])
self.assertEqual(self.d.state_machine.current_state,
self.d.configure.end_state)
def test_configure_append_error_pattern(self):
with self.assertRaises(SubCommandFailure):
self.d.configure('Not valid configuration',
append_error_pattern=[r'Not valid configuration'])
def test_configure_error_pattern2(self):
error_pattern = [r'% Invalid command']
try:
self.d.settings.CONFIGURE_ERROR_PATTERN, error_pattern = \
error_pattern, self.d.settings.CONFIGURE_ERROR_PATTERN
with self.assertRaises(SubCommandFailure):
r = self.d.configure('Not valid configuration')
finally:
self.d.settings.CONFIGURE_ERROR_PATTERN, error_pattern = \
error_pattern, self.d.settings.CONFIGURE_ERROR_PATTERN
self.assertEqual(self.d.state_machine.current_state,
self.d.configure.end_state)
def test_ha_config_lock_retries_succeed(self):
self.d_ha.execute('set config lock count 2')
self.d_ha.settings.CONFIG_LOCK_RETRY_SLEEP = 1
self.d_ha.configure('no logging console',
lock_retries=2, lock_retry_sleep=1)
self.d_ha.configure('no logging console')
def test_ha_config_lock_retries_fail(self):
self.d_ha.execute('set config lock count 3')
self.d_ha.settings.CONFIG_LOCK_RETRY_SLEEP = 1
with self.assertRaises(StateMachineError):
self.d_ha.configure('no logging console', lock_retries=2)
def test_configure_ca_trustpoint(self):
self.d.configure(['crypto pki trustpoint KEYPAIR', 'rsakeypair SSHKEYS'])
def test_configure_commit_cmd_attribute(self):
c = Connection(
hostname='Router',
start=['mock_device_cli --os ios --state enable'],
os='ios',
mit=True,
settings=dict(POST_DISCONNECT_WAIT_SEC=0,GRACEFUL_DISCONNECT_WAIT_SEC=0.2),
service_attributes=dict(configure=dict(commit_cmd="mycommit cmd")),
log_buffer=True
)
c.connect()
self.assertEqual(c.configure.commit_cmd, 'mycommit cmd')
def test_configure_user_end_exit(self):
c = Connection(
hostname='switch',
start=['mock_device_cli --os nxos --state exec'],
os='nxos',
mit=True,
settings=dict(POST_DISCONNECT_WAIT_SEC=0,GRACEFUL_DISCONNECT_WAIT_SEC=0.2),
log_buffer=True
)
c.connect()
c.configure('end')
self.assertEqual(c.state_machine.current_state, 'enable')
c.configure('exit')
self.assertEqual(c.state_machine.current_state, 'enable')
with self.assertRaises(StateMachineError):
c.configure('exitt')
c.configure(['line console', 'exit', 'exit'])
self.assertEqual(c.state_machine.current_state, 'enable')
c.disconnect()
def test_config_transition_exits_when_exclusive(self):
class FakeState:
def __init__(self, pattern):
self.pattern = pattern
class FakeStateMachine:
config_command = 'config term'
def __init__(self):
self.current_state = 'enable'
def get_state(self, name):
return FakeState(pattern=name)
def detect_state(self, spawn):
self.current_state = 'enable'
def go_to(self, target, spawn):
self.current_state = 'exclusive'
class FakeSpawn:
def __init__(self):
self.sent = []
self.settings = AttrDict(
CONFIG_LOCK_RETRY_SLEEP=0,
CONFIG_LOCK_RETRIES=1,
CONFIG_TIMEOUT=1,
)
self.log = logging.getLogger(__name__)
self.buffer = ''
def sendline(self, cmd=''):
self.sent.append(cmd)
sm = FakeStateMachine()
spawn = FakeSpawn()
with patch.object(Dialog, 'process', return_value=None):
config_transition(sm, spawn, context={})
self.assertGreaterEqual(len(spawn.sent), 2)
self.assertEqual(spawn.sent[0], 'config term')
self.assertEqual(spawn.sent.count('config term'), 1)
self.assertEqual(sm.current_state, 'exclusive')
@classmethod
def tearDownClass(cls):
cls.d.disconnect()
cls.d_ha.disconnect()
cls.ha.stop()
class TestExecuteService(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.d = Connection(hostname='Router',
start=['mock_device_cli --os ios --state exec'],
os='ios', enable_password='cisco',
username='cisco',
tacacs_password='cisco')
cls.d.connect()
cls.md = MockDevice(device_os='ios', state='exec')
cls.ha = MockDeviceTcpWrapperIOS(port=0, state='login,exec_standby')
cls.ha.start()
cls.ha_device = Connection(hostname='Router',
start=['telnet 127.0.0.1 '+ str(cls.ha.ports[0]), 'telnet 127.0.0.1 '+ str(cls.ha.ports[1]) ],
os='ios', username='cisco', tacacs_password='cisco', enable_password='cisco',
init_config_commands=[], init_exec_commands=[])
cls.ha_device.connect()
@classmethod
def tearDownClass(cls):
cls.d.disconnect()
cls.ha_device.disconnect()
cls.ha.stop()
def setUp(self):
self.d.enable()
self.ha_device.enable()
self.d.settings.EXEC_ALLOW_STATE_CHANGE = False
def test_universal_execute(self):
self.d.execute('config term', allow_state_change=True)
self.assertEqual(self.d.state_machine.current_state, 'config')
self.d.execute('line console 0')
self.assertEqual(self.d.state_machine.current_state, 'config')
self.d.settings.EXEC_ALLOW_STATE_CHANGE = True
self.d.execute('end')
self.assertEqual(self.d.state_machine.current_state, 'enable')
self.d.execute('disable')
self.assertEqual(self.d.state_machine.current_state, 'disable')
self.d.execute('enable', reply=Dialog([[r'^(.*?)Password:', 'sendline_ctx(tacacs_password)', None, False, False]]))
self.assertEqual(self.d.state_machine.current_state, 'enable')
self.d.execute('disable')
self.assertEqual(self.d.state_machine.current_state, 'disable')
self.ha_device.execute('config term', allow_state_change=True)
self.assertEqual(self.ha_device.active.state_machine.current_state, 'config')
def test_execute_allow_state_change(self):
with self.assertRaises(StateMachineError) as e1:
self.d.execute('config term')
self.assertEqual(self.d.state_machine.current_state, 'config')
self.ha_device.settings.EXEC_ALLOW_STATE_CHANGE = True
with self.assertRaises(StateMachineError) as e2:
self.ha_device.execute('config term', allow_state_change=False)
self.assertEqual(self.ha_device.active.state_machine.current_state, 'config')
def test_execute_with_more_backspace(self):
self.d.settings.MORE_CONTINUE = '\r'
output = self.d.execute('show command with more backspace')
self.assertEqual(output, 'first\r\n\r\nsecond\r\n\r\nthird')
self.assertEqual(repr(output), repr('first\r\n\r\nsecond\r\n\r\nthird'))
def test_execute_with_escape_more_backspace(self):
self.d.settings.MORE_CONTINUE = '\r'
output = self.d.execute('show command with escape more backspace')
self.assertEqual(output, 'first\r\n\r\nsecond\r\n\r\nthird')
self.assertEqual(repr(output), repr('first\r\n\r\nsecond\r\n\r\nthird'))
def test_execute_with_escape_more(self):
self.d.settings.MORE_CONTINUE = '\r'
output = self.d.execute('show command with escape more')
self.assertEqual(output, 'first\r\n\r\nsecond\r\n\r\nthird')
self.assertEqual(repr(output), repr('first\r\n\r\nsecond\r\n\r\nthird'))
def test_execute_with_more(self):
self.d.settings.MORE_CONTINUE = '\r'
output = self.d.execute('show command with more')
self.assertEqual(output, 'first\r\n\r\nsecond\r\n\r\nthird')
self.assertEqual(repr(output), repr('first\r\n\r\nsecond\r\n\r\nthird'))
def test_execute_with_transient_match_1(self):
output = self.d.execute('show command with transient match',
matched_retries=3,
matched_retry_sleep=7)
self.assertEqual(output, 'head\r\nRouter#\r\ntail')
def test_execute_with_transient_match_2(self):
self.d.execute.matched_retry_sleep = 20
try:
output = self.d.execute('show command with transient match')
self.assertEqual(output, 'head\r\nRouter#\r\ntail')
finally:
self.d.execute.matched_retry_sleep = \
self.d.settings.EXECUTE_MATCHED_RETRY_SLEEP
class TestServiceLogging(unittest.TestCase):
@classmethod
def setUpClass(cls):
testbed = """
devices:
R1:
os: iosxe
alias: uut
connections:
defaults:
class: unicon.Unicon
a:
command: mock_device_cli --os iosxe --state general_enable --hostname R1
"""
t = loader.load(testbed)
cls.d = t.devices.uut
cls.d.connect(mit=True)
@classmethod
def tearDownClass(cls):
cls.d.disconnect()
def test_execute_logging(self):
self.maxDiff = None
with self.assertLogs(self.d.log.name, logging.INFO) as cm:
self.d.execute('show version')
self.assertIn("R1(alias=uut) with via 'a'", cm.output[0])
class TestTransmitReceive(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.d = Connection(
hostname='Router',
start=['mock_device_cli --os ios --state exec'],
os='ios', enable_password='cisco',
username='cisco',
tacacs_password='cisco'
)
cls.d.connect()
cls.term_buffer_pattern = re.compile(r'term width 0.*#', re.S)
@classmethod
def tearDownClass(cls):
cls.d.disconnect()
def test_transmit(self):
self.assertTrue(self.d.transmit('term width 0\r'))
def test_receive_when_match(self):
self.d.send('term width 0\r')
self.assertTrue(self.d.receive(r'.*#'))
self.assertRegex(self.d.receive_buffer(), self.term_buffer_pattern)
def test_receive_buffer(self):
self.d.sendline('term width 0')
self.d.receive(r'^.*#')
self.assertRegex(self.d.receive_buffer(), self.term_buffer_pattern)
def test_receive_nopattern(self):
self.d.transmit('term width 0\r')
self.assertFalse(self.d.receive(r'nopattern^', timeout=10))
self.assertRegex(self.d.receive_buffer(), self.term_buffer_pattern)
def test_receive_no_match(self):
self.d.transmit('term width 0\r')
self.assertFalse(self.d.receive(r'somepattern', timeout=10))
self.assertEqual(self.d.receive_buffer(), '')
def test_receive_after_receive_no_match(self):
self.d.sendline('term width 0')
self.assertFalse(self.d.receive(r'wrongpattern', timeout=10))
self.assertEqual(self.d.receive_buffer(), '')
self.assertTrue(self.d.receive(r'term width 0.*#', timeout=10))
self.assertRegex(self.d.receive_buffer(), self.term_buffer_pattern)
def test_receive_nopattern_after_receive_no_match(self):
self.d.sendline('term width 0')
self.assertFalse(self.d.receive(r'wrongpattern', timeout=10))
self.assertEqual(self.d.receive_buffer(), '')
self.assertFalse(self.d.receive(r'nopattern^', timeout=10))