Unittest Tkinter File Dialog Unittest Tkinter File Dialog tkinter tkinter

Unittest Tkinter File Dialog


Unit testing of Tkinter code is not an easy issue. For instance, the IDLE does not have a proper test suite, even though it is part of the standard library. Since you mention that this is going to be the only use of Tkinter in your application, I'd suggest to make unit tests for the outcome of this code: the value of filename.

For instance, you can have a test for a .csv file, and another one for an incorrect file extension. Since tkFileDialog returns an empty string if it is closed by the user, add also a test where filename = ''.

import unittestclass TestFileDialog(unittest.TestCase):    def test_dialog_closed(self):        filename = ''        # ...    def test_incorrect_extension(self):        filename = '/path/to/another/filetype'        # ...    def test_csv_extension(self):        filename = '/path/to/correct/file.csv'        # ...


You could just patch the calls to tkinter:patch tk.Tk() because most CI's will error because they don't have displays.Also patch the file dialog so you can simulate return values and that it is being called with what you expect.

@patch('your_module.tk.Tk')def test_your_stuff(self, Tk)    with @patch('your_module.tkFileDialog.askopenfilename') as file_dialog:        expected = 'expected return value'        assert expected = your_function_calling_file_dialog()        file_dialog.assert_called_once_with(whatever, you, expect, it, to, be, called, with)