几年前的一些代码
RobotFramework的方法实例:
RobotFamework是一个很好的验收测试框架,但是开发的人员交互时,它会是个负担,后面改用了pytest,估计暂时也不会去碰RobotFamework了,故仅留个方法实例在这里。
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Andrew Xu # CreateDate: 2012/09/14 """ This file descripe the main class of FSP GE* in cli. """ # __version__ = $Revision: $ # Standard libraries import random import threading import re import os import time import sys import pickle import argparse import urllib import socket import unittest # Third part libraries import pexpect # Robot libraries from robot.api import logger from robot.libraries.BuiltIn import _Verify def _check_cli_error(): if cli.client.ErrorStr: output_console_error('cliError', "cli return Error", cli.client.ErrorStr, cli.client.ErrorNum, cli.client.ErrorInd) def _datetime(s): date, time = s.split(',') year, month, day = date.split('-') hour, minute, second = time.split('.')[0].split(':') raw = \ r'\x{0:0>2s}\x{1:0>2s}\x{2:0>2s}\x{3:0>2s}\x{4:0>2s}\x{5:0>2s}\x{6:0>2s}\x'\ .format( hex(int(year))[2], hex(int(year))[3:], hex(int(month))[2:], hex(int(day))[2:], hex(int(hour))[2:], hex(int(minute))[2:], hex(int(second))[2:]) + '00' result = urllib.unquote(raw.replace('\\x', '%')) return result class Cli(object): ''' *--Function: cli operations' keywords*. - Support basic cli operations: connect, set, trap, get, set check, \ get check, set rows, walk, safe get, is exist, get single etc. - Support common FSP cli operations: create, destroy, Create Card etc. - Support FSP cli specific feature operations: ecpa_set_stream,\ ecpa_set_control etc. --- Some Glossaries: - arg: the arguments of cli_set, cli_get, cli_walk, etc. \ can be concat of soid, index, value, check value. e.g.\ ecpaControlAction.1.1.1.1=start \ ecpaControlAction.1.1.1.1=start \ ethernet1x10GCardRowStatus.1.1.24=createAndGo -c active - soid: cli string object id. e.g. ecpaControlAction - noid: cli number object id. e.g. .1.3.6.1.4.1.2544.1.12.8.1.1.1.11 - node: cli string object id and index. e.g. ecpaControlAction.1.1.1.1 - index: inistance sequence of a cli id. e.g. 1.1.1.1 ---Rules to write arguments: - index: index can be put after soid or set common index for multi \ nodes. index can be put after soid: ethernet1x10GCardRowStatus.1.1.24.\ common index: | cli set | index=1.1.24 | ethernet1x10GCardRowStatus=unassigned | ''' ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = '1.0.0' client = None reverse = False single = False check = False hostname = None trap_received = False verify = _Verify() fps = {} ########################## basic cli operation ############################ @classmethod def cli_connect(cls,ip,username="root",password="123456", prompt=']#'): ''' *Connect to host use cli.* | *Fixed argument* | *type* | *description* | | hostname | string | hostname or ip addr of cli agent. e.g. \ 172.23.191.126 | | *Named argument * | *type* | *description* | | version | string | default '3', [1, 2 (equiv to 2c), 3] | | portNum | string | default '161' | | timeout | string | default '500000', micro-seconds before retry | | retries | string | default '3', retries before failure | | community | string | default 'private', cli community string | *--Robot Example* | cli_connect | 172.23.191.126 | | cli_connect | 172.23.191.126 | version=2 | ''' # Ssh to remote server ssh_newkey = 'Are you sure you want to continue connecting' child = pexpect.spawn('ssh '+ username + '@'+ ip, maxread=5000) # Enter password i = child.expect(['assword:*', ssh_newkey, pexpect.TIMEOUT, 'key.*? failed', prompt]) if i == 4: print child.before,child.after, else: if i == 3: print child.before,child.after, os.remove(os.path.expanduser('~')+'/.ssh/known_hosts') child = pexpect.spawn('ssh '+ username + '@'+ ip, maxread=5000) i = child.expect(['assword:*', ssh_newkey, pexpect.TIMEOUT]) #print child.before,child.after, if i == 2: #*Timeout print child.before,child.after, print 'ERROR TIMEOUT! SSH could not login. ' if i == 1: #*SSH does not have the public key. Just accept it. print child.before,child.after, child.sendline ('yes\r') i = child.expect (['.*assword: ']) print child.before,child.after, if i == 0: print child.before,child.after, child.send(password +"\r") child.expect([prompt]) Cli.client = child @classmethod def cliCmd(cls,cmd, prompt=']#'): ''' *Create one or more simple objects.* Create objects can be created by set rowstatus only. e.g. card. | *Arbitrary argument* | *type* | *description* | | *args | string | one or more string like 23, 1.1.11 etc | *--Robot Example* | cli_create | ethernet1x10GCardRowStatus.1.1.24 | | cli_create | ethernet1x10GCardRowStatus.1.1.24 | \ ethernet1x10GCardRowStatus.1.1.11 | ''' Cli.client.buffer = '' Cli.client.send(cmd + "\r") #Cli.client.setwinsize(400,400) Cli.client.expect(prompt) print Cli.client.before, Cli.client.after, return Cli.client.before, Cli.client.after def connect(ip,username="root",password=""): ''' | cli_connect | 172.23.191.126 | version=2 | ''' # Ssh to remote server ssh_newkey = 'Are you sure you want to continue connecting' child = pexpect.spawn('ssh '+ username + '@'+ ip, maxread=5000) # Enter password i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'assword:*', 'key verification failed', '\]#']) if i == 4: return child if i == 3: os.remove(os.path.expanduser('~')+'/.ssh/known_hosts') print child.before,child.after, child = pexpect.spawn('ssh '+ username + '@'+ ip, maxread=5000) i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'assword:*']) print child.before,child.after, if i == 0: #*Timeout print 'ERROR TIMEOUT! SSH could not login. ' if i == 1: #*SSH does not have the public key. Just accept it. child.sendline ('yes\r') child.expect ('.*assword: ') print child.before,child.after, #*enter password. child.send(password +"\r") return child def command(child, cmd, prompt='\]#'): ''' *Create one or more simple objects.* Create objects can be created by set rowstatus only. e.g. card. | *Arbitrary argument* | *type* | *description* | | *args | string | one or more string like 23, 1.1.11 etc | *--Robot Example* | cli_create | ethernet1x10GCardRowStatus.1.1.24 | | cli_create | ethernet1x10GCardRowStatus.1.1.24 | \ ethernet1x10GCardRowStatus.1.1.11 | ''' child.buffer = '' child.send(cmd + "\r") child.expect(prompt) print child.before, child.after, return child.before, child.after if __name__ == '__main__': unittest.main(verbosity=2)
包含单元测试的代码:
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Andrew Xu # CreateDate: 2012/09/14 """ This file descripe the main class of FSP GE* in cli. """ # __version__ = $Revision: $ # Standard libraries import random import threading import re import os import time import sys import pickle import argparse import urllib import socket import unittest # Third part libraries import pexpect # Robot libraries from robot.api import logger from robot.libraries.BuiltIn import _Verify # adva libraries from adva_error import * from adva_output import * from adva_constant import * class TestcliFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) self.slot1 = '11' self.slot2 = '7' self.server = '172.23.191.126' self.host = cli() self.host.cli_connect(self.server, community='private') def test_cli_basic(self): print "\n--**create single card: ", self.slot1 self.host.cli_create('ethernet1x10GCardRowStatus.1.1.' + self.slot1) self.host.cli_set('ethernet1x10GCardAdminState.1.1.{0}=management'. format(self.slot1)) self.host.cli_destroy('ethernet1x10GCardRowStatus.1.1.' + self.slot1) print "\n--**create multi card: ", self.slot1, self.slot2 self.host.cli_create('ethernet1x10GCardRowStatus.1.1.' + self.slot1, 'ethernet1x10GCardRowStatus.1.1.' + self.slot2) self.host.cli_set( 'ethernet1x10GCardAdminState.1.1.{0}=management'.format(self.slot1), 'ethernet1x10GCardAdminState.1.1.{0}=management'.format(self.slot2)) self.host.cli_destroy('ethernet1x10GCardRowStatus.1.1.' + self.slot1, 'ethernet1x10GCardRowStatus.1.1.' + self.slot2) print "\n--**cli set check: " self.host.cli_set_check( 'ethernet1x10GCardRowStatus.1.1.{0}=createAndGo -c active'. format(self.slot1)) self.host.cli_set_check( 'ecpaControlTestType.1.1.{0}.1=createAndGo'.format(self.slot1), 'ecpaControlTestType.1.1.93.1=createAndGo', '-N') self.host.cli_delete_card(self.slot1) print "\n--**cli trap: " self.host.cli_set('ftpEnabled.0=true') self.host.cli_trap('ftpEnabled.0=false') print "\n--**cli_set_rows: ", self.slot1, self.slot2 self.host.cli_set_rows('ecpaControlTestType=numframes', 'ecpaControlNumFrames=10') self.host.cli_set_rows('ecpaControlTestType=duration') print "\n--**cli_walk: " self.assertEqual(self.host.cli_walk('ntpClientEnabled'), ['false']) print "\n--**cli_is_exist: " self.assertTrue(self.host.cli_is_exist('cmAuthProtocol.0')) self.assertFalse(self.host.cli_is_exist('cmAuthProtocol.10')) print "\n--**cli_get_check: " self.host.cli_get_check('cmAuthProtocol.0=none', 'ntpClientEnabled.0=false') self.host.cli_get_check('cmAuthProtocol.10=none', 'ntpClientEnabled.10=false', ' -N') print "\n--**cli_get: " self.assertEqual(self.host.cli_get('-s', 'cmAuthProtocol.0'), 'none') print "\n--**cli_get: " self.assertEqual( self.host.cli_get('cmAuthProtocol.0', 'ntpClientEnabled.0'), ['none', 'false']) def test_cli_cfm(self): self.host.cli_create_cards('eth-ge-10s-h=' + self.slot1) self.host.cli_set('cmEthernetTrafficPortSvcType.1.1.' + self.slot1 + '.1=service-multiplexing') print "\n--**cli_create_oamfp: " self.assertEqual( self.host.cli_create_oamfp(self.slot1, 1, 1, 'test123', 'true'), '1.1.{0}.1.1'.format(self.slot1)) self.host.cli_delete_oamfp(self.slot1, 1, 1) self.assertEqual( self.host.cli_create_oamfp(self.slot1, 1, 300, 'test223', '1:3'), '1.1.{0}.1.300'.format(self.slot1)) self.assertEqual(self.host.cli_create_md(333, 'charString', 'test', 0), '333') self.host.cli_delete_md(333) print "\n--**cli_create_md: " self.assertEqual(self.host.cli_create_md(333, 'none', 'none', 0), '333') self.host.cli_delete_md(333) self.assertEqual( self.host.cli_create_md(333, 'macAddressAndUint', 'f0:0f:00:00:00:00-0', 7), '333') self.host.cli_delete_md(333) self.assertEqual( self.host.cli_create_md(333, 'dnsLikeName', 'www.adva.com', 7, 'defMHFexplicit'), '333') print "\n--**cli_create_manet: " self.assertEqual( self.host.cli_create_manet(333, 333, 'charString', 'testname', 'interval10min', '4,2'), '333.333') print "\n--**cli_create_macomp: " index = self.host.cli_create_macomp(333, 333, 1, self.slot1, '1', '34') self.assertEqual( self.host.cli_create_mep( 333, 333, 1, 4, self.slot1, 1, 'up', '-ccmDisabled -ccmPri 7 -alarmPri errXcon'), '333.333.4') print "\n--**cli_create_layer2probe: " self.host.cli_create_layer2probe( 1561, 'test1561', 'up', 'y1731', self.slot1, 1, 333, 333, 1, 4, 'mepid', 2, '-dmmSize 204') self.host.cli_delete_probe(1561) print "\n--**cli_create_layer3probe: " self.host.cli_create_layer3probe( 1, 'test11', 'up', 'udpEcho', self.slot1, 1, '172.23.1.6', '255.255.255.0', '172.23.1.7', '-bin interval-15min 2 \ interval-15min 2 -ourterVlan 0x8100 1-6') print "\n--**cli_create_layer3probe: " self.host.cli_create_schedule(1, 1, 'one-shot', '2013-6-30,19:47:45.0', 5000, 'test11', 0) self.host.cli_delete_schedule(1) print "\n--**cli_create_reflector: " self.host.cli_create_reflector(1, 1, 'down', self.slot1, 1, '172.23.5.8', '255.255.255.0') self.host.cli_delete_reflector(1) self.host.cli_delete_probe(1) self.host.cli_delete_mep(333, 333, 1, 4) self.host.cli_delete_macomp(333, 333, 1, self.slot1, '1') self.host.cli_delete_manet(333, 333) self.host.cli_delete_md(333) self.host.cli_delete_oamfp(self.slot1, 1, 300) print "\n--**cli_create_vlan_table: " index = self.host.cli_create_vlan_table(self.slot1, 1, 34, 43) self.host.cli_delete_vlan_table(self.slot1, 1, 34) self.host.cli_delete_card(self.slot1) def test_cli_egress_ingress_table(self): self.host.cli_create_cards('eth-ge-10s-h=' + self.slot1) self.host.cli_set('cmEthernetTrafficPortSvcType.1.1.' + self.slot1 + '.1=service-multiplexing') self.host.cli_set_egress_table(self.slot1, 1, '2,4,3', '4,5,6') self.host.cli_set_ingress_table(self.slot1, 1, 'priomap-dscp', '54,63,7', '4,5,6') self.host.cli_delete_card(self.slot1) def test_cli_lag(self): print time.ctime() self.host.cli_create_cards('eth-ge-10s-h=' + self.slot1) self.host.cli_create_lag(1, [self.slot1,1,self.slot1,2], 'active-standby') print 'first lag create finished.', time.ctime() self.host.cli_delete_lag(1) print 'first lag delete finished.', time.ctime() self.host.cli_create_lag( 1, [self.slot1,1,self.slot1,2,self.slot1,3,self.slot1,4], 'loadsharing', '-shapperList 4,5,1 -queueProfile 2 -priotiyMapMode\ priomap-tos') print "delet lag:", time.ctime() self.host.cli_delete_lag(1) print "delet card:", time.ctime() self.host.cli_delete_card(self.slot1) print time.ctime() def test_cli_ppg(self): print time.ctime() self.host.cli_create_cards('eth-ge-10s-h=' + self.slot1) self.host.cli_create_ppg(1, self.slot1, 1, self.slot1, 2) print 'first ppg create finished.', time.ctime() self.host.cli_delete_ppg(1) print 'first ppg delete finished.', time.ctime() self.host.cli_create_ppg(12, self.slot1, 1, self.slot1, 2, '-label \ test123 -revertiveDisabled -time 3 -serviceType all-to-one') print "delet ppg:", time.ctime() self.host.cli_delete_ppg(12) print "delet card:", time.ctime() self.host.cli_delete_card(self.slot1) print time.ctime() def test_cli_cards(self): index = self.host.cli_random_create_line_card('eth-xg-1x') self.assertEqual(self.host.cli_get_card_type(index), 'eth-xg-1x') self.host.cli_delete_card(index) self.host.cli_create_cards( 'eth-xg-1x=' + self.slot1, 'stm1-4-et={0}'.format(self.slot2), 'stu=27', 'swf-140g=30', 'sti=37') self.assertEqual(self.host.cli_get_card_type(self.slot1), 'eth-xg-1x') self.assertEqual(self.host.cli_get_card_type(self.slot2), 'stm1-4-et') self.assertEqual(self.host.cli_get_card_type(27), 'stu') self.assertEqual(self.host.cli_get_card_type(30), 'swf-140g') self.assertEqual(self.host.cli_get_card_type(37), 'sti') self.host.cli_delete_card(self.slot1, self.slot2) self.host.cli_create_cards('pwe3-ocnstm=' + self.slot1) self.host.cli_delete_card(self.slot1) def test_cli_stm(self): self.host.cli_create_cards('pwe3-ocnstm=' + self.slot1) self.host.cli_set_card_mode(self.slot1, 'stm1') self.assertEqual(self.host.cli_get_card_mode(self.slot1), 'stm1') self.host.cli_set_card_mode(self.slot1, 'stm4') self.assertEqual(self.host.cli_get_card_mode(self.slot1), 'stm4') self.host.cli_set_card_ip(self.slot1, '172.12.1.19') self.assertEqual(self.host.cli_get_card_ip(self.slot1),'172.12.1.19') self.host.cli_delete_card(self.slot1) self.host.cli_create_cards('stm1-4-et=' + self.slot1) self.host.cli_set_port_EoTDM_mode(self.slot1, 1, 'sts1', 'eopdh') self.assertEqual(self.host.cli_get_port_EoTDM_mode(self.slot1, 1), 'eopdh') self.assertEqual(self.host.cli_get_port_hop_type(self.slot1, 1), 'sts1') self.host.cli_delete_card(self.slot1) def _check_cli_error(): if cli.client.ErrorStr: output_console_error('cliError', "cli return Error", cli.client.ErrorStr, cli.client.ErrorNum, cli.client.ErrorInd) def _datetime(s): date, time = s.split(',') year, month, day = date.split('-') hour, minute, second = time.split('.')[0].split(':') raw = \ r'\x{0:0>2s}\x{1:0>2s}\x{2:0>2s}\x{3:0>2s}\x{4:0>2s}\x{5:0>2s}\x{6:0>2s}\x'\ .format( hex(int(year))[2], hex(int(year))[3:], hex(int(month))[2:], hex(int(day))[2:], hex(int(hour))[2:], hex(int(minute))[2:], hex(int(second))[2:]) + '00' result = urllib.unquote(raw.replace('\\x', '%')) return result class Cli(object): ''' *--Function: cli operations' keywords*. - Support basic cli operations: connect, set, trap, get, set check, \ get check, set rows, walk, safe get, is exist, get single etc. - Support common FSP cli operations: create, destroy, Create Card etc. - Support FSP cli specific feature operations: ecpa_set_stream,\ ecpa_set_control etc. --- Some Glossaries: - arg: the arguments of cli_set, cli_get, cli_walk, etc. \ can be concat of soid, index, value, check value. e.g.\ ecpaControlAction.1.1.1.1=start \ ecpaControlAction.1.1.1.1=start \ ethernet1x10GCardRowStatus.1.1.24=createAndGo -c active - soid: cli string object id. e.g. ecpaControlAction - noid: cli number object id. e.g. .1.3.6.1.4.1.2544.1.12.8.1.1.1.11 - node: cli string object id and index. e.g. ecpaControlAction.1.1.1.1 - index: inistance sequence of a cli id. e.g. 1.1.1.1 ---Rules to write arguments: - index: index can be put after soid or set common index for multi \ nodes. index can be put after soid: ethernet1x10GCardRowStatus.1.1.24.\ common index: | cli set | index=1.1.24 | ethernet1x10GCardRowStatus=unassigned | ''' ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = '1.0.0' client = None reverse = False single = False check = False hostname = None trap_received = False verify = _Verify() fps = {} ########################## basic cli operation ############################ @classmethod def cli_connect(cls,ip,username="root",password="ChgMeNOW"): ''' *Connect to host use cli.* | *Fixed argument* | *type* | *description* | | hostname | string | hostname or ip addr of cli agent. e.g. \ 172.23.191.126 | | *Named argument * | *type* | *description* | | version | string | default '3', [1, 2 (equiv to 2c), 3] | | portNum | string | default '161' | | timeout | string | default '500000', micro-seconds before retry | | retries | string | default '3', retries before failure | | community | string | default 'private', cli community string | *--Robot Example* | cli_connect | 172.23.191.126 | | cli_connect | 172.23.191.126 | version=2 | ''' # Ssh to remote server ssh_newkey = 'Are you sure you want to continue connecting' child = pexpect.spawn('ssh '+ username + '@'+ ip, maxread=5000) # Enter password i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'assword:*', 'key verification failed']) if i == 3: os.remove(os.path.expanduser('~')+'/.ssh/known_hosts') print child.before,child.after, child = pexpect.spawn('ssh '+ username + '@'+ ip, maxread=5000) i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'assword:*']) print child.before,child.after, if i == 0: #*Timeout print 'ERROR TIMEOUT! SSH could not login. ' if i == 1: #*SSH does not have the public key. Just accept it. child.sendline ('yes\r') child.expect ('.*assword: ') print child.before,child.after, #*enter password. child.send(password +"\r") # Reaffirmed can connect to System i = child.expect(['ADVA-->', 'continue.*-->']) print child.before,child.after, if i == 1: #*Send Y child.sendline ('Y\r') child.expect ('ADVA-.*>') print child.before,child.after, Cli.client = child @classmethod def cliCmd(cls,cmd, prompt='ADVA\S*-->'): ''' *Create one or more simple objects.* Create objects can be created by set rowstatus only. e.g. card. | *Arbitrary argument* | *type* | *description* | | *args | string | one or more string like 23, 1.1.11 etc | *--Robot Example* | cli_create | ethernet1x10GCardRowStatus.1.1.24 | | cli_create | ethernet1x10GCardRowStatus.1.1.24 | \ ethernet1x10GCardRowStatus.1.1.11 | ''' Cli.client.buffer = '' Cli.client.send(cmd + "\r") Cli.client.expect(prompt) print Cli.client.before, Cli.client.after, return Cli.client.before, Cli.client.after if __name__ == '__main__': unittest.main(verbosity=2)