EntityUnitTest.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. <?php
  2. namespace Drupal\Tests\Core\Entity;
  3. use Drupal\Core\Access\AccessResult;
  4. use Drupal\Core\Cache\Cache;
  5. use Drupal\Core\DependencyInjection\ContainerBuilder;
  6. use Drupal\Core\Entity\EntityStorageInterface;
  7. use Drupal\Core\Entity\EntityTypeManagerInterface;
  8. use Drupal\Core\Entity\EntityTypeRepositoryInterface;
  9. use Drupal\Core\Language\Language;
  10. use Drupal\entity_test\Entity\EntityTestMul;
  11. use Drupal\Tests\Traits\ExpectDeprecationTrait;
  12. use Drupal\Tests\UnitTestCase;
  13. /**
  14. * @coversDefaultClass \Drupal\Core\Entity\Entity
  15. * @group Entity
  16. * @group Access
  17. */
  18. class EntityUnitTest extends UnitTestCase {
  19. use ExpectDeprecationTrait;
  20. /**
  21. * The entity under test.
  22. *
  23. * @var \Drupal\Core\Entity\Entity|\PHPUnit\Framework\MockObject\MockObject
  24. */
  25. protected $entity;
  26. /**
  27. * The entity type used for testing.
  28. *
  29. * @var \Drupal\Core\Entity\EntityTypeInterface|\PHPUnit\Framework\MockObject\MockObject
  30. */
  31. protected $entityType;
  32. /**
  33. * The entity type manager used for testing.
  34. *
  35. * @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit\Framework\MockObject\MockObject
  36. */
  37. protected $entityTypeManager;
  38. /**
  39. * The ID of the type of the entity under test.
  40. *
  41. * @var string
  42. */
  43. protected $entityTypeId;
  44. /**
  45. * The route provider used for testing.
  46. *
  47. * @var \Drupal\Core\Routing\RouteProvider|\PHPUnit\Framework\MockObject\MockObject
  48. */
  49. protected $routeProvider;
  50. /**
  51. * The UUID generator used for testing.
  52. *
  53. * @var \Drupal\Component\Uuid\UuidInterface|\PHPUnit\Framework\MockObject\MockObject
  54. */
  55. protected $uuid;
  56. /**
  57. * The language manager.
  58. *
  59. * @var \Drupal\Core\Language\LanguageManagerInterface|\PHPUnit\Framework\MockObject\MockObject
  60. */
  61. protected $languageManager;
  62. /**
  63. * The mocked cache tags invalidator.
  64. *
  65. * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface|\PHPUnit\Framework\MockObject\MockObject
  66. */
  67. protected $cacheTagsInvalidator;
  68. /**
  69. * The entity values.
  70. *
  71. * @var array
  72. */
  73. protected $values;
  74. /**
  75. * {@inheritdoc}
  76. */
  77. protected function setUp() {
  78. $this->values = [
  79. 'id' => 1,
  80. 'langcode' => 'en',
  81. 'uuid' => '3bb9ee60-bea5-4622-b89b-a63319d10b3a',
  82. ];
  83. $this->entityTypeId = $this->randomMachineName();
  84. $this->entityType = $this->createMock('\Drupal\Core\Entity\EntityTypeInterface');
  85. $this->entityType->expects($this->any())
  86. ->method('getListCacheTags')
  87. ->willReturn([$this->entityTypeId . '_list']);
  88. $this->entityTypeManager = $this->getMockForAbstractClass(EntityTypeManagerInterface::class);
  89. $this->entityTypeManager->expects($this->any())
  90. ->method('getDefinition')
  91. ->with($this->entityTypeId)
  92. ->will($this->returnValue($this->entityType));
  93. $this->uuid = $this->createMock('\Drupal\Component\Uuid\UuidInterface');
  94. $this->languageManager = $this->createMock('\Drupal\Core\Language\LanguageManagerInterface');
  95. $this->languageManager->expects($this->any())
  96. ->method('getLanguage')
  97. ->with('en')
  98. ->will($this->returnValue(new Language(['id' => 'en'])));
  99. $this->cacheTagsInvalidator = $this->createMock('Drupal\Core\Cache\CacheTagsInvalidator');
  100. $container = new ContainerBuilder();
  101. // Ensure that Entity doesn't use the deprecated entity.manager service.
  102. $container->set('entity.manager', NULL);
  103. $container->set('entity_type.manager', $this->entityTypeManager);
  104. $container->set('uuid', $this->uuid);
  105. $container->set('language_manager', $this->languageManager);
  106. $container->set('cache_tags.invalidator', $this->cacheTagsInvalidator);
  107. \Drupal::setContainer($container);
  108. $this->entity = $this->getMockForAbstractClass('\Drupal\Core\Entity\EntityBase', [$this->values, $this->entityTypeId]);
  109. }
  110. /**
  111. * @covers ::id
  112. */
  113. public function testId() {
  114. $this->assertSame($this->values['id'], $this->entity->id());
  115. }
  116. /**
  117. * @covers ::uuid
  118. */
  119. public function testUuid() {
  120. $this->assertSame($this->values['uuid'], $this->entity->uuid());
  121. }
  122. /**
  123. * @covers ::isNew
  124. * @covers ::enforceIsNew
  125. */
  126. public function testIsNew() {
  127. // We provided an ID, so the entity is not new.
  128. $this->assertFalse($this->entity->isNew());
  129. // Force it to be new.
  130. $this->assertSame($this->entity, $this->entity->enforceIsNew());
  131. $this->assertTrue($this->entity->isNew());
  132. }
  133. /**
  134. * @covers ::getEntityType
  135. */
  136. public function testGetEntityType() {
  137. $this->assertSame($this->entityType, $this->entity->getEntityType());
  138. }
  139. /**
  140. * @covers ::bundle
  141. */
  142. public function testBundle() {
  143. $this->assertSame($this->entityTypeId, $this->entity->bundle());
  144. }
  145. /**
  146. * @covers ::label
  147. * @group legacy
  148. */
  149. public function testLabel() {
  150. $this->addExpectedDeprecationMessage('Entity type ' . $this->entityTypeId . ' defines a label callback. Support for that is deprecated in drupal:8.0.0 and will be removed in drupal:9.0.0. Override the EntityInterface::label() method instead. See https://www.drupal.org/node/3050794');
  151. // Make a mock with one method that we use as the entity's uri_callback. We
  152. // check that it is called, and that the entity's label is the callback's
  153. // return value.
  154. $callback_label = $this->randomMachineName();
  155. $property_label = $this->randomMachineName();
  156. $callback_container = $this->createMock(get_class());
  157. $callback_container->expects($this->once())
  158. ->method(__FUNCTION__)
  159. ->will($this->returnValue($callback_label));
  160. $this->entityType->expects($this->at(0))
  161. ->method('get')
  162. ->with('label_callback')
  163. ->will($this->returnValue([$callback_container, __FUNCTION__]));
  164. $this->entityType->expects($this->at(2))
  165. ->method('getKey')
  166. ->with('label')
  167. ->will($this->returnValue('label'));
  168. // Set a dummy property on the entity under test to test that the label can
  169. // be returned form a property if there is no callback.
  170. $this->entityTypeManager->expects($this->at(1))
  171. ->method('getDefinition')
  172. ->with($this->entityTypeId)
  173. ->will($this->returnValue([
  174. 'entity_keys' => [
  175. 'label' => 'label',
  176. ],
  177. ]));
  178. $this->entity->label = $property_label;
  179. $this->assertSame($callback_label, $this->entity->label());
  180. $this->assertSame($property_label, $this->entity->label());
  181. }
  182. /**
  183. * @covers ::access
  184. */
  185. public function testAccess() {
  186. $access = $this->createMock('\Drupal\Core\Entity\EntityAccessControlHandlerInterface');
  187. $operation = $this->randomMachineName();
  188. $access->expects($this->at(0))
  189. ->method('access')
  190. ->with($this->entity, $operation)
  191. ->will($this->returnValue(AccessResult::allowed()));
  192. $access->expects($this->at(1))
  193. ->method('createAccess')
  194. ->will($this->returnValue(AccessResult::allowed()));
  195. $this->entityTypeManager->expects($this->exactly(2))
  196. ->method('getAccessControlHandler')
  197. ->will($this->returnValue($access));
  198. $this->assertEquals(AccessResult::allowed(), $this->entity->access($operation));
  199. $this->assertEquals(AccessResult::allowed(), $this->entity->access('create'));
  200. }
  201. /**
  202. * @covers ::language
  203. */
  204. public function testLanguage() {
  205. $this->entityType->expects($this->any())
  206. ->method('getKey')
  207. ->will($this->returnValueMap([
  208. ['langcode', 'langcode'],
  209. ]));
  210. $this->assertSame('en', $this->entity->language()->getId());
  211. }
  212. /**
  213. * Setup for the tests of the ::load() method.
  214. */
  215. public function setupTestLoad() {
  216. // Base our mocked entity on a real entity class so we can test if calling
  217. // Entity::load() on the base class will bubble up to an actual entity.
  218. $this->entityTypeId = 'entity_test_mul';
  219. $methods = get_class_methods(EntityTestMul::class);
  220. unset($methods[array_search('load', $methods)]);
  221. unset($methods[array_search('loadMultiple', $methods)]);
  222. unset($methods[array_search('create', $methods)]);
  223. $this->entity = $this->getMockBuilder(EntityTestMul::class)
  224. ->disableOriginalConstructor()
  225. ->setMethods($methods)
  226. ->getMock();
  227. }
  228. /**
  229. * @covers ::load
  230. *
  231. * Tests Entity::load() when called statically on a subclass of Entity.
  232. */
  233. public function testLoad() {
  234. $this->setupTestLoad();
  235. $class_name = get_class($this->entity);
  236. $entity_type_repository = $this->getMockForAbstractClass(EntityTypeRepositoryInterface::class);
  237. $entity_type_repository->expects($this->once())
  238. ->method('getEntityTypeFromClass')
  239. ->with($class_name)
  240. ->willReturn($this->entityTypeId);
  241. $storage = $this->createMock(EntityStorageInterface::class);
  242. $storage->expects($this->once())
  243. ->method('load')
  244. ->with(1)
  245. ->will($this->returnValue($this->entity));
  246. $this->entityTypeManager->expects($this->once())
  247. ->method('getStorage')
  248. ->with($this->entityTypeId)
  249. ->will($this->returnValue($storage));
  250. \Drupal::getContainer()->set('entity_type.repository', $entity_type_repository);
  251. // Call Entity::load statically and check that it returns the mock entity.
  252. $this->assertSame($this->entity, $class_name::load(1));
  253. }
  254. /**
  255. * @covers ::loadMultiple
  256. *
  257. * Tests Entity::loadMultiple() when called statically on a subclass of
  258. * Entity.
  259. */
  260. public function testLoadMultiple() {
  261. $this->setupTestLoad();
  262. $class_name = get_class($this->entity);
  263. $entity_type_repository = $this->getMockForAbstractClass(EntityTypeRepositoryInterface::class);
  264. $entity_type_repository->expects($this->once())
  265. ->method('getEntityTypeFromClass')
  266. ->with($class_name)
  267. ->willReturn($this->entityTypeId);
  268. $storage = $this->createMock(EntityStorageInterface::class);
  269. $storage->expects($this->once())
  270. ->method('loadMultiple')
  271. ->with([1])
  272. ->will($this->returnValue([1 => $this->entity]));
  273. $this->entityTypeManager->expects($this->once())
  274. ->method('getStorage')
  275. ->with($this->entityTypeId)
  276. ->will($this->returnValue($storage));
  277. \Drupal::getContainer()->set('entity_type.repository', $entity_type_repository);
  278. // Call Entity::loadMultiple statically and check that it returns the mock
  279. // entity.
  280. $this->assertSame([1 => $this->entity], $class_name::loadMultiple([1]));
  281. }
  282. /**
  283. * @covers ::create
  284. */
  285. public function testCreate() {
  286. $this->setupTestLoad();
  287. $class_name = get_class($this->entity);
  288. $entity_type_repository = $this->getMockForAbstractClass(EntityTypeRepositoryInterface::class);
  289. $entity_type_repository->expects($this->once())
  290. ->method('getEntityTypeFromClass')
  291. ->with($class_name)
  292. ->willReturn($this->entityTypeId);
  293. $storage = $this->createMock(EntityStorageInterface::class);
  294. $storage->expects($this->once())
  295. ->method('create')
  296. ->with([])
  297. ->will($this->returnValue($this->entity));
  298. $this->entityTypeManager->expects($this->once())
  299. ->method('getStorage')
  300. ->with($this->entityTypeId)
  301. ->will($this->returnValue($storage));
  302. \Drupal::getContainer()->set('entity_type.repository', $entity_type_repository);
  303. // Call Entity::create() statically and check that it returns the mock
  304. // entity.
  305. $this->assertSame($this->entity, $class_name::create([]));
  306. }
  307. /**
  308. * @covers ::save
  309. */
  310. public function testSave() {
  311. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  312. $storage->expects($this->once())
  313. ->method('save')
  314. ->with($this->entity);
  315. $this->entityTypeManager->expects($this->once())
  316. ->method('getStorage')
  317. ->with($this->entityTypeId)
  318. ->will($this->returnValue($storage));
  319. $this->entity->save();
  320. }
  321. /**
  322. * @covers ::delete
  323. */
  324. public function testDelete() {
  325. $this->entity->id = $this->randomMachineName();
  326. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  327. // Testing the argument of the delete() method consumes too much memory.
  328. $storage->expects($this->once())
  329. ->method('delete');
  330. $this->entityTypeManager->expects($this->once())
  331. ->method('getStorage')
  332. ->with($this->entityTypeId)
  333. ->will($this->returnValue($storage));
  334. $this->entity->delete();
  335. }
  336. /**
  337. * @covers ::getEntityTypeId
  338. */
  339. public function testGetEntityTypeId() {
  340. $this->assertSame($this->entityTypeId, $this->entity->getEntityTypeId());
  341. }
  342. /**
  343. * @covers ::preSave
  344. */
  345. public function testPreSave() {
  346. // This method is internal, so check for errors on calling it only.
  347. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  348. // Our mocked entity->preSave() returns NULL, so assert that.
  349. $this->assertNull($this->entity->preSave($storage));
  350. }
  351. /**
  352. * @covers ::postSave
  353. */
  354. public function testPostSave() {
  355. $this->cacheTagsInvalidator->expects($this->at(0))
  356. ->method('invalidateTags')
  357. ->with([
  358. // List cache tag.
  359. $this->entityTypeId . '_list',
  360. ]);
  361. $this->cacheTagsInvalidator->expects($this->at(1))
  362. ->method('invalidateTags')
  363. ->with([
  364. // Own cache tag.
  365. $this->entityTypeId . ':' . $this->values['id'],
  366. // List cache tag.
  367. $this->entityTypeId . '_list',
  368. ]);
  369. // This method is internal, so check for errors on calling it only.
  370. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  371. // A creation should trigger the invalidation of the "list" cache tag.
  372. $this->entity->postSave($storage, FALSE);
  373. // An update should trigger the invalidation of both the "list" and the
  374. // "own" cache tags.
  375. $this->entity->postSave($storage, TRUE);
  376. }
  377. /**
  378. * @covers ::postSave
  379. */
  380. public function testPostSaveBundle() {
  381. $this->cacheTagsInvalidator->expects($this->at(0))
  382. ->method('invalidateTags')
  383. ->with([
  384. // List cache tag.
  385. $this->entityTypeId . '_list',
  386. $this->entityTypeId . '_list:' . $this->entity->bundle(),
  387. ]);
  388. $this->cacheTagsInvalidator->expects($this->at(1))
  389. ->method('invalidateTags')
  390. ->with([
  391. // Own cache tag.
  392. $this->entityTypeId . ':' . $this->values['id'],
  393. // List cache tag.
  394. $this->entityTypeId . '_list',
  395. $this->entityTypeId . '_list:' . $this->entity->bundle(),
  396. ]);
  397. $this->entityType->expects($this->atLeastOnce())
  398. ->method('hasKey')
  399. ->with('bundle')
  400. ->willReturn(TRUE);
  401. // This method is internal, so check for errors on calling it only.
  402. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  403. // A creation should trigger the invalidation of the global list cache tag
  404. // and the one for the bundle.
  405. $this->entity->postSave($storage, FALSE);
  406. // An update should trigger the invalidation of the "list", bundle list and
  407. // the "own" cache tags.
  408. $this->entity->postSave($storage, TRUE);
  409. }
  410. /**
  411. * @covers ::preCreate
  412. */
  413. public function testPreCreate() {
  414. // This method is internal, so check for errors on calling it only.
  415. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  416. $values = [];
  417. // Our mocked entity->preCreate() returns NULL, so assert that.
  418. $this->assertNull($this->entity->preCreate($storage, $values));
  419. }
  420. /**
  421. * @covers ::postCreate
  422. */
  423. public function testPostCreate() {
  424. // This method is internal, so check for errors on calling it only.
  425. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  426. // Our mocked entity->postCreate() returns NULL, so assert that.
  427. $this->assertNull($this->entity->postCreate($storage));
  428. }
  429. /**
  430. * @covers ::preDelete
  431. */
  432. public function testPreDelete() {
  433. // This method is internal, so check for errors on calling it only.
  434. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  435. // Our mocked entity->preDelete() returns NULL, so assert that.
  436. $this->assertNull($this->entity->preDelete($storage, [$this->entity]));
  437. }
  438. /**
  439. * @covers ::postDelete
  440. */
  441. public function testPostDelete() {
  442. $this->cacheTagsInvalidator->expects($this->once())
  443. ->method('invalidateTags')
  444. ->with([
  445. $this->entityTypeId . ':' . $this->values['id'],
  446. $this->entityTypeId . '_list',
  447. ]);
  448. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  449. $storage->expects($this->once())
  450. ->method('getEntityType')
  451. ->willReturn($this->entityType);
  452. $entities = [$this->values['id'] => $this->entity];
  453. $this->entity->postDelete($storage, $entities);
  454. }
  455. /**
  456. * @covers ::postDelete
  457. */
  458. public function testPostDeleteBundle() {
  459. $this->cacheTagsInvalidator->expects($this->once())
  460. ->method('invalidateTags')
  461. ->with([
  462. $this->entityTypeId . ':' . $this->values['id'],
  463. $this->entityTypeId . '_list',
  464. $this->entityTypeId . '_list:' . $this->entity->bundle(),
  465. ]);
  466. $this->entityType->expects($this->atLeastOnce())
  467. ->method('hasKey')
  468. ->with('bundle')
  469. ->willReturn(TRUE);
  470. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  471. $storage->expects($this->once())
  472. ->method('getEntityType')
  473. ->willReturn($this->entityType);
  474. $entities = [$this->values['id'] => $this->entity];
  475. $this->entity->postDelete($storage, $entities);
  476. }
  477. /**
  478. * @covers ::postLoad
  479. */
  480. public function testPostLoad() {
  481. // This method is internal, so check for errors on calling it only.
  482. $storage = $this->createMock('\Drupal\Core\Entity\EntityStorageInterface');
  483. $entities = [$this->entity];
  484. // Our mocked entity->postLoad() returns NULL, so assert that.
  485. $this->assertNull($this->entity->postLoad($storage, $entities));
  486. }
  487. /**
  488. * @covers ::referencedEntities
  489. */
  490. public function testReferencedEntities() {
  491. $this->assertSame([], $this->entity->referencedEntities());
  492. }
  493. /**
  494. * @covers ::getCacheTags
  495. * @covers ::getCacheTagsToInvalidate
  496. * @covers ::addCacheTags
  497. */
  498. public function testCacheTags() {
  499. // Ensure that both methods return the same by default.
  500. $this->assertEquals([$this->entityTypeId . ':' . 1], $this->entity->getCacheTags());
  501. $this->assertEquals([$this->entityTypeId . ':' . 1], $this->entity->getCacheTagsToInvalidate());
  502. // Add an additional cache tag and make sure only getCacheTags() returns
  503. // that.
  504. $this->entity->addCacheTags(['additional_cache_tag']);
  505. // EntityTypeId is random so it can shift order. We need to duplicate the
  506. // sort from \Drupal\Core\Cache\Cache::mergeTags().
  507. $tags = ['additional_cache_tag', $this->entityTypeId . ':' . 1];
  508. sort($tags);
  509. $this->assertEquals($tags, $this->entity->getCacheTags());
  510. $this->assertEquals([$this->entityTypeId . ':' . 1], $this->entity->getCacheTagsToInvalidate());
  511. }
  512. /**
  513. * @covers ::getCacheContexts
  514. * @covers ::addCacheContexts
  515. */
  516. public function testCacheContexts() {
  517. $cache_contexts_manager = $this->getMockBuilder('Drupal\Core\Cache\Context\CacheContextsManager')
  518. ->disableOriginalConstructor()
  519. ->getMock();
  520. $cache_contexts_manager->method('assertValidTokens')->willReturn(TRUE);
  521. $container = new ContainerBuilder();
  522. $container->set('cache_contexts_manager', $cache_contexts_manager);
  523. \Drupal::setContainer($container);
  524. // There are no cache contexts by default.
  525. $this->assertEquals([], $this->entity->getCacheContexts());
  526. // Add an additional cache context.
  527. $this->entity->addCacheContexts(['user']);
  528. $this->assertEquals(['user'], $this->entity->getCacheContexts());
  529. }
  530. /**
  531. * @covers ::getCacheMaxAge
  532. * @covers ::mergeCacheMaxAge
  533. */
  534. public function testCacheMaxAge() {
  535. // Cache max age is permanent by default.
  536. $this->assertEquals(Cache::PERMANENT, $this->entity->getCacheMaxAge());
  537. // Set two cache max ages, the lower value is the one that needs to be
  538. // returned.
  539. $this->entity->mergeCacheMaxAge(600);
  540. $this->entity->mergeCacheMaxAge(1800);
  541. $this->assertEquals(600, $this->entity->getCacheMaxAge());
  542. }
  543. }