在介紹這個以前,能夠先看下python的目錄Python\Lib\site-packages下面的文件夾,你會發現這個目錄下面有DatabaseLibrary、RequestsLibrary、Selenium2Library等等這些咱們熟悉的名稱,沒錯,就是在RIDE編輯框裏面import的包名,因此有時候爲何會import失敗(導入後顯示紅色),就是由於這個目錄沒有你要導入的包。所以,咱們若是要開發自定義關鍵字庫,就能夠在這個目錄新建一個相似的文件夾便可,具體結構是怎麼樣的,能夠先看看RequestsLibrary是怎麼寫的,依葫蘆畫瓢便可。html
點開RequestsLibrary目錄以後,咱們發現有這麼幾個py文件python
首先看__init__.py,學了python的同窗都知道這個很眼熟,類的初始化時常常用到,這裏的做用基本相似,打開看下git
from .RequestsKeywords import RequestsKeywords from .version import VERSION _version_ = VERSION class RequestsLibrary(RequestsKeywords): """ RequestsLibrary is a HTTP client keyword library that uses the requests module from Kenneth Reitz https://github.com/kennethreitz/requests Examples: | Create Session | google | http://www.google.com | | Create Session | github | http://github.com/api/v2/json | | ${resp} | Get google | / | | Should Be Equal As Strings | ${resp.status_code} | 200 | | ${resp} | Get github | /user/search/bulkan | | Should Be Equal As Strings | ${resp.status_code} | 200 | | ${jsondata} | To Json | ${resp.content} | | Dictionary Should Contain Value | ${jsondata['users'][0]} | Bulkan Savun Evcimen | """ ROBOT_LIBRARY_SCOPE = 'GLOBAL'
這裏就知道另一個文件version.py是幹啥用的了,這個筆者認爲無關緊要,只是一個版本號,直接在__init__.py定義也同樣。類名RequestsLibrary就是咱們在RIDE導入的名稱,繼承的這個RequestsKeywords,就是文件RequestsKeywords.py裏面的一個關鍵字實現類,最後一行ROBOT_LIBRARY_SCOPE = 'GLOBAL',必需要加,自定義時照着寫便可,RF框架會自動識別;最後一個文件compat.py點開閱讀源碼後發現,實際上是在判斷是否爲python3,主要爲了兼容python2和python3而import依賴包,也不是必要文件。所以咱們能夠知道,實際生效有做用的文件主要就是__init__.py和RequestsKeywords.py了。github
接下來筆者不詳細舉案例了,簡單分析一下RequestsKeywords.py裏面的一個關鍵字實現編程
def create_session(self, alias, url, headers={}, cookies=None, auth=None, timeout=None, proxies=None, verify=False, debug=0, max_retries=3, backoff_factor=0.10, disable_warnings=0): """ Create Session: create a HTTP session to a server ``url`` Base url of the server ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of default headers ``auth`` List of username & password for HTTP Basic Auth ``timeout`` Connection timeout ``proxies`` Dictionary that contains proxy urls for HTTP and HTTPS communication ``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to False. ``debug`` Enable http verbosity option more information https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel ``max_retries`` The maximum number of retries each connection should attempt. ``backoff_factor`` The pause between for each retry ``disable_warnings`` Disable requests warning useful when you have large number of testcases """ auth = requests.auth.HTTPBasicAuth(*auth) if auth else None logger.info('Creating Session using : alias=%s, url=%s, headers=%s, \ cookies=%s, auth=%s, timeout=%s, proxies=%s, verify=%s, \ debug=%s ' % (alias, url, headers, cookies, auth, timeout, proxies, verify, debug)) return self._create_session( alias, url, headers, cookies, auth, timeout, max_retries, backoff_factor, proxies, verify, debug, disable_warnings)
create_session這個關鍵字是否是很熟悉,在RF中使用的時候,直接輸入Create Session便可使用,按F5查看幫助信息,跟上面源碼註釋部分同樣。json
好了,弄明白這個原理,接下來就能夠依葫蘆畫瓢愉快的手撕python代碼實現本身想要的關鍵字了,哈哈~~api
擴展:若是按照上述的方法,確實能夠完成用戶自定義庫的開發,可是有時候這樣會給項目維護帶來必定的困難,由於你寫的關鍵字不是跟項目的測試用例放在一塊兒維護的,還須要單獨去維護用戶自定義庫的工程。因此推薦另一種方式完成自定義關鍵字庫的開發和維護,這裏舉一個例子,在關鍵字的文件夾下面直接建立一個py文件,採用函數式編程的方式,使用的關鍵字以前,直接導入Library,選擇你寫好的py文件。注意:路徑不對或者py文件語法寫的有問題導入都會報錯,顯示紅色。cookie
示例代碼,mykey.py:session
import json import types import sys from robot.api import logger from robot.libraries.BuiltIn import BuiltIn builtin = BuiltIn() PY3 = sys.version_info > (3,) def mykey_to_json(content, pretty_print=False): """ Convert a string to a JSON object ``content`` String content to convert into JSON ``pretty_print`` If defined, will output JSON is pretty print format """ if PY3: if isinstance(content, bytes): content = content.decode(encoding='utf-8') if pretty_print: json_ = _json_pretty_print(content) else: json_ = json.loads(content) logger.info('To JSON using : content=%s ' % (content)) logger.info('To JSON using : pretty_print=%s ' % (pretty_print)) return json_ def _json_pretty_print(content): """ Pretty print a JSON object ``content`` JSON object to pretty print """ temp = json.loads(content) return json.dumps(temp, sort_keys=True, indent=4, separators=(',', ': '))