You are here

public function CronRunTest::testAutomatedCron in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/system/tests/src/Functional/System/CronRunTest.php \Drupal\Tests\system\Functional\System\CronRunTest::testAutomatedCron()
  2. 10 core/modules/system/tests/src/Functional/System/CronRunTest.php \Drupal\Tests\system\Functional\System\CronRunTest::testAutomatedCron()

Ensure that the automated cron run module is working.

In these tests we do not use REQUEST_TIME to track start time, because we need the exact time when cron is triggered.

File

core/modules/system/tests/src/Functional/System/CronRunTest.php, line 58

Class

CronRunTest
Tests cron runs.

Namespace

Drupal\Tests\system\Functional\System

Code

public function testAutomatedCron() {

  // Test with a logged in user; anonymous users likely don't cause Drupal to
  // fully bootstrap, because of the internal page cache or an external
  // reverse proxy. Reuse this user for disabling cron later in the test.
  $admin_user = $this
    ->drupalCreateUser([
    'administer site configuration',
  ]);
  $this
    ->drupalLogin($admin_user);

  // Ensure cron does not run when a non-zero cron interval is specified and
  // was not passed.
  $cron_last = time();
  $cron_safe_interval = 100;
  \Drupal::state()
    ->set('system.cron_last', $cron_last);
  $this
    ->config('automated_cron.settings')
    ->set('interval', $cron_safe_interval)
    ->save();
  $this
    ->drupalGet('');
  $this
    ->assertSame($cron_last, \Drupal::state()
    ->get('system.cron_last'), 'Cron does not run when the cron interval is not passed.');

  // Test if cron runs when the cron interval was passed.
  $cron_last = time() - 200;
  \Drupal::state()
    ->set('system.cron_last', $cron_last);
  $this
    ->drupalGet('');
  sleep(1);

  // Verify that cron runs when the cron interval has passed.
  $this
    ->assertLessThan(\Drupal::state()
    ->get('system.cron_last'), $cron_last);

  // Disable cron through the interface by setting the interval to zero.
  $this
    ->drupalGet('admin/config/system/cron');
  $this
    ->submitForm([
    'interval' => 0,
  ], 'Save configuration');
  $this
    ->assertSession()
    ->pageTextContains('The configuration options have been saved.');
  $this
    ->drupalLogout();

  // Test if cron does not run when the cron interval is set to zero.
  $cron_last = time() - 200;
  \Drupal::state()
    ->set('system.cron_last', $cron_last);
  $this
    ->drupalGet('');
  $this
    ->assertSame($cron_last, \Drupal::state()
    ->get('system.cron_last'), 'Cron does not run when the cron threshold is disabled.');
}