EntityFieldDefaultValueTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Drupal\KernelTests\Core\Entity;
  3. use Drupal\Component\Uuid\Uuid;
  4. use Drupal\Component\Render\FormattableMarkup;
  5. /**
  6. * Tests default values for entity fields.
  7. *
  8. * @group Entity
  9. */
  10. class EntityFieldDefaultValueTest extends EntityKernelTestBase {
  11. /**
  12. * The UUID object to be used for generating UUIDs.
  13. *
  14. * @var \Drupal\Component\Uuid\UuidInterface
  15. */
  16. protected $uuid;
  17. protected function setUp() {
  18. parent::setUp();
  19. // Initiate the generator object.
  20. $this->uuid = $this->container->get('uuid');
  21. }
  22. /**
  23. * Tests default values on entities and fields.
  24. */
  25. public function testDefaultValues() {
  26. // All entity variations have to have the same results.
  27. foreach (entity_test_entity_types() as $entity_type) {
  28. $this->assertDefaultValues($entity_type);
  29. }
  30. }
  31. /**
  32. * Executes a test set for a defined entity type.
  33. *
  34. * @param string $entity_type_id
  35. * The entity type to run the tests with.
  36. */
  37. protected function assertDefaultValues($entity_type_id) {
  38. $entity = $this->container->get('entity_type.manager')
  39. ->getStorage($entity_type_id)
  40. ->create();
  41. $definition = $this->entityTypeManager->getDefinition($entity_type_id);
  42. $langcode_key = $definition->getKey('langcode');
  43. $this->assertEqual($entity->{$langcode_key}->value, 'en', new FormattableMarkup('%entity_type: Default language', ['%entity_type' => $entity_type_id]));
  44. $this->assertTrue(Uuid::isValid($entity->uuid->value), new FormattableMarkup('%entity_type: Default UUID', ['%entity_type' => $entity_type_id]));
  45. $this->assertEqual($entity->name->getValue(), [], 'Field has one empty value by default.');
  46. }
  47. /**
  48. * Tests custom default value callbacks.
  49. */
  50. public function testDefaultValueCallback() {
  51. $entity = $this->entityTypeManager->getStorage('entity_test_default_value')->create();
  52. // The description field has a default value callback for testing, see
  53. // entity_test_field_default_value().
  54. $string = 'description_' . $entity->language()->getId();
  55. $expected = [
  56. [
  57. 'shape' => "shape:0:$string",
  58. 'color' => "color:0:$string",
  59. ],
  60. [
  61. 'shape' => "shape:1:$string",
  62. 'color' => "color:1:$string",
  63. ],
  64. ];
  65. $this->assertEqual($entity->description->getValue(), $expected);
  66. }
  67. }