You are here

function CronRunTest::testAutomatedCron in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 core/modules/system/src/Tests/System/CronRunTest.php \Drupal\system\Tests\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/src/Tests/System/CronRunTest.php, line 51
Contains \Drupal\system\Tests\System\CronRunTest.

Class

CronRunTest
Tests cron runs.

Namespace

Drupal\system\Tests\System

Code

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(array(
    '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
    ->assertTrue($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);
  $this
    ->assertTrue($cron_last < \Drupal::state()
    ->get('system.cron_last'), 'Cron runs when the cron interval is passed.');

  // Disable cron through the interface by setting the interval to zero.
  $this
    ->drupalPostForm('admin/config/system/cron', [
    'interval' => 0,
  ], t('Save configuration'));
  $this
    ->assertText(t('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
    ->assertTrue($cron_last == \Drupal::state()
    ->get('system.cron_last'), 'Cron does not run when the cron threshold is disabled.');
}