function CronQueueTest::testUncaughtExceptions

Same name in other branches
  1. 10 core/modules/system/tests/src/Kernel/System/CronQueueTest.php \Drupal\Tests\system\Kernel\System\CronQueueTest::testUncaughtExceptions()

Tests that non-queue exceptions thrown by workers are handled properly.

See also

\Drupal\cron_queue_test\Plugin\QueueWorker\CronQueueTestException

File

core/modules/system/tests/src/Kernel/System/CronQueueTest.php, line 175

Class

CronQueueTest
Tests the Cron Queue runner.

Namespace

Drupal\Tests\system\Kernel\System

Code

public function testUncaughtExceptions() : void {
    $this->logger
        ->log(RfcLogLevel::ERROR, '%type: @message in %function (line %line of %file).', Argument::that(function ($args) {
        return $args['@message'] === 'That is not supposed to happen.' && $args['exception'] instanceof \Exception;
    }))
        ->shouldBeCalled();
    $this->logger
        ->log(RfcLogLevel::INFO, 'Cron run completed.', Argument::cetera())
        ->shouldBeCalled();
    // Get the queue to test the normal Exception.
    $queue = $this->container
        ->get('queue')
        ->get(CronQueueTestException::PLUGIN_ID);
    // Enqueue an item for processing.
    $queue->createItem([
        $this->randomMachineName() => $this->randomMachineName(),
    ]);
    // Run cron; the worker for this queue should throw an exception and handle
    // it.
    $this->cron
        ->run();
    $this->assertEquals(1, \Drupal::state()->get('cron_queue_test_exception'));
    // The item should be left in the queue.
    $this->assertEquals(1, $queue->numberOfItems(), 'Failing item still in the queue after throwing an exception.');
    // Expire the queue item manually. system_cron() relies in
    // \Drupal::time()->getRequestTime() to find queue items whose expire field needs to be
    // reset to 0. This is a Kernel test, so \Drupal::time()->getRequestTime() won't change
    // when cron runs.
    // @see system_cron()
    // @see \Drupal\Core\Cron::processQueues()
    $this->connection
        ->update('queue')
        ->condition('name', 'cron_queue_test_exception')
        ->fields([
        'expire' => \Drupal::time()->getRequestTime() - 1,
    ])
        ->execute();
    $this->cron
        ->run();
    $this->assertEquals(2, \Drupal::state()->get('cron_queue_test_exception'));
    $this->assertEquals(0, $queue->numberOfItems(), 'Item was processed and removed from the queue.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.