Search code examples
pythonunit-testingtddtkinter

How do I run unittest on a Tkinter app?


I've just begun learning about TDD, and I'm developing a program using a Tkinter GUI. The only problem is that once the .mainloop() method is called, the test suite hangs until the window is closed.

Here is an example of my code:

# server.py
import Tkinter as tk

class Server(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.mainloop()

# test.py
import unittest
import server

class ServerTestCase(unittest.TestCase):
    def testClassSetup(self):
       server.Server()
       # and of course I can't call any server.whatever functions here

if __name__ == '__main__':
    unittest.main()

What is the appropriate way of testing Tkinter apps? Or is it just 'dont'?


Solution

  • One thing you can do is spawn the mainloop in a separate thread and use your main thread to run the actual tests; watch the mainloop thread as it were. Make sure you check the state of the Tk window before doing your asserts.

    Multithreading any code is hard. You may want to break your Tk program down into testable pieces instead of unit testing the entire thing at once (which really isn't unit testing).

    I would finally suggest testing at least at the control level if not lower for your program, it will help you tremendously.