You are here

public function EndOfTransactionQueriesTest::testEntitySaveRollback in Drupal 10

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Cache/EndOfTransactionQueriesTest.php \Drupal\KernelTests\Core\Cache\EndOfTransactionQueriesTest::testEntitySaveRollback()
  2. 9 core/tests/Drupal/KernelTests/Core/Cache/EndOfTransactionQueriesTest.php \Drupal\KernelTests\Core\Cache\EndOfTransactionQueriesTest::testEntitySaveRollback()

File

core/tests/Drupal/KernelTests/Core/Cache/EndOfTransactionQueriesTest.php, line 108

Class

EndOfTransactionQueriesTest
Tests that cache tag invalidation queries are delayed to the end of transactions.

Namespace

Drupal\KernelTests\Core\Cache

Code

public function testEntitySaveRollback() {
  \Drupal::cache()
    ->set('test_cache_pretransaction_entity_test_list', 'something', Cache::PERMANENT, [
    'entity_test_list',
  ]);
  \Drupal::cache()
    ->set('test_cache_pretransaction_user_list', 'something', Cache::PERMANENT, [
    'user_list',
  ]);
  \Drupal::state()
    ->set('delay_cache_tags_invalidation_exception', TRUE);
  try {
    EntityTest::create([
      'name' => $this
        ->randomString(),
    ])
      ->save();
    $this
      ->fail('Exception not thrown');
  } catch (\Exception $e) {
    $this
      ->assertEquals('Abort entity save to trigger transaction rollback.', $e
      ->getMessage());
  }

  // The cache has not been invalidated.
  $this
    ->assertNotEmpty(\Drupal::cache()
    ->get('test_cache_pretransaction_entity_test_list'));
  $this
    ->assertNotEmpty(\Drupal::cache()
    ->get('test_cache_pretransaction_user_list'));

  // Save a user, that should invalidate the cache tagged with user_list but
  // not the one with entity_test_list.
  User::create([
    'name' => 'johndoe',
    'status' => 1,
  ])
    ->save();
  $this
    ->assertNotEmpty(\Drupal::cache()
    ->get('test_cache_pretransaction_entity_test_list'));
  $this
    ->assertFalse(\Drupal::cache()
    ->get('test_cache_pretransaction_user_list'));
}