win ui自动化测试

import uiautomation, time, os, random
# 借助 inspect。exe 工具定位

def cal_test():
os.system('calc.exe')
time.sleep(2)
cal = uiautomation.WindowControl(Name='计算器', searchDepth=1) # searchDepth搜索深度
# print(cal.BoundingRectangle)
# cal.Maximize()
cal.ButtonControl(Name='三').Click()
cal.ButtonControl(AutomationId='plusButton').Click()
cal.ButtonControl(Name='五').Click()
cal.ButtonControl(Name='等于').Click()
time.sleep(1)
result = cal.TextControl(AutomationId='CalculatorResults').Name
print(result)
if result == '显示为 8':
print('ok')
else:
print('no')

cal.MenuItemControl()


cal_test()

一、uiautomation方法
1、WindowContrl(searchDepth,ClassName,SubName) 查找窗口中的程序,如果有中文则需用Unicode;可用window.Exists(maxSearchSeconds)来判断此窗口是否存在;
2、EditControl(searchFromControl) 查找编辑位置,找到后可用DoubleClick()来改变电脑的focus;edit.SetValue(“string”)输入值;
3、Win32API.SendKeys(“string”) 如果已在编辑位置,则可用此方法来输入值,{Ctrl}为ctrl键,其他类似;{@ 8}格式可输入8个@,对于数字也可实现此功能,但对于字母不能…;
4、MenuItemControl(searchFromControl,Name) 查找菜单按钮;
5、ComboBoxControl(searchFromControl,AutomationI) 查找下拉框,然后在此基础上用Select(“name”)方法来选择需要的选项;
6、BottonControl(searchFromControl,Name,SubName) 查找按钮;
7、automation.FindControl(firefoxWindow,
二、对找到句柄常用操作
Click() 点击;
RighClik() 右键点击;
SendKeys() 发送字符;
SetValue() 传值,一般对EditControl用;
三、对windows程序常用操作
subprocess.Popen(‘Name’)   用进程打开程序;
window.Close()         关闭窗口;
window.SetActive()     使用;
window.SetTopMost()     设置为顶层
window.ShowWindow(uiautomation.ShowWindow.Maximize) 窗口最大化
window.CaptureToImage(‘Notepad.png’) 截图;
uiautomation.Win32API.PressKey(uiautomation.Keys.VK_CONTROL) 按住Ctrl键
uiautomation.Win32API.ReleaseKey(uiautomation.Keys.VK_CONTROL) 释放Ctrl键
automation.GetConsoleWindow() #return console window that runs python,打开控制台
automation.Logger.ColorfulWriteLine(’ I will open <Color=Green>Notepad and <Color=Yellow>automate it. Please wait for a while.’) 控制台传值(彩色字体),普通传值用WriteLine;
automation.ShowDesktop() 显示桌面;
四、句柄的抓取
直接运行automation模块枚举窗口时,支持下列参数(从doc窗口运行automation.py程序 ):
-t intValue 延迟枚举时间,单位秒
-r 从树的根部枚举,如果不指定,从当前窗口枚举
-d intValue 枚举控件树的的深度,如果不指定,枚举整个树
-f 从焦点控件枚举,如果不指定,从当前窗口枚举
-c 从光标下的控件枚举,如果不指定,从当前窗口枚举
-a 获取光标下控件及其所有父控件
-n 显示控件的完整Name, 如果不指定,只显示前30个字符
-m 显示控件更多属性,默认只显示控件的四个属性
示例:
automation.pyc –t3, 3秒后枚举当前窗口所有控件
automation.pyc –d2 –t3, 3秒后枚举当前窗口前三层控件
automation.pyc –r –d1 –t0 -n, 0秒后从根部枚举前两层控件,并显示控件完整名称
automation.pyc –c –t3, 3秒后显示鼠标光标下面的控件信息
原文地址:https://www.cnblogs.com/yaohu/p/12588968.html