使用Appium和WinAppDriver开始进行Windows桌面自动化测试
前提设置
1.Python安装和环境设置
安装 Python
-
从官方网站下载 Python。
-
安装过程中,勾选“将 Python 添加到 PATH”选项。
-
使用以下命令验证安装:
python --version
pip --version
创建并激活虚拟环境
创建虚拟环境可以保持依赖项的整洁和隔离。
创建1个新环境:
python -m venv venv
激活它
venv\Scripts\activate
安装Appium Python客户端
pip install Appium-Python-Client
2.安装WinAppDriver
访问WinAppDriver版本页面并下载最新的稳定版本,WinAppDriver 提供 Appium 用于控制 Windows 桌面应用程序的通信桥梁。
3.安装Node.js
从Node官网下载 Windows 安装程序,安装程序会自动包含 npm,你需要使用 npm 来安装和运行 Appium。
4.安装Appium服务器
Node.js 安装完成后,使用 npm 全局安装 Appium:
npm install -g appium
5.安装Appium Windows驱动
运行以下命令安装 Appium Windows 驱动程序,以添加对 Windows 桌面自动化的支持:
appium driver install windows
运行以下命令验证 Windows 驱动程序是否已成功安装:
appium driver list
6.启动Appium服务器
在终端中运行以下命令启动 Appium 服务器:
appium
在测试期间,请保持此终端窗口运行。
7.安装定位工具
Windows Inspector
它是检查 Windows UI 自动化元素的主要实用程序,你可以使用它来读取属性、验证树状结构,并在连接到正在运行的应用程序时提取 NativeWindowHandle。
Appium Inspector
强烈推荐使用此工具,它可以帮助你通过 Appium 会话预览元素、验证 XPath 表达式并更轻松地探索 UI 结构。Appium Inspector 在处理属性不唯一的旧版应用程序时尤其有用。
编写脚本
以打开记事本为例:
-
启动记事本
-
找到文本编辑区域
-
清除任何现有内容
-
验证内容是否已清除
-
添加新文本
-
验证文本是否已成功添加
-
关闭应用程序
示例代码:
from appium import webdriver
from appium.options.windows import WindowsOptions
from selenium.webdriver.common.keys import Keys
import time
deftest_notepad_app():
options = WindowsOptions()
options.set_capability("app", "notepad.exe")
options.set_capability("platformName", "Windows")
options.set_capability("deviceName", "WindowsPC")
driver = webdriver.Remote(
command_executor="http://127.0.0.1:4723",
options=options
)
time.sleep(1)
text_area = driver.find_element("name", "Text editor")
text_area.send_keys(Keys.CONTROL, 'a')
text_area.send_keys(Keys.DELETE)
cleared_value = text_area.get_attribute("Value.Value")
assert cleared_value == None, "Text area not cleared properly!"
print("✓ Cleared existing text if any and verified it")
new_text = "Writing text using Appium with WinAppDriver"
text_area.send_keys(new_text)
added_value = text_area.get_attribute("Value.Value")
assert added_value == new_text, "Text not added correctly!"
print("✓ Added text and verified it")
driver.quit()
print("✓ Test completed successfully")
if __name__ == "__main__":
test_notepad_app()
运行测试
脚本准备就绪后,运行测试非常简单。在执行测试之前,请确保以下组件正常运行。
启动Appium服务器
Appium 必须手动启动并在后台运行,打开新的命令提示符窗口并运行:
appium
运行Python脚本
导航到包含测试脚本的文件夹并执行以下命令:
python test_notepad_app.py
夜雨聆风
