如何真正测试 Python 中的信号处理? [英] How to really test signal handling in Python?

查看:34
本文介绍了如何真正测试 Python 中的信号处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码很简单:

def start():
    signal(SIGINT, lambda signal, frame: raise SystemExit())
    startTCPServer()

因此,我使用 SIGINT 的信号处理注册了我的应用程序,然后启动了一个 TCP 侦听器.

So I register my application with signal handling of SIGINT, then I start a start a TCP listener.

这是我的问题:

  1. 如何使用 python 代码发送 SIGINT 信号?

  1. How can I using python code to send a SIGINT signal?

如何测试应用程序是否收到 SIGINT 信号,是否会引发 SystemExit 异常?

How can I test whether if the application receives a signal of SIGINT, it will raise a SystemExit exception?

如果我在测试中运行 start(),它会阻塞,我该如何向它发送信号?

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?

您可以使用 将 Python 脚本作为子进程运行subprocess.Popen(),然后使用 Popen.send_signal() 方法 向该进程发送信号,然后使用 Popen.poll().

You can run your Python script as a subprocess with subprocess.Popen(), then use the Popen.send_signal() method to send signals to that process, then test that the process has exited with Popen.poll().

这篇关于如何真正测试 Python 中的信号处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆