My code is simple:
def start():
signal(SIGINT, lambda signal, frame: raise SystemExit())
startTCPServer()
So I register my application with signal handling of SIGINT
, then I start a start a TCP listener.
here are my questions:
How can I using python code to send a SIGINT signal?
How can I test whether if the application receives a signal of SIGINT, it will raise a SystemExit exception?
If I run
start()
in my test, it will block and how can I send a signal to it?
First of, testing the signal itself is a functional or integration test, not a unit test. See What's the difference between unit, functional, acceptance, and integration tests?
You can run your Python script as a subprocess with
subprocess.Popen()
, then use thePopen.send_signal()
method to send signals to that process, then test that the process has exited withPopen.poll()
.You can use
os.kill
, which slightly misleadingly, can used to send any signal to any process by its ID. The process ID of the application/test can be found byos.getpid()
, so you would have...The usual way in a test you can check that some code raises SystemExit, is with
unittest.TestCase::assertRaises
...This is the trick: you can start another thread which then sends a signal back to the main thread which is blocking.
Putting it all together, assuming your production
start
function is instart.py
:Then your test code could be like the following, say in
test.py
and run using
The above is the same technique as in the answer at https://stackoverflow.com/a/49500820/1319998