Unit testing and e2e testing are the some techniques used for checking the integrity of any application/software when it is in development. Automation plays an important role in web crawling and software testing as it save time and speed-up the efficiency of the overall process.
PyWinAuto is an automation tool to control Windows applications and send mouse or keyboard actions to window dialog and controls. It is Python based module and can be installed using pip as follow:
1
pip install pywinauto
Figure: PyWinAuto in action. [Source]
Automating an command line application is an simple task because we have clean communication flow which is standard streams and it can be easily achievable by Python built-in module subprocess using this there are, handsome video converters available which communicate with powerful FFMPEG (command line tool for video processing).
Sometime we need to control GUI based application or there is a flow which open up GUI for input while staying in console for it execution life cycle. To handle such situations, PyWinAuto do a awesome job. Sample code for controlling Notepad is followed.
Example Automation for Notepad
In this example we are trying to control Notepad and enter some text i.e. “Testing… One, Two, Three.” and save text with file name “win-auto.txt” in default directory.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from pywinauto.application import Application
from pywinauto.timings import TimeoutError
app = Application().start("notepad.exe")
app.Notepad.Edit.set_text("Testing... One, Two, Three.") # write text on notepad
app.Notepad.menu_select("File->SaveAs") # open save as window
app.SaveAs.EncodingComboBox.select("UTF-8")
app.SaveAs.Edit.set_edit_text("win-auto.txt") # set filename
app.SaveAs.Save.click(double=True) # click save button
try:
app.SaveAs.wait_not("visible") # wait for Save windows to close.
except TimeoutError: # If Save As window doesn't close with in timeout
if app.ConfirmSaveAs.wait("visible"): # check if Confirm Save As is visible
app.ConfirmSaveAs.Yes.click() # click Yes to on Confirm Save As dialog
app.ConfirmSaveAs.wait_not("visible")
app.Notepad.menu_select("File->Exit") # close notepad through menu item
Learn More
There are example code given on the PyWinAuto GitHub page but that leave person with doubt that how could they access button or text area of a given process window, way around is to look at print_control_identifiers
function, this show all the available components/element in GUI Tree.
1
app.Notepad.print_control_identifiers() # list all properties of Notepad
However it get worst when it returns you will 1000s line of output and you have to figure out, your specific element you are looking for.
To get better insight on; how to access element of some of the know applications such as MS Paint, Notepad, 7zip, Firefox and etc, then check out these PyWinAuto examples.