function CronRunTest::testAutomaticCron

Ensure that the automatic cron run feature 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

drupal/core/modules/system/lib/Drupal/system/Tests/System/CronRunTest.php, line 56
Definition of Drupal\system\Tests\System\CronRunTest.

Class

CronRunTest

Namespace

Drupal\system\Tests\System

Code

function testAutomaticCron() {

  // Ensure cron does not run when the cron threshold is enabled and was
  // not passed.
  $cron_last = time();
  $cron_safe_threshold = 100;
  state()
    ->set('system.cron_last', $cron_last);
  config('system.cron')
    ->set('threshold.autorun', $cron_safe_threshold)
    ->save();
  $this
    ->drupalGet('');
  $this
    ->assertTrue($cron_last == state()
    ->get('system.cron_last'), 'Cron does not run when the cron threshold is not passed.');

  // Test if cron runs when the cron threshold was passed.
  $cron_last = time() - 200;
  state()
    ->set('system.cron_last', $cron_last);
  $this
    ->drupalGet('');
  sleep(1);
  $this
    ->assertTrue($cron_last < state()
    ->get('system.cron_last'), 'Cron runs when the cron threshold is passed.');

  // Disable the cron threshold through the interface.
  $admin_user = $this
    ->drupalCreateUser(array(
    'administer site configuration',
  ));
  $this
    ->drupalLogin($admin_user);
  $this
    ->drupalPost('admin/config/system/cron', array(
    'cron_safe_threshold' => 0,
  ), t('Save configuration'));
  $this
    ->assertText(t('The configuration options have been saved.'));
  $this
    ->drupalLogout();

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