如何在RSpec中测试信号处理,尤其是SIGTERM的处理? [英] How to test signal handling in RSpec, particularly handling of SIGTERM?
问题描述
Heroku可能出于各种原因将SIGTERM发送到您的应用程序,因此我创建了一个处理程序来处理一些清理工作,以防万一.某些谷歌搜索尚未就如何在RSpec中进行测试提供任何答案或示例.这是基本代码:
Heroku may send a SIGTERM to your application for various reasons, so I have created a handler to take care of some cleanup in case this happens. Some googling hasn't yielded any answers or examples on how to test this in RSpec. Here's the basic code:
Signal.trap('TERM') do
cleanup
end
def cleanup
puts "doing some cleanup stuff"
...
exit
end
当程序收到SIGTERM时,测试此清除方法的最佳方法是什么?
What's the best way to test that this cleanup method is called when the program receives a SIGTERM?
推荐答案
杀死自己!使用Process.kill 'TERM', 0
将信号发送到RSpec并测试该处理程序是否已被调用.的确,如果没有捕获到信号,则测试将崩溃,而不是很好地报告失败,但是至少您会知道代码中存在问题.
Kill yourself! Send the signal to RSpec with Process.kill 'TERM', 0
and test that the handler is called. It's true that if the signal isn't trapped the test will crash rather than nicely reporting a failure, but at least you'll know there's a problem in your code.
例如:
class SignalHandler
def self.trap_signals
Signal.trap('TERM') { term_handler }
end
def self.term_handler
# ...
end
end
describe SignalHandler do
describe '#trap_signals' do
it "traps TERM" do
# The MRI default TERM handler does not cause RSpec to exit with an error.
# Use the system default TERM handler instead, which does kill RSpec.
# If you test a different signal you might not need to do this,
# or you might need to install a different signal's handler.
old_signal_handler = Signal.trap 'TERM', 'SYSTEM_DEFAULT'
SignalHandler.trap_signals
expect(SignalHandler).to receive(:term_handler).with no_args
Process.kill 'TERM', 0 # Send the signal to ourself
# Put the Ruby default signal handler back in case it matters to other tests
Signal.trap 'TERM', old_signal_handler
end
end
end
我只是测试了处理程序是否被调用,但是您同样可以很好地测试处理程序的副作用.
I merely tested that the handler was called, but you could equally well test a side effect of the handler.
这篇关于如何在RSpec中测试信号处理,尤其是SIGTERM的处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!