I have a Python tkinter script which I want to run some functional tests on. The script includes both tkinter.filedialog.askopenfilename()
and tkinter.filedialog.asksaveasfilename()
, so I wanted a part of the test which uploads/downloads a file. I tried to use pyautogui
to try to automate mouse clicks and to send keys to try to automate these actions, but doing so didn't work (nothing visible changed on the screen and no file was loaded).
Functional Test attempt with pyautogui
class TestOrganizeAttendance(unittest.TestCase): def setUp(self): self.organizer = AttendanceOrganizer() ... def test_attendance_organizer_window_operation(self): ... #User clicks button and their computer's files appear self.organizer.upload_file_button.invoke() self.assertIn( "explorer.exe", [p.name() for p in psutil.process_iter()]) #User selects a file to be uploaded filepath = os.path.abspath( os.path.join('.', 'tests', 'sample_attendance.csv')) pyautogui.PAUSE = 2.5 pyautogui.hotkey('alt', 'd') pyautogui.typewrite(filepath) pyautogui.hotkey('enter') ....
Script
class AttendanceOrganizer: def __init__(self): self.upload_file_button = tkinter.Button( self.root, text="Upload File", command=self.upload_file) self.download_file_button = tkinter.Button( self.root, text="Download File", command=self.download_file) ... def upload_file(self): self.details_var.set( value="Select a file to upload") filetypes = [('Comma Separated Values', '.csv')] filepath = tkinter.filedialog.askopenfilename( parent=self.root, filetypes=filetypes) if not (filepath and os.path.splitext(filepath)[-1] == '.csv'): return self.upload_var.set(value=filepath) self.details_var.set( value=f"File Uploaded\t{self.details_var.get()}") with open(filepath, encoding='utf-16') as file: self.values = list(csv.reader(file, delimiter='\t')) del self.values[0] self.organize_data_button.config(state='normal') def download_file(self): filetypes = [('Comma Separated Values', '.csv')] filepath = tkinter.filedialog.asksaveasfilename( parent=self.root, filetypes=filetypes) with open(f"{filepath}.csv", 'w', newline='') as file: fieldnames = ["Last", "First", "Joined", "Left"] writer = csv.DictWriter( file, fieldnames=fieldnames, delimiter='\t') writer.writeheader() for item in self.data: writer.writerow(self.data[item]) ...
https://stackoverflow.com/questions/65546214/automate-tkinter-file-dialogues-for-functional-testing January 03, 2021 at 10:49AM
没有评论:
发表评论