Robot Framework 框架是基於 Python 語言開發的,因此,它本質上是 Python 的一個庫。html
建立 py_robot.py 文件,代碼以下:python
from robot.api import TestSuite from robot.api import ResultWriter from robot.model import Keyword # 百度搜索測試 class BaiduSearchTest: def __init__(self, name, librarys=["SeleniumLibrary"]): # 建立測試套件 self.suite = TestSuite(name) # 導入SeleniumLibrary for lib in librarys: self.suite.resource.imports.library(lib) # 定義變量 def create_variables(self): variables = { "${baidu}": "https://www.baidu.com", "${browser}": "Chrome", "${search_input}": "id=kw", "${search_btn}": "id=su" } for k, v in variables.items(): self.suite.resource.variables.create(k, v) # 測試用例:啓動瀏覽器 def open_browsers(self): test_01 = self.suite.tests.create("啓動瀏覽器") test_01.keywords.create("Open Browser", args=["${baidu}", "${browser}"]) test_01.keywords.create("Title Should Be", args=["百度一下,你就知道"]) # 測試用例:百度搜索測試 def search_word(self): test_02 = self.suite.tests.create("百度搜索測試") test_02.keywords.create("Input Text", args=["${search_input}", "測試教程網"]) test_02.keywords.create("Click Button", args=["${search_btn}"]) test_02.keywords.create("Sleep", args=["5s"]) # 測試用例:斷言驗證搜索結果標題 def assert_title(self): test_03 = self.suite.tests.create("斷言驗證搜索結果標題") test_03.keywords.create("Title Should Be", args=["測試教程網_百度搜索"]) # 測試用例:關閉測試用例 def close_browsers(self): test_04 = self.suite.tests.create("關閉瀏覽器") test_04.keywords.create("Close All Browsers") # 運行 def run(self): self.create_variables() self.open_browsers() self.search_word() self.assert_title() self.close_browsers() # 運行套件 result = self.suite.run(critical="百度搜索", output="output.xml") # 生成日誌、報告文件 ResultWriter(result).write_results( report="report.html", log="log.html") if __name__ == "__main__": print("用Python寫Robot Framework測試") suite = BaiduSearchTest("百度搜索測試套件") suite.run()
這段代碼的運行經過 python 命令來執行。api
> python py_robot.py 用Python寫Robot Framework測試 ============================================================================== 百度搜索測試套件 ============================================================================== 啓動瀏覽器 DevTools listening on ws://127.0.0.1:12950/devtools/browser/bcbf14bb-ebc4-425c-882f-44531afd9689 啓動瀏覽器 | PASS | ------------------------------------------------------------------------------ 百度搜索測試 | PASS | ------------------------------------------------------------------------------ 斷言驗證搜索結果標題 | PASS | ------------------------------------------------------------------------------ 關閉瀏覽器 | PASS | ------------------------------------------------------------------------------ 百度搜索測試套件 | PASS | 0 critical tests, 0 passed, 0 failed 4 tests total, 4 passed, 0 failed ============================================================================== Output: D:\rf_test\robotSe\output.xml
Robot Framework 用的好,Python 少不了!因此,個人建議是要想用好 Robot Framework 必需要學習和掌握 Python 語言。瀏覽器