[Python] How to test python threads?

Discussão em 'Python' iniciado por Stack, Agosto 31, 2025.

  1. Stack

    Stack Membro Participativo

    Setup: a chat app that can (obviously) send and receive strings. My test code:

    157 # System test.
    158 try:
    159 import time
    160 Thread(target=listen, daemon=True).start()
    161 time.sleep(1)
    162 Thread(target=say, args=['localhost', 'Test message!@#'], daemon=True).start()
    163 time.sleep(1)
    164 print('\nSYSTEM TEST PASSED')
    165 except Exception as e:
    166 print('\nSYSTEM TEST FAILED!')
    167 print('Reason: ', e)


    Despite the prolific sleep(), exceptions in the threads are printed yet not propagated to the main thread so it never 'FAILED'-s.

    The obvious solution is to implement some inter-thread communication mechanism. What worries me is that would be solely for the tests - the happy path requires it not. And once you go ITC you start needing syncronization and whatnot.

    Is it wise to add this extra complexity(source or bugs and head-scratching) solely for the purpose of testing? Isn't there a cleaner solution?

    Continue reading...

Compartilhe esta Página