(Unit) Test python signal handler

后端 未结 2 929
天涯浪人
天涯浪人 2021-01-21 13:51

I have a simple Python service, where there is a loop that performs some action infinitely. On various signals, sys.exit(0) is called, which causes SystemExit

2条回答
  •  臣服心动
    2021-01-21 14:28

    You can trigger a SIGINT (or any signal) from another thread after some delay, which is received in the main thread. You can then assert on its effects just as in any other test, as below.

    import os
    import signal
    import time
    import threading
    import unittest
    from unittest.mock import (
        Mock,
        patch,
    )
    
    import service
    
    class TestService(unittest.TestCase):
    
        @patch('service.print')
        def test_signal_handling(self, mock_print):
    
            pid = os.getpid()
    
            def trigger_signal():
                while len(mock_print.mock_calls) < 1:
                    time.sleep(0.2)
                os.kill(pid, signal.SIGINT)
    
            thread = threading.Thread(target=trigger_signal)
            thread.daemon = True
            thread.start()
    
            service.main()
    
            self.assertEqual(mock_print.mock_calls[1][1][0], 'Some cleanup')
    
    
    if __name__ == '__main__':
        unittest.main()
    

提交回复
热议问题