EntityReferenceItemTest.php 23.3 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\field\Kernel\EntityReference;
4

5
use Drupal\comment\Entity\Comment;
6
use Drupal\comment\Entity\CommentType;
7
use Drupal\Component\Render\FormattableMarkup;
8 9
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldItemInterface;
10
use Drupal\Core\Field\FieldStorageDefinitionInterface;
11
use Drupal\Core\StringTranslation\TranslatableMarkup;
12
use Drupal\Core\Language\LanguageInterface;
13 14
use Drupal\entity_test\Entity\EntityTest;
use Drupal\entity_test\Entity\EntityTestStringId;
15 16
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
17
use Drupal\node\Entity\NodeType;
18
use Drupal\node\NodeInterface;
19
use Drupal\taxonomy\TermInterface;
20
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
21 22
use Drupal\file\Entity\File;
use Drupal\node\Entity\Node;
23
use Drupal\taxonomy\Entity\Term;
24
use Drupal\taxonomy\Entity\Vocabulary;
25
use Drupal\user\Entity\User;
26
use Drupal\Tests\field\Traits\EntityReferenceTestTrait;
27 28 29

/**
 * Tests the new entity API for the entity reference field type.
30 31
 *
 * @group entity_reference
32
 */
33
class EntityReferenceItemTest extends FieldKernelTestBase {
34

35 36
  use EntityReferenceTestTrait;

37
  /**
38
   * Modules to install.
39 40 41
   *
   * @var array
   */
42
  protected static $modules = ['node', 'comment', 'file', 'taxonomy', 'text', 'filter', 'views', 'field'];
43

44 45 46 47 48 49 50 51 52 53 54 55 56 57
  /**
   * The taxonomy vocabulary to test with.
   *
   * @var \Drupal\taxonomy\VocabularyInterface
   */
  protected $vocabulary;

  /**
   * The taxonomy term to test with.
   *
   * @var \Drupal\taxonomy\TermInterface
   */
  protected $term;

58 59 60 61 62 63 64
  /**
   * The test entity with a string ID.
   *
   * @var \Drupal\entity_test\Entity\EntityTestStringId
   */
  protected $entityStringId;

65 66 67
  /**
   * Sets up the test.
   */
68
  protected function setUp(): void {
69 70
    parent::setUp();

71
    $this->installEntitySchema('entity_test_string_id');
72
    $this->installEntitySchema('taxonomy_term');
73 74 75 76 77
    $this->installEntitySchema('node');
    $this->installEntitySchema('comment');
    $this->installEntitySchema('file');

    $this->installSchema('comment', ['comment_entity_statistics']);
78
    $this->installSchema('node', ['node_access']);
79

80
    $this->vocabulary = Vocabulary::create([
81
      'name' => $this->randomMachineName(),
82
      'vid' => mb_strtolower($this->randomMachineName()),
83
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
84
    ]);
85
    $this->vocabulary->save();
86

87
    $this->term = Term::create([
88
      'name' => $this->randomMachineName(),
89
      'vid' => $this->vocabulary->id(),
90
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
91
    ]);
92 93
    $this->term->save();

94 95 96 97 98 99 100 101
    NodeType::create([
      'type' => $this->randomMachineName(),
    ])->save();
    CommentType::create([
      'id' => $this->randomMachineName(),
      'target_entity_type_id' => 'node',
    ])->save();

102 103 104 105 106
    $this->entityStringId = EntityTestStringId::create([
      'id' => $this->randomMachineName(),
    ]);
    $this->entityStringId->save();

107
    // Use the util to create an instance.
108
    $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_taxonomy_term', 'Test content entity reference', 'taxonomy_term');
109
    $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_entity_test_string_id', 'Test content entity reference with string ID', 'entity_test_string_id');
110
    $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_taxonomy_vocabulary', 'Test config entity reference', 'taxonomy_vocabulary');
111
    $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_node', 'Test node entity reference', 'node', 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
112 113 114
    $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_user', 'Test user entity reference', 'user');
    $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_comment', 'Test comment entity reference', 'comment');
    $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_file', 'Test file entity reference', 'file');
115
    $this->createEntityReferenceField('entity_test_string_id', 'entity_test_string_id', 'field_test_entity_test', 'Test content entity reference with string ID', 'entity_test');
116 117 118
  }

  /**
119
   * Tests the entity reference field type for referencing content entities.
120
   */
121
  public function testContentEntityReferenceItem() {
122
    $tid = $this->term->id();
123 124

    // Just being able to create the entity like this verifies a lot of code.
125
    $entity = EntityTest::create();
126
    $entity->field_test_taxonomy_term->target_id = $tid;
127
    $entity->name->value = $this->randomMachineName();
128 129
    $entity->save();

130
    $entity = EntityTest::load($entity->id());
131 132
    $this->assertInstanceOf(FieldItemListInterface::class, $entity->field_test_taxonomy_term, 'Field implements interface.');
    $this->assertInstanceOf(FieldItemInterface::class, $entity->field_test_taxonomy_term[0], 'Field item implements interface.');
133
    $this->assertEqual($entity->field_test_taxonomy_term->target_id, $tid);
134
    $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $this->term->getName());
135 136
    $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $tid);
    $this->assertEqual($entity->field_test_taxonomy_term->entity->uuid(), $this->term->uuid());
137 138
    // Verify that the label for the target ID property definition is correct.
    $label = $entity->field_test_taxonomy_term->getFieldDefinition()->getFieldStorageDefinition()->getPropertyDefinition('target_id')->getLabel();
139
    $this->assertInstanceOf(TranslatableMarkup::class, $label);
140
    $this->assertEqual($label->render(), 'Taxonomy term ID');
141 142

    // Change the name of the term via the reference.
143
    $new_name = $this->randomMachineName();
144
    $entity->field_test_taxonomy_term->entity->setName($new_name);
145
    $entity->field_test_taxonomy_term->entity->save();
146
    // Verify it is the correct name.
147
    $term = Term::load($tid);
148
    $this->assertEqual($term->getName(), $new_name);
149

150
    // Make sure the computed term reflects updates to the term id.
151
    $term2 = Term::create([
152
      'name' => $this->randomMachineName(),
153
      'vid' => $this->term->bundle(),
154
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
155
    ]);
156
    $term2->save();
157

158 159 160 161 162 163
    // Test all the possible ways of assigning a value.
    $entity->field_test_taxonomy_term->target_id = $term->id();
    $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id());
    $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term->getName());

    $entity->field_test_taxonomy_term = [['target_id' => $term2->id()]];
164
    $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term2->id());
165
    $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term2->getName());
166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    // Test value assignment via the computed 'entity' property.
    $entity->field_test_taxonomy_term->entity = $term;
    $this->assertEqual($entity->field_test_taxonomy_term->target_id, $term->id());
    $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term->getName());

    $entity->field_test_taxonomy_term = [['entity' => $term2]];
    $this->assertEqual($entity->field_test_taxonomy_term->target_id, $term2->id());
    $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term2->getName());

    // Test assigning an invalid item throws an exception.
    try {
      $entity->field_test_taxonomy_term = ['target_id' => 'invalid', 'entity' => $term2];
      $this->fail('Assigning an invalid item throws an exception.');
    }
    catch (\InvalidArgumentException $e) {
      $this->pass('Assigning an invalid item throws an exception.');
    }

185 186 187
    // Delete terms so we have nothing to reference and try again
    $term->delete();
    $term2->delete();
188
    $entity = EntityTest::create(['name' => $this->randomMachineName()]);
189
    $entity->save();
190 191

    // Test the generateSampleValue() method.
192
    $entity = EntityTest::create();
193 194 195
    $entity->field_test_taxonomy_term->generateSampleItems();
    $entity->field_test_taxonomy_vocabulary->generateSampleItems();
    $this->entityValidateAndSave($entity);
196 197 198 199 200 201 202 203 204

    // Tests that setting an integer target ID together with an entity object
    // succeeds and does not cause any exceptions. There is no assertion here,
    // as the assignment should not throw any exceptions and if it does the
    // test will fail.
    // @see \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::setValue().
    $user = User::create(['name' => $this->randomString()]);
    $user->save();
    $entity = EntityTest::create(['user_id' => ['target_id' => (int) $user->id(), 'entity' => $user]]);
205
  }
206

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  /**
   * Tests the ::generateSampleValue() method.
   */
  public function testGenerateSampleValue() {
    $entity = EntityTest::create();

    // Test while a term exists.
    $entity->field_test_taxonomy_term->generateSampleItems();
    $this->assertInstanceOf(TermInterface::class, $entity->field_test_taxonomy_term->entity);
    $this->entityValidateAndSave($entity);

    // Delete the term and test again.
    $this->term->delete();
    $entity->field_test_taxonomy_term->generateSampleItems();
    $this->assertInstanceOf(TermInterface::class, $entity->field_test_taxonomy_term->entity);
    $this->entityValidateAndSave($entity);
  }

225 226 227 228 229 230 231 232 233 234 235 236 237
  /**
   * Tests the ::generateSampleValue() method when it has a circular reference.
   */
  public function testGenerateSampleValueCircularReference() {
    // Delete the existing entity.
    $this->entityStringId->delete();

    $entity_storage = \Drupal::entityTypeManager()->getStorage('entity_test');
    $entity = $entity_storage->createWithSampleValues('entity_test');
    $this->assertInstanceOf(EntityTestStringId::class, $entity->field_test_entity_test_string_id->entity);
    $this->assertInstanceOf(EntityTest::class, $entity->field_test_entity_test_string_id->entity->field_test_entity_test->entity);
  }

238 239 240 241 242 243 244
  /**
   * Tests referencing content entities with string IDs.
   */
  public function testContentEntityReferenceItemWithStringId() {
    $entity = EntityTest::create();
    $entity->field_test_entity_test_string_id->target_id = $this->entityStringId->id();
    $entity->save();
245
    $storage = \Drupal::entityTypeManager()->getStorage('entity_test');
246 247
    $storage->resetCache();
    $this->assertEqual($this->entityStringId->id(), $storage->load($entity->id())->field_test_entity_test_string_id->target_id);
248 249
    // Verify that the label for the target ID property definition is correct.
    $label = $entity->field_test_taxonomy_term->getFieldDefinition()->getFieldStorageDefinition()->getPropertyDefinition('target_id')->getLabel();
250
    $this->assertInstanceOf(TranslatableMarkup::class, $label);
251
    $this->assertEqual($label->render(), 'Taxonomy term ID');
252 253
  }

254
  /**
255
   * Tests the entity reference field type for referencing config entities.
256
   */
257 258 259 260
  public function testConfigEntityReferenceItem() {
    $referenced_entity_id = $this->vocabulary->id();

    // Just being able to create the entity like this verifies a lot of code.
261
    $entity = EntityTest::create();
262
    $entity->field_test_taxonomy_vocabulary->target_id = $referenced_entity_id;
263
    $entity->name->value = $this->randomMachineName();
264 265
    $entity->save();

266
    $entity = EntityTest::load($entity->id());
267 268
    $this->assertInstanceOf(FieldItemListInterface::class, $entity->field_test_taxonomy_vocabulary, 'Field implements interface.');
    $this->assertInstanceOf(FieldItemInterface::class, $entity->field_test_taxonomy_vocabulary[0], 'Field item implements interface.');
269
    $this->assertEqual($entity->field_test_taxonomy_vocabulary->target_id, $referenced_entity_id);
270
    $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $this->vocabulary->label());
271 272 273 274
    $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $referenced_entity_id);
    $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->uuid(), $this->vocabulary->uuid());

    // Change the name of the term via the reference.
275
    $new_name = $this->randomMachineName();
276
    $entity->field_test_taxonomy_vocabulary->entity->set('name', $new_name);
277 278
    $entity->field_test_taxonomy_vocabulary->entity->save();
    // Verify it is the correct name.
279
    $vocabulary = Vocabulary::load($referenced_entity_id);
280
    $this->assertEqual($vocabulary->label(), $new_name);
281 282

    // Make sure the computed term reflects updates to the term id.
283
    $vocabulary2 = $vocabulary = Vocabulary::create([
284
      'name' => $this->randomMachineName(),
285
      'vid' => mb_strtolower($this->randomMachineName()),
286
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
287
    ]);
288 289 290 291
    $vocabulary2->save();

    $entity->field_test_taxonomy_vocabulary->target_id = $vocabulary2->id();
    $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $vocabulary2->id());
292
    $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $vocabulary2->label());
293 294 295 296

    // Delete terms so we have nothing to reference and try again
    $this->vocabulary->delete();
    $vocabulary2->delete();
297
    $entity = EntityTest::create(['name' => $this->randomMachineName()]);
298
    $entity->save();
299
  }
300

301 302 303 304 305
  /**
   * Tests entity auto create.
   */
  public function testEntityAutoCreate() {
    // The term entity is unsaved here.
306
    $term = Term::create([
307 308 309
      'name' => $this->randomMachineName(),
      'vid' => $this->term->bundle(),
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
310
    ]);
311 312 313 314 315 316 317 318 319 320
    $entity = EntityTest::create();
    // Now assign the unsaved term to the field.
    $entity->field_test_taxonomy_term->entity = $term;
    $entity->name->value = $this->randomMachineName();
    // This is equal to storing an entity to tempstore or cache and retrieving
    // it back. An example for this is node preview.
    $entity = serialize($entity);
    $entity = unserialize($entity);
    // And then the entity.
    $entity->save();
321
    $term = \Drupal::service('entity.repository')->loadEntityByUuid($term->getEntityTypeId(), $term->uuid());
322 323 324
    $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id());
  }

325 326 327 328 329
  /**
   * Test saving order sequence doesn't matter.
   */
  public function testEntitySaveOrder() {
    // The term entity is unsaved here.
330
    $term = Term::create([
331 332 333
      'name' => $this->randomMachineName(),
      'vid' => $this->term->bundle(),
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
334
    ]);
335
    $entity = EntityTest::create();
336 337 338
    // Now assign the unsaved term to the field.
    $entity->field_test_taxonomy_term->entity = $term;
    $entity->name->value = $this->randomMachineName();
339 340 341 342 343 344
    // Now get the field value.
    $value = $entity->get('field_test_taxonomy_term');
    $this->assertTrue(empty($value['target_id']));
    $this->assertNull($entity->field_test_taxonomy_term->target_id);
    // And then set it.
    $entity->field_test_taxonomy_term = $value;
345 346 347 348 349 350 351
    // Now save the term.
    $term->save();
    // And then the entity.
    $entity->save();
    $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id());
  }

352 353 354 355
  /**
   * Tests that the 'handler' field setting stores the proper plugin ID.
   */
  public function testSelectionHandlerSettings() {
356
    $field_name = mb_strtolower($this->randomMachineName());
357
    $field_storage = FieldStorageConfig::create([
358 359 360
      'field_name' => $field_name,
      'entity_type' => 'entity_test',
      'type' => 'entity_reference',
361
      'settings' => [
362
        'target_type' => 'entity_test',
363 364
      ],
    ]);
365 366 367
    $field_storage->save();

    // Do not specify any value for the 'handler' setting in order to verify
368
    // that the default handler with the correct derivative is used.
369
    $field = FieldConfig::create([
370 371
      'field_storage' => $field_storage,
      'bundle' => 'entity_test',
372
    ]);
373
    $field->save();
374 375
    $field = FieldConfig::load($field->id());
    $this->assertEqual($field->getSetting('handler'), 'default:entity_test');
376

377 378 379 380
    // Change the target_type in the field storage, and check that the handler
    // was correctly reassigned in the field.
    $field_storage->setSetting('target_type', 'entity_test_rev');
    $field_storage->save();
381
    $field = FieldConfig::load($field->id());
382
    $this->assertEqual($field->getSetting('handler'), 'default:entity_test_rev');
383

384
    // Change the handler to another, non-derivative plugin.
385
    $field->setSetting('handler', 'views');
386 387
    $field->save();
    $field = FieldConfig::load($field->id());
388 389 390 391 392 393 394 395
    $this->assertEqual($field->getSetting('handler'), 'views');

    // Change the target_type in the field storage again, and check that the
    // non-derivative handler was unchanged.
    $field_storage->setSetting('target_type', 'entity_test_rev');
    $field_storage->save();
    $field = FieldConfig::load($field->id());
    $this->assertEqual($field->getSetting('handler'), 'views');
396 397
  }

398
  /**
399
   * Tests ValidReferenceConstraint with newly created and unsaved entities.
400
   */
401
  public function testAutocreateValidation() {
402
    // The term entity is unsaved here.
403
    $term = Term::create([
404 405 406
      'name' => $this->randomMachineName(),
      'vid' => $this->term->bundle(),
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
407
    ]);
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    $entity = EntityTest::create([
      'field_test_taxonomy_term' => [
        'entity' => $term,
        'target_id' => NULL,
      ],
    ]);
    $errors = $entity->validate();
    // Using target_id of NULL is valid with an unsaved entity.
    $this->assertEqual(0, count($errors));
    // Using target_id of NULL is not valid with a saved entity.
    $term->save();
    $entity = EntityTest::create([
      'field_test_taxonomy_term' => [
        'entity' => $term,
        'target_id' => NULL,
      ],
    ]);
    $errors = $entity->validate();
    $this->assertEqual(1, count($errors));
    $this->assertEqual($errors[0]->getMessage(), 'This value should not be null.');
    $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_taxonomy_term.0');
    // This should rectify the issue, favoring the entity over the target_id.
    $entity->save();
    $errors = $entity->validate();
    $this->assertEqual(0, count($errors));
433 434 435 436 437 438

    // Test with an unpublished and unsaved node.
    $title = $this->randomString();
    $node = Node::create([
      'title' => $title,
      'type' => 'node',
439
      'status' => NodeInterface::NOT_PUBLISHED,
440 441 442 443 444 445 446 447 448 449 450 451 452 453
    ]);

    $entity = EntityTest::create([
      'field_test_node' => [
        'entity' => $node,
      ],
    ]);

    $errors = $entity->validate();
    $this->assertEqual(1, count($errors));
    $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $title]));
    $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');

    // Publish the node and try again.
454
    $node->setPublished();
455 456 457
    $errors = $entity->validate();
    $this->assertEqual(0, count($errors));

458 459 460 461 462
    // Test with a mix of valid and invalid nodes.
    $unsaved_unpublished_node_title = $this->randomString();
    $unsaved_unpublished_node = Node::create([
      'title' => $unsaved_unpublished_node_title,
      'type' => 'node',
463
      'status' => NodeInterface::NOT_PUBLISHED,
464 465 466 467 468 469
    ]);

    $saved_unpublished_node_title = $this->randomString();
    $saved_unpublished_node = Node::create([
      'title' => $saved_unpublished_node_title,
      'type' => 'node',
470
      'status' => NodeInterface::NOT_PUBLISHED,
471 472 473 474 475 476 477
    ]);
    $saved_unpublished_node->save();

    $saved_published_node_title = $this->randomString();
    $saved_published_node = Node::create([
      'title' => $saved_published_node_title,
      'type' => 'node',
478
      'status' => NodeInterface::PUBLISHED,
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    ]);
    $saved_published_node->save();

    $entity = EntityTest::create([
      'field_test_node' => [
        [
          'entity' => $unsaved_unpublished_node,
        ],
        [
          'target_id' => $saved_unpublished_node->id(),
        ],
        [
          'target_id' => $saved_published_node->id(),
        ],
      ],
    ]);

    $errors = $entity->validate();
    $this->assertEqual(2, count($errors));
    $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title]));
    $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
    $this->assertEqual($errors[1]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $saved_unpublished_node->id()]));
    $this->assertEqual($errors[1]->getPropertyPath(), 'field_test_node.1.target_id');

    // Publish one of the nodes and try again.
504
    $saved_unpublished_node->setPublished();
505 506 507 508 509 510 511
    $saved_unpublished_node->save();
    $errors = $entity->validate();
    $this->assertEqual(1, count($errors));
    $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title]));
    $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');

    // Publish the last invalid node and try again.
512
    $unsaved_unpublished_node->setPublished();
513 514 515
    $errors = $entity->validate();
    $this->assertEqual(0, count($errors));

516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    // Test with an unpublished and unsaved comment.
    $title = $this->randomString();
    $comment = Comment::create([
      'subject' => $title,
      'comment_type' => 'comment',
      'status' => 0,
    ]);

    $entity = EntityTest::create([
      'field_test_comment' => [
        'entity' => $comment,
      ],
    ]);

    $errors = $entity->validate();
    $this->assertEqual(1, count($errors));
    $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'comment', '%label' => $title]));
    $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_comment.0.entity');

    // Publish the comment and try again.
536
    $comment->setPublished();
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
    $errors = $entity->validate();
    $this->assertEqual(0, count($errors));

    // Test with an inactive and unsaved user.
    $name = $this->randomString();
    $user = User::create([
      'name' => $name,
      'status' => 0,
    ]);

    $entity = EntityTest::create([
      'field_test_user' => [
        'entity' => $user,
      ],
    ]);

    $errors = $entity->validate();
    $this->assertEqual(1, count($errors));
    $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'user', '%label' => $name]));
    $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_user.0.entity');

    // Activate the user and try again.
    $user->activate();
    $errors = $entity->validate();
    $this->assertEqual(0, count($errors));

    // Test with a temporary and unsaved file.
    $filename = $this->randomMachineName() . '.txt';
    $file = File::create([
      'filename' => $filename,
      'status' => 0,
    ]);

    $entity = EntityTest::create([
      'field_test_file' => [
        'entity' => $file,
      ],
    ]);

    $errors = $entity->validate();
    $this->assertEqual(1, count($errors));
    $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'file', '%label' => $filename]));
    $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_file.0.entity');

    // Set the file as permanent and try again.
    $file->setPermanent();
    $errors = $entity->validate();
    $this->assertEqual(0, count($errors));
585 586
  }

587
}