cltk编程及应用简介.ppt_第1页
cltk编程及应用简介.ppt_第2页
cltk编程及应用简介.ppt_第3页
cltk编程及应用简介.ppt_第4页
cltk编程及应用简介.ppt_第5页
已阅读5页,还剩48页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Tcl and the Tk Toolkit,ChenTao April, 2010,Outlines,Tcl/Tk Around Us Tcl/Tk Overview Basic Tcl Syntax Introduction for Tk Introduction for Expect Homebrew Test Automation Framework The SUR of TAO Project Resources,Tcl/Tk Around Us,From WorkPlace,In WCS In ITE/8610 Using Expect to communicate with WCS : send CLI commands and get response. In Cisco IOS Routerenable Router#tclsh Router(tcl)#puts $tcl_version 8.3 Test Automation for Telecommunication and Network Equipments,To Our Daily Life,Its easy to design handy programs based on Tcl to fulfill different tasks A fish screen save program A e-piano A Painting pad,Tcl/Tk Overview,-Say “tickle tee-kay”,Whats Tcl,Tcl stands for Tool Command Language Joh Ousterhout, University of California. First release was in 1989. A simple scripting language: Cross platform support. Tcl can run on most popular operation system such as unix/linux, Windows, Macintosh and so forth Scripts are interpreted at run time. Which makes the development cycle faster than compiled languages, no waiting for long compilations The capability to call C/C+ routines Similar to other shell languages such as UNIX C shell, Perl, VB. “Easy” to study Excellent text analysis competence,Whats Tcl (cont),Un-typed and a string-based command language Data types are not used when variables are defined. You neednt specify a variable as integer, float or a string. The basic mechanisms are all related to strings and string substitutions All variables are stored as strings. automatic type conversion in context,set x 10 ;#create a variable “x” and give a value “10” to it set y 20; #create a variable “y” and give a value “20” to it set z expr $x + $y ;# x plus y and save result in “z” set y “Im a string now. Indeed Im always string:-)” puts “Expression result is: $z”; #print result on standard out puts “Y becomes as: ”$y” set aArray “Jack boy Merry girl” ;# define an array puts “Im an array, but a string indeed:n $aArray”,Whats Tcl (cont),Easy to extend There are numerous free extensions built on top of Tcl/Tk for specific functions available on the Internet. Tclx: Handling signal events Net-Snmp : support snmp communinication BWidget/IWidget etc.: Tk extensions provides special and powerful widgets Http & ncgi: for http server programming It is easy to add new Tcl primitives by writing C procedures Tcl/Tk is Pure C Open-Source code, new Tcl commands can be implemented by specific extensions programmed in C , fairly easy without changing Tcl core. Totally Free!,Whats Tk,Tk A Tcl-based toolkit for programming graphical user interfaces Quick and easy to build powerful user interfaces. Portable , one copy of script can work unchanged on UNIX, Windows, and the Macintosh.,Whats Expect,Expect A Tcl-based Toolkit for Automating Interactive Programs The program interactively prompt and expect user to enter keystrokes in response A default command in some operation systems Theres also an Expect extension for tcl which can also be loaded to tcl shell,Tcl not so good news,Interpreted languages run slower and use more processing time or overhead Without a complier,syntax errors cant be found until the script is executed Un-typed languages do not allow for the most efficient translation of code,Basic Tcl Syntax,Tcl Commands Format,A Tcl script consists of one or more commands Commands are separated by newlines or semi-colons A script with two commands separated by a newline character: set a 24 set b 25 Above script could be written on a single line using a semi-colon separator: set a 24; set b 25 Basically each command consists of one or more words First word is the name of a command Additional words are arguments to that command Words are separated by spaces and tabs var1 var2 ,Variable,Neednt declare the type of variable, automatic conversion in context set x “10.99”; # this is a string puts “expr int($x)”;# output would be 10 Need to be declared and assigned a value before use Variable name is case-sensitive Assignment expression : set To use value of a variable, put a “$” ahead of it as $ If you want to append extra characters to a variable, use braces around variable name as: set x “Hello ” puts “$xJack!”; # This is wrong, it would treat xJack as variable name puts “$xJack!”;#This is right! Different scopes should share variable values by specific methods. namespace procedure To use global to visit global variables children interpreter,Comments,Comment is set in a shell way, leading by a “#” set a(“john”) boy ;#Set value of element “john” of array “a” as “boy” # Or we can do as array set a “john boy”; #If you lik, you can comment using multi-lines Be careful when add comments to a “switch” expression switch var “go” to handle go # If it does not support following value, comment it later: = Wrong! “pause ,Standard Output & Input,I/O operation for standard input and output, normally the terminal in front of us. Print out on terminal: puts “abcdefg No Thanks.” Format the string by using “format” command Similar as C set str format “%-2d%20s%9d”, 193 is not equal to 0133;#octal number “193 is not equal to 91” Get input: puts -nonewline “Your name please:” gets stdin sName,Math and Logical Expression,expr expr expr 1 + 2; set x 10; set y 20; expr $x + $y = 30 expr abs(-10) = 10 expr 10 * rand() = 9.06197207004855;#result is double , 0 5 ;# in range of 07 incr set x 1 incr x = 2 incr x 3 = 5 incr x -2 = 3 logic “and” “or” .,Control: Branch and Loop,If elseif.else if Boolean expression if xxx else if xxx elseif else For set sum 0; for set i 0;set y 10 $i 450,While while gets $fd line =0 Switch switch -exact $xyz “0” ; ?break?; “1” ?default ? Foreach (refer to operation of list),List, Array & Operation,“list” represent a list of string Commands for list list, lindex, lrange, lappend, lreplace split, join Array is similar as the “associate” array or hash data in perl or php.,%set lst1 “Jack boy blue Merry girl red”; #or %set lst2 list Red White Yellow Blue %foreach x $lst puts “$xn” %foreach x y z $lst1 puts “student name: $x, a $y, who likes $z“ student name: Jack, a boy, who likes blue student name: Merry, a girl, who likes red puts lindex $lst2 2 = White puts lindex $lst2 0 = Red,%array set aArr list Jack boy Merry girl %parray aArr aArr(Jack) = boy aArr(Merry) = girl %array get aArr Jack boy Merry girl %array names aArr Jack Merry %array size aArr 2 %foreach x y array get aArr puts “Name: $x, a $y“ Name: Jack, a boy Name: Merry, a girl,String & Operation,append format subst,string command string compare string match string equal (added in 8.4) string range string tolower/toupper string trim,string comparation: if $str1 = $str2 puts equal string comparing commands such as “string match”,string class check: string is if string is integer 10 puts ok,Proc and Return,Procedure in tcl similar as function in C, perl, php, unix shell etc. proc arg1 arg2.args proc body return string proc calc1 opa “opb 10” return expr $opa + $opb calc1 2 3 = 5 calc1 2 = 12 proc calc2 args ;# Vary argument list set opa lindex $args 0 set opb lindex $args 1 return expr $opa + $opb global variable In a procedure, use “global ” to make a global variable visible from inside of procedure,File I/O,Write file % set fd open abc w+ =filef76ec0 % puts $fd “abcdn“ % puts $fd “efgtn“ % flush $fd % close $fd,Read file %set fd open abc r =filef840d8 Get file content line by line % while gets $fd line != -1 puts -nonewline $line =abcd efgt Read command read ?chunk bytes? set str read $fd while !eof $fd svet buf read $fd 10000 . ,Socket & File Event,socket ?-myaddr addr? ?-myport myport? ?-async? host port socket -server command ?-myaddr addr? port NOTE: “port” specified here is the “listening” port which cant be used to transfer data. As the connection request is accepted, a new socket will be created for transport data.,proc Accept newSock addr port global sock_arr puts “Accepted $newSock from $addr port $port“ set sock_arr(addr,$newSock) list $addr $port fconfigure $newSock -blocking 0 buffering none fileevent $newSock readable list Echo $newSock ,set status catch socket -server Accept $SERVER_PORT ss if !$status set sock_arr(main) $ss puts “Create server socket success. Servers socket is $ss“ else error “Create servers socket failed: $ss“ ,proc Echo sock global sock_arr if eof $sock | catch gets $sock line return puts $sock string toupper $line flush $sock ,Variable interpolation,Happens in double quote “” and normal expressions set x “Hello” puts “$x Jack!” set y list $x Jack“!” Interpolation would be prohibited in most kinds of braces puts $x Jack the result would be : $x Jack Its not always such thing for brace, brace in some command will not prohibit variable replacement : catch err for if,Error Handling & Diagnostic,Multi-line command set x list Nanjing Beijing list Shen Yang Dalian Should no special character except for carriage-return/new line Should not put comment after the “catch” command catch command catch errors, but would not break the process error information to be saved as the “errorInfo” global variable Store error information the “error” command error command can cause an error, error “line 50 broken for mismatched value” = This error can be captured by “catch” command and return 1, and error string will be set to errorInfo.,Regular Expression Syntax - Commands,regexp regexp ?flags? pattern string ?match sub1 sub2.? # Get IP address out, and last number regexp 0-91,3.0-91,3.:digit:+.(:digit:1,3) “IP Address:“ sMatch sVar1 regsub regsub ?switches? pattern string subspec varname,Regular Expression Syntax - Basic,Matching characters Most characters simply match themselves the period, “.” ,matches any single character ab matches ab; “a.” match an a followed by any charactor. Character sets a-z matches any character in this range a-z matches any character isnt in this range, = not matches or Quantifiers * for zero or more: a* matches zero or more as. “.*” matches anything + for once or more : a+ matches a, aa, aa.a ? zero or one: a? matches zero or one a Alternation (or branch) (H|h)ello matches Hello and hello, same as hello|Hello Anchor : matches the beginning of a string $: matches to the end of a string: .*$ matches a whole line with anything, even empty line Bachslash Quoting To turn off special means of following character: . * ? + ( ) $ | Capturing sub-patterns grouped with parentheses “Im.* IP address (0-9+.0-9+.0-9+.0-9+)$” NOTE: sub-patterns will be captured and save in specific variables. If use (?:pattern), pattern will be captured but not saved, command will be faster,Regular Expression Syntax - Advanced,character classes :digit: =0-9=d :alpha: = A-Za-z :space:= bfnrtv =s Nongreedy Quantifiers By default quantifier + * ? will match as many characters as possible. Use “?” behind them can prohibit such .+n matches as many lines as possible till last line .+?n matches just one line Bound Quantifiers m,n matches latest m times, and maximum n times Back references NOTE: regsub does not support the function of using back-references outside of regular expression in perl s/(S+)s+(S+)/$2 $1/,Signal,trap call back scripts sig_name trap puts “bye bye”;exit SIGINT,Time Event: the after command,proc Circle global switcher if $switcher = “off“ # kill all after event, and then return # do something for repeat after 1000 Circle ,after milliseconds after ms arg ?arg.? after cancel id after cancel command after idle command after info ?id?,Introduction for Tk,Create children widgets,Window is organized in a hierarchy A primary window - the root of the hierarchy, is the main window of the application named as “.” . Widgets in primary window are its children window, named as “.” And child window can has its own children . “.” First charactor of should be in lower-case or a digital number,frame .fBut frame .fText .fBut configure -borderwidth 1 ; .fText configure -borderwidth 1 entry .fBut.eEnt -width 20 set bBut button .fBut.bHello -text “ HELLO! “ .fBut.eEnt configure -bg pink .fBut.bHello configure -command .fBut.eEnt insert end “hello!“; .fText.tText insert end “ Hello “ set tTr text .fText.tText -yscrollcommand “.fText.yscroll set “ -xscrollcommand “.fText.xscroll set “ $tTr configure -width 40 -height 20 -foreground brown -wrap word scrollbar .fText.yscroll -command “$tTr yview“ -orient vertical scrollbar .fText.xscroll -command “$tTr xview“ -orient horizontal,Display Widgets,Put and display widgets in main window: .fBut : a Framework contains a single line text input entry .fText : a Framework contains a text will scrollbar .fBut.eEnt : The entry set bBut .fBut.bHello : A button set tTr .fText.text : Text body .fText.yscroll : X scroll bar (horizontal) .fText.xscroll : Y scroll bar (vertical) Three main geometry manager pack : constraint-based geometry manager grid : control in detail place: place a widget in another one,pack .fBut .fText -side left -fill both -expand true grid .fBut.eEnt -sticky news grid $bBut -sticky news grid $tTr .fText.yscroll -sticky news grid .fText.xscroll -sticky ew grid rowconfigure .fText 0 -weight 1 grid columnconfigure .fText 0 -weight 1 grid propagate .fText false,A Simple Menu,menubutton .mb -text File -menu .mb.menu pack .mb -padx 10 -pady 10 set m menu .mb.menu -tearoff 1 $m add command -label Hello -command puts “Hello, World!“ $m add check -label Boolean -variable foo -command puts “foo = $foo“ $m add separator $m add cascade -label Fruit -menu $m.sub1 set m2 menu $m.sub1 -tearoff 0 $m2 add radio -label apple -variable fruit -value apple $m2 add radio -label orange -variable fruit -value orange $m2 add radio -label kiwi -variable fruit -value kiwi note: to add menu in BsPmMonitorGui,Introduction for Expect,Expect Commands Syntax,spawn spawn telnet return a pid save handle in local variable “spawn_id” send alias of exp_send When use together with Tk, exp_send is prefer. expect expect -re “Password:” -re “User Name:” . exp_continue eof timeout ,interact close exp_internal 0|1 log_file options of “send” -h set send_human .1 .3 1 .05 2 set send_human .4 .4 .2 .5 100 send -s set send_slow 10,.001 timeout,user_spawn_id,user_spawn_id,fifo,in,out,spawn_id,user_spawn_id,user_spawn_id,fifo,in,out,spawn_id No. 1,spawn_id No. 2,in,out,Expect,Expect,fifo,in,out,fifo,standard I/O,Example 1: Manipulate MGW automatically,spawn expect “Login:“ send “rootrn” expect “Password:” send “rootnr” expect “” send “send 13,1:connectrn” expect -timeout 5 -re “connect.*C” send “helprn” expect timeout 3 “C”,spawn expect “Login:“ exp_send “rootrn” exp_continue “Password:” exp_send “rootnr” exp_continue -re “” exp_send “send 13,1:connectrn” puts “connect ok” timeout puts “time out” eof puts “session broken” ,Test Automation with Tcl/Tk and Expect,Manul Test,Test Simulator,analyzes traffic/signaling,SNMP/CLI/WEM,SUT,sends traffic/signaling,Other EM.,Test Engineer,controls,controls,controls,Test Management DB,feedback test results and update test status,tests to do,Test Equipment ( ITE, EAST. ),System Under Test,Element Manager,Test management Data Base,Example Test Scenario,Install patches,Configure System,Specific Configuration,Change Specific config,Cleanup Configuration,Patch fallback,Invoke Test Tool,Verify result ?,Calling Test Tool,Verify result ?,Pass/Fail,Pass/fail,Automation,Simulator,analyzes traffic/signaling,SNMP/CLI/WEM,SUT,sends traffic/signaling,Other EM.,Test Scripts,controls,controls,controls,Test Management DB,feedback test results and update test status,tests to do,Test Equipment ( ITE, EAST. ),System Under Test,Element Manager,Test management Data Base,Thinking About Automation: Methods,Test Harness Editor Execution Execute test scripts in specific flow/sequence Configuration Start/Pause/Stop Status monitor : pass/failure TC number and list Log Report Compatible Test-case language independent Additional: Test requirement mgmt Test Script and Data Method Lined script -data hardcode with script , script cant be shared Capture-Playback -data hardcode with script, script cant be shared Shared script Data-driven (few data drives scripts) Table-driven (huge data drives same scripts) Try to detach data from scripts Key-word driven .,Thinking About Automation: Variable Test,Multi-Path instead of static/single path,Why Tcl,Multi solutions to control equipments Socket Expect SNMP Serial port (Dialup) . Many Test Equipment provides Tcl driven API library Easy for learning and maintenance Easy to extend pcap, libnet Tcl homebrew Ethernet test API Totally free,TestCase Script LIB,Function LIB: NE Functions. TA Functions.,A Example Homebrew Test Framework,Data-Driven + Shared Script,Test Harness Report & Control Functions,Com LIB,SUT,TA a,TA n,Driven Data,Test Harness,Test Execution Configuration File (e.g a batch file),TA a,SUR -Switch Utilization Report,Purpose,SUR is used to collect the utilization of WCS in all sites lab It try to answer following questions about WCS: Switch down time. Switch usage (in term of percentage %) during the up time. How busy is the switch during the usag

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论