-
Notifications
You must be signed in to change notification settings - Fork 18
/
Common.py
1806 lines (1461 loc) · 58.7 KB
/
Common.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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
# -*- coding: utf-8 -*-
# Copyright 2017-2020 NTT Communications
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Common library for RENAT
It loads config files and create necessary varibles. The file should be the 1st
library included from any test case.
== Table of Contents ==
- `Configuration file`
- `Variables`
- `Shortcuts`
- `Keywords`
= Configuration file =
== Global configuration ==
There are 2 important configuration files. The global configuration files (aka
master files) include device information, authentication etc that are used for
all the test cases in the suite. The local configuration file ``local.yaml``
includes information about nodes, tester ports etc. that are used in a specific
test case.
At the beginning, the module makes a local copy the master files and initialize
necessary variables.
The RENAT framework utilized the YAML format for its configurations file.
The master files folder is defined by ``renat-master-folder`` in
``$RENAT_PATH/config/config.yaml``. Usually, users do not need to modify the
master files. The most common case is when new device is deployed, the
``device.yaml`` need to be update so that device could be used in the test
cases.
=== 1. device.yaml: contains global device information ===
Each device information is store under ``device`` block and has the following
format:
| <node_name>
| type: <device type>
| description: <any useful description>
| ip: <the IPv4 address of the device
Where <node_name> is the name of the device. It could be the name of a switch,
router or a web appliance box and should be uniq between the devices.
<description> is any useful information and <ip> is the IP that RENAT
uses to access the device.
<type> is important because it will be used as a key of the ``access_template``
in template file. Usually users do not need to invent a new type but should use
the existed type. When a new platform need to be supported, a new type will be
introduced with the correspon template and authentication information.
Examples:
| device:
| apollo:
| type: ssh-host
| description: main server
| ip: 10.128.3.101
| artermis:
| type: ssh-host
| description: second server
| ip: 10.128.3.91
| vmx11:
| type: juniper
| description: r1
| ip: 10.128.64.11
| vmx12:
| type: juniper
| description: r2
| ip: 10.128.64.12
=== 2. template.yaml: contains device template information ===
The template file contains information about how to access to the device and how
it should polling information ( SNMP only for now). Each template has the
following format:
| <type>:
| access: ssh, telnet or jump
| auth: plaint-text or public-key
| profile: authentication profile name
| prompt: a regular expression for the PROMPT of the CLI device> (optional)
| login_prompt: a login PROMPT for CLI device (optional)
| password_prompt:a PROMPT for asking password of CLI device (optional)
| append: a phrase to append automatically for every CLI command that executes> on this device (optional>
| init: an array of command that will be executed automatically after a sucessful login of CLI device> (optional)
| target: another type (mandatory in case of access is ``jump``
*Note*: Becareful about the prompt field. Usually RENAT will wait until it could
see the prompt in its output. A wrong prompt will halt the system until it is
timed out.
Examples:
| access-template:
| # template for an oridnary UNIX server access by SSH
| ssh-host:
| access: ssh
| auth: public-key
| profile: default
| prompt: \$
| append:
| init: unalias -a
| # template for a Juniper router
| juniper:
| access: telnet
| auth: plain-text
| profile: default
| prompt: "(#|>) "
| append: ' | no-more'
| init:
| # template for a Cisco router
| cisco:
| access: ssh
| auth: plain-text
| profile: default
| prompt: "\@.*(#|>) "
| append:
| init:
| # template for a Juniper router access through a SmartCS console server
| jump-smartcs:
| access: jump
| access_base: telnet
| auth: plain-text
| profile: default
| prompt: "tty.*> "
| password_prompt: "Password:"
| target: juniper
| snmp-template:
| juniper:
| mib: ./mib-Juniper.json
| community: public
| poller: renat
| cisco:
| mib: ./mib-Cisco.json
| community: public
=== 3. auth.yaml: contains authentication information ===
The file contains authentication information that system uses when access to a
device. Each authencation type has follwing format:
| plain-text
| <profile>
| user: <user name>
| password: <password>
or
| public-key:
| <profile>:
| user: <user name>
| key: <public key path>
Where <profile> is the name of the authentication profile specificed in the
``access template`` of the device
Example:
| auth:
| plain-text:
| default:
| user: user
| pass: xxxxxx
| flets:
| user: user
| pass: xxxxxx
| arbor:
| user: admin
| pass: xxxxxx
|
| public-key: # for Public Key authentication
| default:
| user: robot
| key: /home/user/.ssh/robot_id_rsa
| test:
| user: jenkins
| key: /var/lib/jenkins/.ssh/id_rsa
== Local Configuration ==
Local configuration (aka ``local.yaml``) was used by a test case of its sub test
cases. Test cases could includes several test cases (the sub level is not
limited). The local configuration is defined by ``local.yaml`` in the ``config``
folder of each test case. If a test case does not has the ``local.yaml`` in its
``config`` folder, it will use the ``local.yaml`` file in its parent test case
and so on. This will help users to share the test information for related test
case without having the same ``local.yaml`` for each test case (*Note:* this
feature is enabled from RENAT 0.1.4). The ``local.yaml`` that is really used for
the test is called ``active local.yaml``.
When user used the wizard ``item.sh`` to create a new test case, they have the
ability to crete new ``local.yaml`` or not. ``local.yaml`` could be edited and
inserted new information later to hold more informations for the test case.
When a test is run, it will display its current active ``local.yaml``
The local configuration file of each test item is stored in the ``config``
folder of the item as ``local.yaml`
Usually the ``local.yaml`` has following parts:
- CLI node information: started by ``node`` keyword
- WEB node information: started by ``webapp`` keyword
- Tester device information: started by ``tester`` keyword
- Default information: automatically created and started by ``default`` keyword
- And other neccessary information for the test by yaml format
Example:
| # CLI node
| node:
| vmx11:
| device: vmx11
| snmp_polling: yes
| vmx12:
| device: vmx11
| snmp_polling: yes
| apollo:
| device: vmx11
| snmp_polling: yes
|
| # web application information
| webapp:
| arbor-sp-a:
| device: arbor-sp-a
| proxy:
| http: 10.128.8.210:8080
| ssl: 10.128.8.210:8080
| socks: 10.128.8.210:8080
|
| # Tester information
| tester:
| tester01:
| type: ixnet
| ip: 10.128.32.70
| config: vmx_20161129.ixncfg
|
| # Other local information specific for this case
| port-mapping:
| uplink01:
| device: vmx11
| port: ge-0/0/0
| downlink01:
| device: vmx12
| port: ge-0/0/2
|
| # Default information
| default:
| ignore-dead-node: yes
| terminal:
| width: 80
| height: 32
| result_folder: result
= Variables =
The module automatically create ``GLOBAL`` & ``LOCAL`` variable for other
libraries. It also creates global list variables `GLOBAL``,``LOCAL`` and
``NODE`` that could be accessed from `Robot Framework` test cases.
The GLOBAL variable holds all information defined by the master files and LOCAL
variable holds all variables defined by active ``local.yaml``. And ``NODE`` is a
list that hold all active nodes defined in the ``local.yaml``.
Users could access to the information of a key in ``local.yaml`` by
``${LOCAL['key']}``, information of a node by ``${LOCAL['node']['vmx11']}`` or
simply ``$NODE['vmx']``. When a keyword need a list of current node, ``@{NODE}``
could be used.
*Notes:* By default, RENAT will stop and raise an exception if connection to a
node is failed. But if ``ignore-dead-node`` is defined as ``yes`` (default) is
the current active ``local.yaml``, RENAT will omit an warning but keep running
the test and remove the node from its active node list.
"""
ROBOT_LIBRARY_VERSION = 'RENAT 0.1.17'
import os,socket,json,ipaddress
import glob,fnmatch
import re
import yaml
import glob
import time,datetime
from datetime import timedelta
import codecs
import numpy
import random
import shutil
import pdfkit
import string
import fileinput
import difflib
import hashlib
import pandas
import sys,select
import subprocess
import pyscreenshot as pyscreenshot
from pyvirtualdisplay import Display
from selenium.webdriver.common.keys import Keys
try:
from sets import Set
except:
pass
import robot.libraries.DateTime as DateTime
from robot.libraries.BuiltIn import BuiltIn
from collections import OrderedDict
import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.utils import COMMASPACE, formatdate
# make sure the yaml dictionary is in its order
yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
lambda loader, node: OrderedDict(loader.construct_pairs(node)))
# filter all warning
# done this for openpyxl, maybe we should not do this
import warnings
warnings.filterwarnings("ignore")
### global setting
GLOBAL = {}
LOCAL = {}
NODE = []
WEBAPP = []
DISPLAY = None
START_TIME = datetime.datetime.now()
###
import logging
logging.getLogger('Display').setLevel(logging.ERROR)
def log(msg,level=1):
""" Logs ``msg`` to the current log file (not console)
The ``msg`` will logged only if the level is bigger than the global level
``${DEBUG}`` which could be defined at runtime.
If ``${DEBUG}`` is not defined, it will be considered as the default
``level`` as 1.
Examples:
| Common.`Log` | XXX | # this always be logged |
| Common.`Log` | AAA | level=2 | # this will not be logged with common run.sh |
| Common.`Log` | BBB | level=2 | # ./run.sh -v ``DEBUG:2`` will log the message |
*Notes*: For common use
- level 1: is default
- level 2: is debug mode
- level 3: is very informative mode
"""
_level = None
try:
_level = BuiltIn().get_variable_value('${DEBUG}')
except:
pass
if _level is None: _level=1
if int(_level) >= int(level):
BuiltIn().log(msg)
def log_to_console(msg,level=1,no_newline=False):
""" Logs a message to console
See Common.`Print` for more details about debug level
"""
_level = None
try:
_level = BuiltIn().get_variable_value('${DEBUG}')
except:
pass
if _level is None: _level=1
if int(_level) >= int(level):
if no_newline :
BuiltIn().log_to_console(msg,no_newline=True)
else :
BuiltIn().log_to_console(msg)
def err(msg):
""" Prints error ``msg`` to console
"""
BuiltIn().log_to_console(msg)
###
try:
_result_folder = os.path.basename(BuiltIn().get_variable_value('${OUTPUT DIR}'))
except:
log("ERROR: Error happened while trying to get global RF variables")
_folder = os.path.dirname(__file__)
if _folder == '': _folder = '.'
### load global setting
_config_path = _folder + '/usr/config.yaml'
if not os.path.exists(_config_path):
_config_path = _folder + '/config/config.yaml'
if not os.path.exists(_config_path):
raise Exception("ERR: could not find global config.yaml")
with open(_config_path) as f:
file_content = f.read()
GLOBAL.update(yaml.load(os.path.expandvars(file_content)))
### copy config file from maser to tmp
### overwrite the current files
_tmp_folder = _folder + '/tmp/'
# _tmp_folder = os.getcwd() + '/tmp/'
_renat_master_folder = GLOBAL['default']['renat-master-folder']
#lock_file = _renat_master_folder + '/tmp.lock'
#with open(lock_file,'r') as lock:
# while True:
# try:
# fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
# shutil.copy2(_renat_master_folder+'/device.yaml',_tmp_folder)
# shutil.copy2(_renat_master_folder+'/auth.yaml',_tmp_folder)
# shutil.copy2(_renat_master_folder+'/template.yaml',_tmp_folder)
# break
# except IOError as e:
# time.sleep(1)
_calient_master_path = GLOBAL['default']['calient-master-path']
if _calient_master_path:
newest_calient = max(glob.iglob(_calient_master_path))
shutil.copy2(newest_calient,_tmp_folder + "/calient.xlsm")
_ntm_master_path = GLOBAL['default']['ntm-master-path']
# if _ntm_master_path:
# _ntm_master_path = os.path.expandvars(_ntm_master_path)
if _ntm_master_path:
newest_ntm = max(glob.iglob(_ntm_master_path))
shutil.copy2(newest_ntm,_tmp_folder + "/g4ntm.xlsm")
### expand environment variable and update GLOBAL config
for entry in ['auth.yaml', 'device.yaml','template.yaml']:
with codecs.open(_renat_master_folder + '/' + entry,"r","utf-8") as f:
file_content = f.read()
retry = 0
if len(file_content) == 0 and retry < 3:
time.sleep(5)
BuiltIn().log_to_console("WARN: could not access file %s. Will retry" % entry)
file_content = f.read()
retry += 1
if retry == 3:
BuiltIn().log_to_console("ERROR: could not get global config correctly")
GLOBAL.update(yaml.load(os.path.expandvars(file_content)))
### local setting
### trace all config folder in the path
access_path = ""
check_path = ""
local_config_path = ""
for entry in os.getcwd().split('/'):
if entry == "": continue
access_path = access_path + '/' + entry
check_path = access_path + '/config/local.yaml'
if os.path.exists(check_path):
local_config_path = check_path
if local_config_path == '':
BuiltIn().log_to_console("WARN: Could not find the local config file")
else:
with open(local_config_path) as f:
LOCAL.update(yaml.load(f))
BuiltIn().log_to_console("Current local.yaml: " + local_config_path)
USER = os.path.expandvars("$USER")
HOME = os.path.expandvars("$HOME")
# read from local configuration
if 'node' in LOCAL: NODE = LOCAL['node']
if NODE is None: NODE = []
if 'webaapp' in LOCAL: WEBAPP = LOCAL['webapp']
if WEBAPP is None: WEBAPP = []
newline = GLOBAL['default']['newline']
def renat_version():
""" Returns RENAT version string
"""
BuiltIn().log("RENAT version is : `%s`" % ROBOT_LIBRARY_VERSION)
return ROBOT_LIBRARY_VERSION
def get_renat_path():
""" Returns the absolute path of RENAT folder
"""
return _folder
def get_item_name():
""" Returns the name of the running item
"""
return os.path.basename(os.getcwd())
def get_config_path():
""" Returns absolute path of RENAT config folder path
"""
return _folder + "/config"
def get_item_config_path():
""" Returns absolute path of current item config folder
"""
return os.getcwd() + '/config/'
def get_tmp_path():
""" Returns temporary path
"""
return os.getcwd() + '/tmp'
def get_result_path():
""" Returns absolute path of the current result folder
"""
return os.getcwd() + '/' + _result_folder
def get_result_folder():
""" Returns current result folder name. Default is ``result`` in current
test case.
*Note*: the keyword only returns the ``name`` of the result folder not its
absolue path.
"""
return _result_folder
def set_result_folder(folder):
""" Sets the result folder to ``folder`` and return the old result folder.
The result folder contains all output files from the test likes tester
ouput, config file ...
``folder`` is a folder name that under current test case folder
The system will create a new folder if it does not exist and set its mode to
`0775`
*Note:* Result folder should be set at the begining of the test. Changing
result folder only has effect on up comming connection
"""
global _result_folder
old_folder = _result_folder
_result_folder = folder
folder_path = os.getcwd() + '/' + folder
try:
if not os.path.exists(folder_path):
os.makedirs(folder_path)
os.chmod(folder_path,int('0775',8))
except Exception as e:
BuiltIn().log("ERROR:" + str(e.args))
# set ROBOT variable
# BuiltIn().set_variable('${OUTPUT DIR}', folder_path)
# BuiltIn().set_variable('${OUTPUT DIR}', folder_path)
# BuiltIn().set_variable('${LOG_FODER}', folder)
BuiltIn().set_global_variable('${LOG_FODER}', folder)
BuiltIn().set_global_variable('${RESULT_FOLDER}', folder)
BuiltIn().set_global_variable('${RESULT_PATH}', folder_path)
BuiltIn().log("Changed current result folder to `%s`" % (folder_path))
return old_folder
def version():
""" Returns the current version of RENAT
"""
return ROBOT_LIBRARY_VERSION
def node_with_attr(attr_name,value):
""" Returns a list of nodes which have attribute ``attr_name`` with value ``value``
"""
result = [ node for node in NODE if attr_name in NODE[node] and NODE[node][attr_name] == value ]
BuiltIn().log("Found %d nodes with condition `%s`=`%s`" % (len(result),attr_name,value))
return result
def node_with_tag(*tag_list):
""" Returns list of ``node`` or ``webapp`` from ``local.yaml`` that has *ALL* tags defined by ``tag_list``
Tag was defined like this in local.yaml
| vmx11:
| device: vmx11
| snmp_polling: yes
| tag:
| - tag1
| - tag2
Examples:
| ${test3}= | Common.`Node With Tag` | tag1 | tag3 |
"""
result = []
if sys.version_info[0] > 2:
s0 = set(tag_list)
if 'node' in LOCAL and LOCAL['node']:
for item in LOCAL['node']:
if 'tag' in LOCAL['node'][item]:
if LOCAL['node'][item]['tag']:
s1 = set(LOCAL['node'][item]['tag'])
else:
s1 = set()
if s0.issubset(s1): result.append(item)
if 'webapp' in LOCAL and LOCAL['webapp']:
for item in LOCAL['webapp']:
if 'tag' in LOCAL['webapp'][item]:
if LOCAL['webapp'][item]['tag']:
s1 = set(LOCAL['webapp'][item]['tag'])
else:
s1 = set()
else:
s0 = Set(tag_list)
if 'node' in LOCAL and LOCAL['node']:
for item in LOCAL['node']:
if 'tag' in LOCAL['node'][item]:
s1 = Set(LOCAL['node'][item]['tag'])
if s0.issubset(s1): result.append(item)
if 'webapp' in LOCAL and LOCAL['webapp']:
for item in LOCAL['webapp']:
if 'tag' in LOCAL['webapp'][item]:
s1 = Set(LOCAL['webapp'][item]['tag'])
if s0.issubset(s1): result.append(item)
BuiltIn().log("Found %d nodes have the tags(%s)" % (len(result),str(tag_list)))
return result
def node_without_tag(*tag_list):
""" Returns list of ``node`` from ``local.yaml`` that *does not has ANY* tags defined by ``tag_list``
Tag was defined like this in local.yaml
| vmx11:
| device: vmx11
| snmp_polling: yes
| tag:
| - tag1
| - tag2
Examples:
| ${test3}= | Common.`Node Without Tag` | tag1 | tag3 |
"""
result = []
if sys.version_info[0] > 2:
s0 = set(tag_list)
if not LOCAL['node']: return result
for node in LOCAL['node']:
if 'tag' in LOCAL['node'][node]:
if LOCAL['node'][node]['tag']:
s1 = set(LOCAL['node'][node]['tag'])
else:
s1 = set()
if len(s0 & s1) == 0: result.append(node)
else:
BuiltIn().log(" Node `%s` has no `tag` key, check your `local.yaml`" % node)
else:
s0 = Set(tag_list)
if not LOCAL['node']: return result
for node in LOCAL['node']:
if 'tag' in LOCAL['node'][node]:
s1 = Set(LOCAL['node'][node]['tag'])
if len(s0 & s1) == 0: result.append(node)
else:
BuiltIn().log(" Node `%s` has no `tag` key, check your `local.yaml`" % node)
BuiltIn().log("Found %d nodes do not include any tags(%s)" % (len(result),str(tag_list)))
return result
def mib_for_node(node):
""" Returns the mib file name for this ``node``
mib file is define by ``mib`` keyword under the ``node`` in ``local.yaml``
| ...
| node:
| vmx11:
| device: vmx11
| snmp_polling: yes
| mib: mib11.txt
| ...
Default value is defined by ``mib`` keyword from global
``config/snmp-template.yaml`` for the ``type`` of the node
Example:
| ${mib}= | Common.`MIB For Node` | vmx11 |
"""
mib_file = None
if 'mib' in LOCAL['node'][node]:
mib_file = LOCAL['node'][node]['mib']
if mib_file is None:
device = LOCAL['node'][node]['device']
type = GLOBAL['device'][device]['type']
mib_file = GLOBAL['snmp-template'][type]['mib']
return mib_file
def loop_for_node_tag(var,tags,*keywords):
""" Repeatly executes RF ``keyword`` for nodes that has tag ``tags``
multi tags are separated by `:`
keywords has same meaning with ``keywords`` used by `Run Keywords` of
RobotFramework ( keyword and its arguments are separated by ``AND`` with the
others.
Example:
| `Loop For Node Tag` | \${node} | tag1 |
| ... | `Switch` | \${node} | AND |
| ... | `Cmd` | show system user | AND |
| ... | `Cmd` | show system uptime |
*Note:* ``$`` in variable name must be escaped
"""
nodes = node_with_tag(*tags.split(':'))
for node in nodes:
BuiltIn().set_test_variable(var,node)
BuiltIn().run_keywords(*keywords)
def is_stable(seq,threshold,percentile='90'):
""" Checks if the value sequence is stable or not
"""
check_value = numpy.percentile(seq,percentile)
result = (check_value < threshold)
BuiltIn().log("check_value = %s threshold = %s result=%s" % (check_value,threshold,result) )
return result
def str2seq(str_index,size):
""" Returns a sequence from string format
Examples:
| `Str2Seq` | :: | 5 | # (0,1,2,3,4) |
| `Str2Seq` | :2 | 5 | # (0,1) |
| `Str2Seq` | 1:3 | 5 | # (1,2) |
| `Str2Seq` | 0:5:2 | 5 | # (0,2,4) |
"""
if ':' in str_index:
# tmp = map(lambda x: 0 if x=='' else int(x),str_index.split(':'))
tmp = [ int(x) if x!='' else 0 for x in str_index.split(':') ]
if len(tmp) > 3:
return None
else:
result = range(*list(tmp))
if len(result) == 0: result = range(size)
return result
else:
# return list(map(int,str_index.split(',')))
return [ int(x) for x in str_index.split(',') ]
return None
def csv_select(src_file,row=u':',col=u':',dst_file=None,flatten=False,header=None):
""" Select part of the CSV file and write it to other file
``row`` and ``col`` are used to specify necessary rows and columns.
They are using the same format with slice for Python list.
- : and : means all rows and columns
- :2 and : means first 2 rows and all columns
- : and 1,2 means all rows and 2nd and 3rd columns
- 0:3 and 1 means 3 rows from the 1st one(0,1,2) and second column
- 0:5:2 and 1 means 3 rows(0,3,5) and second column
*Notes:*
- Rows and columns are indexed from zero
- When ':' is used, the string has format: <start>:<stop> or <start>:<stop>:<step>
For convenience, ':' means all the data, ':x' means first 'x' data
Examples:
| `CSV Select` | result/data05.csv | 0,1,2 | 0,1 | result/result3.csv |
| `CSV Select` | result/data05.csv | : | 0,1 | result/result4.csv |
| `CSV Select` | result/data05.csv | :2 | : | result/result5.csv |
| `CSV Select` | result/data05.csv | 0:3 | : | result/result6.csv |
| `CSV Select` | result/data05.csv | 0:5:2 | : | result/result7.csv |
| `CSV Select` | result/data05.csv | 0:5:2 | : |
"""
src_pd = pandas.read_csv(src_file,header=header)
s = src_pd.shape
data = src_pd.iloc[str2seq(row,s[0]),str2seq(col,s[1])]
if dst_file:
data.to_csv(dst_file,index=None,header=header)
BuiltIn().log("Wrote to CSV file `%s`" % dst_file)
else:
BuiltIn().log("Select data from CSV file `%s`" % src_file)
if flatten:
result = data.values.flatten().tolist()
else:
result = data.values.tolist()
return result
def csv_to_list(filepath,col=u"0",header=None):
""" Return a column of value from csv to list
Exmaple:
| ${LIST}= | CSV To List | 100 |
"""
df = pandas.read_csv(filepath,header=header)
result = df.iloc[:,int(col)].values.tolist()
BuiltIn().log("Return %d values from `%s`" % (len(result),filepath))
return result
def csv_concat(src_pattern, dst_name,input_header=None,result_header=True):
""" Concatinates CSV files vertically
If the CSV files has header, set ``has_header`` to ``${TRUE}``
Examples:
| Commmon.`CSV Concat` | config/data0[3,4].csv | result/result2.csv | |
| Commmon.`CSV Concat` | config/data0[3,4].csv | result/result2.csv | has_header=${TRUE} |
"""
file_list = sorted(glob.glob(src_pattern))
num = len(file_list)
if num < 1:
BuiltIn().log("Could not find any file to concatinate")
return False
file = file_list.pop(0)
pd = pandas.read_csv(file,header=input_header)
for file in file_list:
pd_next = pandas.read_csv(file,header=input_header)
pd = pandas.concat([pd, pd_next])
pd.to_csv(dst_name,index=None,header=result_header)
BuiltIn().log("Concatinated %d files to %s" % (num,dst_name))
return True
def csv_merge(src_pattern,dst_name,input_header=None,key='0',select_column=':',result_header=True):
""" Merges all CSV files ``horizontally`` by ``key`` key from ``src_pattern``
``input_header`` defines whether the input files has header row or not. If
``input_header`` is ``${NULL}``, the keyword assume that input files have no
header and automatically define columns name. When ``input_header`` is not
null (default is zero), the row define by ``input_header`` will be used as header
and data is counted from the next row.
``select_column`` is a string that define the output columns and ``key`` is the
column name that used to merge. When ``input_header`` is ``${NULL}``,
``select_column`` and `key` is the index of columns. Otherwise, they are
`column name`.
The result header (column names) is decided by ``result_header`` (`True` or `False`)
The keyword returns ``False`` if no file is found by the pattern
Examples:
| Common.`CSV Merge` | config/data0[3,4].csv | result/result2.csv |
| Common.`CSV Merge` | config/data0[3,4].csv | result/result2.csv | input_header=0 |
| Common.`CSV Merge` | src_pattern=${RESULT_FOLDER}/balance*.csv | input_header=0 |
| ... | dst_name=${RESULT_FOLDER}/result.csv | result_header=${FALSE} |
| ... | key=Stat Name | select_column=Valid Frames Rx. |
| Common.`CSV Merge` | src_pattern=${RESULT_FOLDER}/balance*.csv | input_header=${NULL} |
| ... | dst_name=${RESULT_FOLDER}/result.csv | result_header=${FALSE} |
| ... | key=0 | select_column=5 |
"""
file_list = sorted(glob.glob(src_pattern))
num = len(file_list)
if not select_column == ':':
columns = '%s,%s' % (key,select_column)
else:
columns = select_column
if num < 1:
BuiltIn().log("File number is less than %d" % (num))
return False
elif num < 2:
f1_name = file_list.pop(0)
if input_header is None:
f1 = pandas.read_csv(f1_name,header=input_header)
s = f1.shape
result = f1.iloc[:,str2seq(columns,s[1])]
else:
f1 = pandas.read_csv(f1_name,header=int(input_header))
result = f1[columns.split(',')]
result.to_csv(dst_name,index=None,header=result_header)
BuiltIn().log("File number is less than %d, merged anyway" % (num))
return True
else:
f1_name = file_list.pop(0)
f2_name = file_list.pop(0)
if input_header is None:
f1 = pandas.read_csv(f1_name,header=input_header)
f2 = pandas.read_csv(f2_name,header=input_header)
s = f1.shape
result1 = f1.loc[:,str2seq(columns,s[1])]
s = f2.shape
result2 = f2.loc[:,str2seq(columns,s[1])]
else:
f1 = pandas.read_csv(f1_name,header=int(input_header))
f2 = pandas.read_csv(f2_name,header=int(input_header))
result1 = f1[columns.split(',')]
result2 = f2[columns.split(',')]
if input_header is None:
m = pandas.merge(result1,result2,on=int(key))
else:
m = pandas.merge(result1,result2,on=key)
for item in file_list:
if input_header is None:
f = pandas.read_csv(item,header=input_header)
s = f.shape
result = f.iloc[:,str2seq(columns,s[1])]
else:
f = pandas.read_csv(item,header=int(input_header))
result = f[columns.split(',')]
if input_header is None:
m = pandas.merge(m,result,on=int(key))
else:
m = pandas.merge(m,result,on=key)
# write to file without index
m.to_csv(dst_name,index=None,header=result_header)
BuiltIn().log("Merged %d files to %s" % (num,dst_name))
return True
def merge_files(path_name,file_name):
""" Merges all the text files defined by ``path_name`` to ``file_name``
Example:
| `Merge Files` | ./result/*.csv | ./result/test.csv |
"""
file_list = glob.glob(path_name)
with open(file_name,'w') as fout:
fin = fileinput.input(file_list)
for line in fin:
fout.write(line)
fin.close()
BuiltIn().log("Merges %d files to %s" % (len(file_list),file_name))
def create_sequence(start,end,interval,option='float'):
""" Creates a list with number from ``start`` to ``end`` with ``interval``
Example:
| @{list}= | `Create Sequence` | 10 | 15 | 0.5 |
will create a list of ``[11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5]``
"""
result = []
if option == 'float':
result = numpy.arange(float(start),float(end),float(interval)).tolist()
if option == 'int':
result = numpy.arange(int(start),int(end),int(interval)).tolist()
return result
def change_mod(name,mod,relative=True):
""" Changes file mod, likes Unix chmod
``mod`` is a string specifying the privilege mode
``relative`` is ``False`` or ``True``
Examples:
| Common.`Change Mod` | tmp | 0775 |
"""
if relative:
path = os.getcwd() + "/" + name
else:
path = name
os.chmod(path,int(mod,8))
BuiltIn().log("Changed `%s` to mode %s" % (path,mod))
def get_test_device():
""" Return a list of all test device that is used in this test