【原创】基于pyautogui库进行自动化测试
前期准备:
python3.6
pyautogui
pywinauto
以下代码实现内容:
1.打开记事本
2.记事本中输入This is a test
3.保存内容
4.退出进程
import pyautogui from pywinauto import application import time import os class Autogui(): def __init__(self): self.app=application.Application() def run(self, tool_name): self.app.start(tool_name) time.sleep(2) #defined coordinates def coordinate(self,path): try: coordinates = pyautogui.locateOnScreen(path) x, y = pyautogui.center(coordinates) return x,y except Exception as e: print('Undefined coordinates: ', e) #Abnormal judgment def onscreen(self,x,y,content1): while pyautogui.onScreen(x, y) == True: print(content1) break def moveto(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) def moverel(self,x,y): pyautogui.moveRel(x,y,1,pyautogui.easeInQuad) def leftclick(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.click(button='left') def leftclick_down(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.mouseDown(button='left') def leftclick_up(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.mouseUp(button='left') def rightclick(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.click(button='right') def middleclick(self0,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.click(button='middle') def doubleclick(self,x,y): pyautogui.moveTo(x,y,0.5,pyautogui.easeInQuad) pyautogui.PAUSE=0.5 pyautogui.doubleClick(button='left') def keydown(self,key): pyautogui.keyDown(key) def press(self,key): pyautogui.press(key) def keyup(self,key): pyautogui.keyUp(key) def hotkey(self,key1,key2): pyautogui.hotkey(key1,key2) if __name__=='__main__': Test=Autogui() application_path=input('Application path : ') Test.run(application_path) # Test.run('notepad.exe') time.sleep(1) source_Path='./fouce.png' source_judge_Path='./fouce_judge.png' content1='The edit operation is correct' content2='The edit operation is fail' key1='s' key2='ctrlleft' # edit try: Test.leftclick(Test.coordinate(source_Path)[0], Test.coordinate(source_Path)[1]) pyautogui.typewrite('This is a test',0.1) time.sleep(0.5) Test.onscreen(Test.coordinate(source_judge_Path)[0], Test.coordinate(source_judge_Path)[1], content1) except Exception as e: print(content2 + ': ', e) # save try: time.sleep(2) Test.hotkey(key2, key1) time.sleep(0.5) print('The save operation is correct') except Exception as e: print('Save Error: ', e) try: time.sleep(2) os.system('taskkill /F /IM notepad.exe') except Exception as e: print('Exit Error: ',e) input()
贴上代码中两张图片,fouce.png 用来将光标定位到输入区域,fouce_judge.png 用来跟实际结果做对比,判断实际结果是否正确
fouce.png
fouce_judge.png
pyautogui自动化脚本优点
1.不用担心因为分辨率的改变导致脚本失效(这句话是错的,分辨率会影响识别)
2.完全自定义日志输出
3.真UI自动化,可以判断每一步UI是否正确
积极拥抱前沿技术的软件测试工程师