Question
Laravel 11: Is it possible to force PHPUnit to trigger / "press" CTRL+C to simulate interruption of an artisan command?
I have an artisan command that can run for minutes or hours, processing multitude of records in a loop within the handle()
method.
I have introduced the ability to interrupt such a long process by humans, by allowing them to press CTRL+C during command runtime.
The following code works flawlessly:
pcntl_async_signals(true);
pcntl_signal(SIGINT, [$this, 'shutdown']);
pcntl_signal(SIGTERM, [$this, 'shutdown']);
and as soon as user presses CTRL+C, the shutdown()
method is being called. It doesn't matter what shutdown()
does, it matters that I can trigger it.
However when testing, I don't know how can I simulate pressing CTRL+C to trigger shutdown, so that code-coverage shows body of shutdown as green (called), rather than red (not reached).
I'm already testing whether necessary methods are available:
public function test_sync_process_can_be_interrupted_by_user_via_terminal(): void
{
$this->assertTrue(function_exists('pcntl_async_signals'));
$this->assertTrue(function_exists('pcntl_signal'));
}
This test is green, but this is not enough for me. I want unit test to "press" these keys. How can I force PHPUnit to do so when testing my artisan command $this->artisan('my:long-command')
?