You are here

public function FormCacheTest::testCacheToken in Drupal 8

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Form/FormCacheTest.php \Drupal\KernelTests\Core\Form\FormCacheTest::testCacheToken()
  2. 10 core/tests/Drupal/KernelTests/Core/Form/FormCacheTest.php \Drupal\KernelTests\Core\Form\FormCacheTest::testCacheToken()

Tests the form cache with a logged-in user.

File

core/tests/Drupal/KernelTests/Core/Form/FormCacheTest.php, line 56

Class

FormCacheTest
Tests \Drupal::formBuilder()->setCache() and \Drupal::formBuilder()->getCache().

Namespace

Drupal\KernelTests\Core\Form

Code

public function testCacheToken() {
  \Drupal::currentUser()
    ->setAccount(new UserSession([
    'uid' => 1,
  ]));
  \Drupal::formBuilder()
    ->setCache($this->formBuildId, $this->form, $this->formState);
  $cached_form_state = new FormState();
  $cached_form = \Drupal::formBuilder()
    ->getCache($this->formBuildId, $cached_form_state);
  $this
    ->assertEqual($this->form['#property'], $cached_form['#property']);
  $this
    ->assertNotEmpty($cached_form['#cache_token'], 'Form has a cache token');
  $this
    ->assertEqual($this->formState
    ->get('example'), $cached_form_state
    ->get('example'));

  // Test that the form cache isn't loaded when the session/token has changed.
  // Change the private key. (We cannot change the session ID because this
  // will break the parent site test runner batch.)
  \Drupal::state()
    ->set('system.private_key', 'invalid');
  $cached_form_state = new FormState();
  $cached_form = \Drupal::formBuilder()
    ->getCache($this->formBuildId, $cached_form_state);
  $this
    ->assertNull($cached_form, 'No form returned from cache');
  $cached_form_state_example = $cached_form_state
    ->get('example');
  $this
    ->assertEmpty($cached_form_state_example);

  // Test that loading the cache with a different form_id fails.
  $wrong_form_build_id = $this
    ->randomMachineName(9);
  $cached_form_state = new FormState();
  $this
    ->assertNull(\Drupal::formBuilder()
    ->getCache($wrong_form_build_id, $cached_form_state), 'No form returned from cache');
  $cached_form_state_example = $cached_form_state
    ->get('example');
  $this
    ->assertEmpty($cached_form_state_example, 'Cached form state was not loaded');
}