我想添加一些关于我的cli应用如何处理不同信号(SIGTERM
等)的测试。我正在与pytest一起使用本机测试解决方案click.testing.CliRunner
。
测试看起来很标准和简单
def test_breaking_process(server, runner):
address = server.router({'^/$': Page("").exists().slow()})
runner = CliRunner(mix_stderr=True)
args = [address, '--no-colors', '--no-progress']
result = runner.invoke(main, args)
assert result.exit_code == 0
并且我被困在这里,如何发送SIGTERM
在runner.invoke
中进行处理?如果使用e2e测试(调用可执行程序而不是CLIrunner),我认为这样做没有问题,但是我想尝试实现这一点(至少能够发送os.kill)
有办法吗?
因此,如果要测试可点击的应用程序以处理不同的信号,则可以执行下一个步骤。
def test_breaking_process(server, runner):
from multiprocessing import Queue, Process
from threading import Timer
from time import sleep
from os import kill, getpid
from signal import SIGINT
url = server.router({'^/$': Page("").slow().exists()})
args = [url, '--no-colors', '--no-progress']
q = Queue()
# Running out app in SubProcess and after a while using signal sending
# SIGINT, results passed back via channel/queue
def background():
Timer(0.2, lambda: kill(getpid(), SIGINT)).start()
result = runner.invoke(main, args)
q.put(('exit_code', result.exit_code))
q.put(('output', result.output))
p = Process(target=background)
p.start()
results = {}
while p.is_alive():
sleep(0.1)
else:
while not q.empty():
key, value = q.get()
results[key] = value
assert results['exit_code'] == 0
assert "Results can be inconsistent, as execution was terminated" in results['output']