使用Python和Robot Framework编写前端测试用例教程
Robot Framework是一个基于Python的通用自动化测试框架,特别适合编写Web前端测试用例。以下是详细教程:
1. 环境搭建
安装必要的包
pip install robotframework
pip install robotframework-seleniumlibrary
pip install selenium
下载浏览器驱动
- Chrome: ChromeDriver
- Firefox: GeckoDriver
将驱动添加到系统PATH中。
2. 基础项目结构
project/
├── tests/
│ ├── __init__.robot
│ ├── login_tests.robot
│ └── search_tests.robot
├── resources/
│ ├── common.robot
│ ├── page_objects/
│ │ ├── login_page.robot
│ │ └── home_page.robot
│ └── variables.robot
└── results/
3. 编写第一个测试用例
创建基础资源文件
resources/variables.robot
*** Variables ***
${BROWSER} chrome
${URL} https://example.com
${DELAY} 0.5
resources/common.robot
*** Settings ***
Library SeleniumLibrary
*** Keywords ***
Open Browser To Login Page
Open Browser ${URL} ${BROWSER}
Maximize Browser Window
Set Selenium Speed ${DELAY}
Login Page Should Be Open
Login Page Should Be Open
Title Should Be Login Page
Go To Login Page
Go To ${URL}/login
Login Page Should Be Open
创建页面对象
resources/page_objects/login_page.robot
*** Variables ***
${USERNAME_FIELD} id=username
${PASSWORD_FIELD} id=password
${LOGIN_BUTTON} id=loginBtn
${ERROR_MESSAGE} css=.error-message
*** Keywords ***
Input Username
[Arguments] ${username}
Input Text ${USERNAME_FIELD} ${username}
Input Password
[Arguments] ${password}
Input Text ${PASSWORD_FIELD} ${password}
Click Login Button
Click Button ${LOGIN_BUTTON}
Login Should Succeed
Location Should Be ${URL}/dashboard
Title Should Be Dashboard
Login Should Fail With Message
[Arguments] ${expected_message}
Wait Until Element Is Visible ${ERROR_MESSAGE}
Element Text Should Be ${ERROR_MESSAGE} ${expected_message}
编写测试用例
tests/login_tests.robot
*** Settings ***
Documentation 登录功能测试用例
Library SeleniumLibrary
Resource ../resources/common.robot
Resource ../resources/page_objects/login_page.robot
Suite Setup Open Browser To Login Page
Suite Teardown Close All Browsers
Test Setup Go To Login Page
*** Test Cases ***
Valid Login
[Documentation] 测试有效登录
Input Username testuser
Input Password testpass123
Click Login Button
Login Should Succeed
Invalid Username
[Documentation] 测试无效用户名
Input Username invaliduser
Input Password testpass123
Click Login Button
Login Should Fail With Message Invalid username or password
Invalid Password
[Documentation] 测试无效密码
Input Username testuser
Input Password wrongpassword
Click Login Button
Login Should Fail With Message Invalid username or password
Empty Credentials
[Documentation] 测试空凭证
Click Login Button
Login Should Fail With Message Please enter username and password
4. 高级测试用例示例
数据驱动测试
tests/data_driven_login.robot
*** Settings ***
Documentation 数据驱动的登录测试
Library SeleniumLibrary
Resource ../resources/common.robot
Resource ../resources/page_objects/login_page.robot
Test Template Login With Invalid Credentials Should Fail
*** Test Cases *** USERNAME PASSWORD EXPECTED_ERROR
Invalid Username invalid_user correct_pass Invalid username
Invalid Password valid_user wrong_pass Invalid password
Empty Username ${EMPTY} testpass Please enter username
Empty Password testuser ${EMPTY} Please enter password
*** Keywords ***
Login With Invalid Credentials Should Fail
[Arguments] ${username} ${password} ${expected_error}
Go To Login Page
Input Username ${username}
Input Password ${password}
Click Login Button
Login Should Fail With Message ${expected_error}
复杂交互测试
tests/search_tests.robot
*** Settings ***
Documentation 搜索功能测试
Library SeleniumLibrary
Resource ../resources/common.robot
Suite Setup Open Browser To Login Page
Suite Teardown Close All Browsers
*** Variables ***
${SEARCH_FIELD} id=search
${SEARCH_BUTTON} id=searchBtn
${RESULTS_CONTAINER} css=.search-results
*** Keywords ***
Perform Search
[Arguments] ${search_term}
Input Text ${SEARCH_FIELD} ${search_term}
Click Element ${SEARCH_BUTTON}
Wait Until Element Is Visible ${RESULTS_CONTAINER}
Verify Search Results Contain
[Arguments] ${expected_text}
Element Should Contain ${RESULTS_CONTAINER} ${expected_text}
Verify No Results Message
Element Should Contain ${RESULTS_CONTAINER} No results found
*** Test Cases ***
Successful Search
[Documentation] 测试成功搜索
Perform Search Robot Framework
Verify Search Results Contain Robot Framework
Search With Special Characters
[Documentation] 测试特殊字符搜索
Perform Search @#$%test
Verify Search Results Contain test
Empty Search
[Documentation] 测试空搜索
Perform Search ${EMPTY}
Verify No Results Message
5. 自定义Python库
创建自定义关键字库 libraries/custom_keywords.py:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from SeleniumLibrary import SeleniumLibrary
class CustomKeywords:
def __init__(self, selenium: SeleniumLibrary):
self.selenium = selenium
def wait_for_element_and_click(self, locator, timeout=10):
"""等待元素可点击后点击"""
driver = self.selenium.driver
element = WebDriverWait(driver, timeout).until(
EC.element_to_be_clickable(locator)
)
element.click()
def take_screenshot_with_timestamp(self, filename_prefix="screenshot"):
"""带时间戳的截图"""
from datetime import datetime
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{filename_prefix}_{timestamp}.png"
self.selenium.capture_page_screenshot(filename)
return filename
在Robot Framework中使用:
*** Settings ***
Library ../libraries/custom_keywords.py
*** Test Cases ***
Test With Custom Keyword
Wait For Element And Click id=submitBtn
${screenshot} Take Screenshot With Timestamp login_test
Log Screenshot saved as: ${screenshot}
6. 运行和报告
运行测试
# 运行所有测试
robot tests/
# 运行特定测试文件
robot tests/login_tests.robot
# 运行带有标签的测试
robot --include smoke tests/
# 生成详细报告
robot --outputdir results --log login_log.html --report login_report.html tests/
配置文件
robot.yml
default:
outputdir: results
log: log.html
report: report.html
include: smoke
exclude: broken
metadata:
Version: 1.0
Environment: TEST
7. 最佳实践
- 页面对象模式: 将页面元素和操作封装成关键字
- 数据驱动: 使用Test Template进行数据驱动测试
- 标签管理: 使用标签分类测试用例
- 错误处理: 合理使用等待和异常处理
- 模块化设计: 将通用功能提取到资源文件中
8. 常用断言和操作
# 元素操作
Click Element id=button
Input Text id=inputField Hello World
Select From List By Value id=dropdown option1
# 断言
Page Should Contain Welcome
Element Should Be Visible id=successMessage
Element Should Be Enabled id=submitBtn
Checkbox Should Be Selected id=agreeCheckbox
# 等待
Wait Until Page Contains Loading complete 10s
Wait Until Element Is Visible id=results 5s
# 浏览器操作
Go To https://newpage.com
Go Back
Reload Page
Get Location # 获取当前URL
这个教程涵盖了Robot Framework前端测试的基础和进阶用法。通过合理的项目结构和关键字设计,可以创建可维护性强、可读性好的前端自动化测试用例。