function CronRunTest::testAutomatedCron

Same name and namespace in other branches
  1. 9 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()
  3. 11.x 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->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.');
}

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