差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

rf:rf:evaluate [2013/03/11 01:30]
tony
rf:rf:evaluate [2023/06/25 09:48]
行 1: 行 1:
-{{tag>​RobotFramework}} 
-====== Evaluate該怎麼用?​ ====== 
-===== 前言 ===== 
-Builtin的RobotFramework Library提供了**Evaluate** Keyword。它所提供的功能是「執行Python描述句」。但實際上到底有什麼用途呢?​原本我僅僅拿來將string轉為int的功用,經過一些查詢與試驗,我將心得整理給大家。 
-===== Builtin ===== 
-Builtin的function可以參考[[http://​robotframework.googlecode.com/​hg/​doc/​libraries/​BuiltIn.html?​r=2.7.6#​Evaluate|Library Doc for Evaluate]]。這裡針對我有使用的function做說明。 
-==== 數字轉換 ==== 
-Python提供了int、long、float與complex等function讓你可以將字串轉為數字,也可以透過它們做四則運算。首先以字串轉數字為例,我將8設於${num_str}中,再透過Evaluate+int轉為數字。這裡必須注意的是:​ 「int()中放變數必須以單引號'​括起」。否則,假如你設定的數字為08,在轉換int時會出現Syntax Error。 
-<​code>​ 
-${num_str} | Set Variable | 8 
-${num} | Evaluate | int('​${num_str}'​) 
-</​code>​ 
-其中int與long的第二個參數為base,這是根據你的input所決定:​ 
-<​code>​ 
-Comment | num = 9 
-${num} | Evaluate | int('​11',​ 8)  
-Comment | num = 11 
-${num} | Evaluate | int('​11',​ 10) 
-Comment | num = 17 
-${num} | Evaluate | int('​11',​ 16) 
-</​code>​ 
-其它還有像bin、oct、hex,可以將整數轉為2、8、16進位。 
-==== 運算 ==== 
-四則運算:​ 直接將運算子加上即可:​ 
-<​code>​ 
-${num} | Evaluate | int('​${hour}'​)*60 + int('​${min}'​) 
-</​code>​ 
-指數: 可以用pow。以下面兩個例子來說,第一個是2的3次方為8,第二個是2的3次方再mod 7為1。需注意的是:​ 「傳入值必須是數字不可為字串」。 
-<​code>​ 
-${num} | Evaluate | pow(2,3) 
-${num} | Evaluate | pow(2,3,7) 
-</​code>​ 
-取最大最小值:​ 使用max/​min,可以選擇丟一個array的方式,也可以當多個參數傳入。 
-<​code>​ 
-@{num_list} | Create List | 2 | 3 | 5 | 7 
-${num} | Evaluate | max(@{num_list}) 
-${num} | Evaluate | min(@{num_list}) 
-${num} | Evaluate | min(1,​3,​5,​7) 
-</​code>​ 
-其它還有abs、ord、unichar等functions,這部分就當大家的功課了。 
-===== Other Libraries ===== 
-在前一節中,是直接透過使用function去達到你的需求,因為在Python中,函式也是屬於First-Class。在這部分主要分享給你的,是使用物件所提供的函示。以前剛開始寫Robot時,只是想做tolowercase與touppercase的字串轉換。但因為Robot本身的Library中並沒有提供這樣s的Keyword,只好自己寫一個出來。要達到這個需求,除了使用Plugin寫法去引用Java或Python中的字串函式外,Evaluate也能達到一樣的效力。我直接使用[[http://​docs.python.org/​2/​library/​stdtypes.html#​string-methods|Built-in DataType]]的function來達到lower與upper的轉換:​ 
-<​code>​ 
-${str} | Set Variable | TEMP 
-${lower_str} | Evaluate | '​${str}'​.lower() 
-${upper_str} | Evaluate | '​${str}'​.upper() 
-</​code>​ 
  
- 
- 
-===== 總結 ===== 
-不是每一個function都能夠使用,因為Robot並不一定能夠接受參數與回傳格式,而且function會根據Python版本不一定會支援。如果你是透過RobotFramework的jar,那它所用的Python版本就要看Jython。假如使用了不支援的function,以bin()來說,應該會看到NameError:​ name '​bin'​ is not defined的錯誤訊息,這時候就要自己來了! \\ 
-\\ 
-友藏內心獨白:​ 沒有妳在我都自己來~我都自己來。 
-===== Reference ===== 
-  * [[http://​docs.python.org/​2/​library/​|Python Library]] 
-  * [[http://​robotframework.googlecode.com/​hg/​doc/​libraries/​BuiltIn.html?​r=2.7.6#​Evaluate|Library Doc for Evaluate]] 
-  * [[http://​docs.python.org/​2/​library/​functions.html|Bultin Function for Python]] 
- 
-=====    ===== 
----- 
-\\ 
-~~DISQUS~~