ContentEntityBaseUnitTest.php 20.6 KB
Newer Older
1
2
3
4
<?php

namespace Drupal\Tests\Core\Entity;

5
use Drupal\Core\Access\AccessResult;
6
use Drupal\Core\DependencyInjection\ContainerBuilder;
7
use Drupal\Core\Entity\ContentEntityInterface;
8
use Drupal\Core\Field\BaseFieldDefinition;
9
use Drupal\Core\Language\LanguageInterface;
10
use Drupal\Core\TypedData\TypedDataManagerInterface;
11
12
13
14
15
use Drupal\Tests\UnitTestCase;
use Drupal\Core\Language\Language;

/**
 * @coversDefaultClass \Drupal\Core\Entity\ContentEntityBase
16
 * @group Entity
17
 * @group Access
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 */
class ContentEntityBaseUnitTest extends UnitTestCase {

  /**
   * The bundle of the entity under test.
   *
   * @var string
   */
  protected $bundle;

  /**
   * The entity under test.
   *
   * @var \Drupal\Core\Entity\ContentEntityBase|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $entity;

35
36
37
38
39
40
41
  /**
   * An entity with no defined language to test.
   *
   * @var \Drupal\Core\Entity\ContentEntityBase|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $entityUnd;

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
  /**
   * The entity type used for testing.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $entityType;

  /**
   * The entity manager used for testing.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $entityManager;

  /**
   * The type ID of the entity under test.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * The typed data manager used for testing.
   *
   * @var \Drupal\Core\TypedData\TypedDataManager|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $typedDataManager;

70
71
72
73
74
75
76
  /**
   * The field type manager used for testing.
   *
   * @var \Drupal\Core\Field\FieldTypePluginManager|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $fieldTypePluginManager;

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $languageManager;

  /**
   * The UUID generator used for testing.
   *
   * @var \Drupal\Component\Uuid\UuidInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $uuid;

  /**
   * The entity ID.
   *
   * @var int
   */
  protected $id;

98
99
100
  /**
   * Field definitions.
   *
101
   * @var \Drupal\Core\Field\BaseFieldDefinition[]
102
103
104
   */
  protected $fieldDefinitions;

105
106
107
  /**
   * {@inheritdoc}
   */
108
  protected function setUp() {
109
110
111
112
    $this->id = 1;
    $values = array(
      'id' => $this->id,
      'uuid' => '3bb9ee60-bea5-4622-b89b-a63319d10b3a',
113
      'defaultLangcode' => array(LanguageInterface::LANGCODE_DEFAULT => 'en'),
114
    );
115
116
    $this->entityTypeId = $this->randomMachineName();
    $this->bundle = $this->randomMachineName();
117
118

    $this->entityType = $this->getMock('\Drupal\Core\Entity\EntityTypeInterface');
119
120
121
122
123
124
    $this->entityType->expects($this->any())
      ->method('getKeys')
      ->will($this->returnValue(array(
        'id' => 'id',
        'uuid' => 'uuid',
    )));
125
126
127
128
129
130
131
132
133

    $this->entityManager = $this->getMock('\Drupal\Core\Entity\EntityManagerInterface');
    $this->entityManager->expects($this->any())
      ->method('getDefinition')
      ->with($this->entityTypeId)
      ->will($this->returnValue($this->entityType));

    $this->uuid = $this->getMock('\Drupal\Component\Uuid\UuidInterface');

134
    $this->typedDataManager = $this->getMock(TypedDataManagerInterface::class);
135
136
137
138
    $this->typedDataManager->expects($this->any())
      ->method('getDefinition')
      ->with('entity')
      ->will($this->returnValue(['class' => '\Drupal\Core\Entity\Plugin\DataType\EntityAdapter']));
139

140
141
    $english = new Language(array('id' => 'en'));
    $not_specified = new Language(array('id' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'locked' => TRUE));
142
143
144
    $this->languageManager = $this->getMock('\Drupal\Core\Language\LanguageManagerInterface');
    $this->languageManager->expects($this->any())
      ->method('getLanguages')
145
      ->will($this->returnValue(array('en' => $english, LanguageInterface::LANGCODE_NOT_SPECIFIED => $not_specified)));
146
147
148
    $this->languageManager->expects($this->any())
      ->method('getLanguage')
      ->with('en')
149
      ->will($this->returnValue($english));
150
    $this->languageManager->expects($this->any())
151
152
153
      ->method('getLanguage')
      ->with(LanguageInterface::LANGCODE_NOT_SPECIFIED)
      ->will($this->returnValue($not_specified));
154

155
156
157
158
    $this->fieldTypePluginManager = $this->getMockBuilder('\Drupal\Core\Field\FieldTypePluginManager')
      ->disableOriginalConstructor()
      ->getMock();
    $this->fieldTypePluginManager->expects($this->any())
159
      ->method('getDefaultStorageSettings')
160
161
      ->will($this->returnValue(array()));
    $this->fieldTypePluginManager->expects($this->any())
162
      ->method('getDefaultFieldSettings')
163
      ->will($this->returnValue(array()));
164
165
166
    $this->fieldTypePluginManager->expects($this->any())
      ->method('createFieldItemList')
      ->will($this->returnValue($this->getMock('Drupal\Core\Field\FieldItemListInterface')));
167

168
169
170
171
172
    $container = new ContainerBuilder();
    $container->set('entity.manager', $this->entityManager);
    $container->set('uuid', $this->uuid);
    $container->set('typed_data_manager', $this->typedDataManager);
    $container->set('language_manager', $this->languageManager);
173
    $container->set('plugin.manager.field.field_type', $this->fieldTypePluginManager);
174
175
    \Drupal::setContainer($container);

176
    $this->fieldDefinitions = array(
177
178
      'id' => BaseFieldDefinition::create('integer'),
      'revision_id' => BaseFieldDefinition::create('integer'),
179
180
181
182
183
    );

    $this->entityManager->expects($this->any())
      ->method('getFieldDefinitions')
      ->with($this->entityTypeId, $this->bundle)
184
      ->will($this->returnValue($this->fieldDefinitions));
185
    $this->entity = $this->getMockForAbstractClass('\Drupal\Core\Entity\ContentEntityBase', array($values, $this->entityTypeId, $this->bundle));
186
187
188

    $values['defaultLangcode'] = array(LanguageInterface::LANGCODE_DEFAULT => LanguageInterface::LANGCODE_NOT_SPECIFIED);
    $this->entityUnd = $this->getMockForAbstractClass('\Drupal\Core\Entity\ContentEntityBase', array($values, $this->entityTypeId, $this->bundle));
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
  }

  /**
   * @covers ::isNewRevision
   * @covers ::setNewRevision
   */
  public function testIsNewRevision() {
    // Set up the entity type so that on the first call there is no revision key
    // and on the second call there is one.
    $this->entityType->expects($this->at(0))
      ->method('hasKey')
      ->with('revision')
      ->will($this->returnValue(FALSE));
    $this->entityType->expects($this->at(1))
      ->method('hasKey')
      ->with('revision')
      ->will($this->returnValue(TRUE));
206
207
208
209
210
211
212
213
    $this->entityType->expects($this->at(2))
      ->method('hasKey')
      ->with('revision')
      ->will($this->returnValue(TRUE));
    $this->entityType->expects($this->at(3))
      ->method('getKey')
      ->with('revision')
      ->will($this->returnValue('revision_id'));
214
215
216
217
218
219
220
221
    $this->entityType->expects($this->at(4))
      ->method('hasKey')
      ->with('revision')
      ->will($this->returnValue(TRUE));
    $this->entityType->expects($this->at(5))
      ->method('getKey')
      ->with('revision')
      ->will($this->returnValue('revision_id'));
222
223
224
225

    $field_item_list = $this->getMockBuilder('\Drupal\Core\Field\FieldItemList')
      ->disableOriginalConstructor()
      ->getMock();
226
227
    $field_item = $this->getMockBuilder('\Drupal\Core\Field\FieldItemBase')
      ->disableOriginalConstructor()
228
      ->getMockForAbstractClass();
229

230
231
232
    $this->fieldTypePluginManager->expects($this->any())
      ->method('createFieldItemList')
      ->with($this->entity, 'revision_id', NULL)
233
      ->will($this->returnValue($field_item_list));
234

235
236
    $this->fieldDefinitions['revision_id']->getItemDefinition()->setClass(get_class($field_item));

237
238
239
    $this->assertFalse($this->entity->isNewRevision());
    $this->assertTrue($this->entity->isNewRevision());
    $this->entity->setNewRevision(TRUE);
240
    $this->assertTrue($this->entity->isNewRevision());
241
242
  }

243
244
245
246
247
248
249
250
251
252
253
254
  /**
   * @covers ::setNewRevision
   */
  public function testSetNewRevisionException() {
    $this->entityType->expects($this->once())
      ->method('hasKey')
      ->with('revision')
      ->will($this->returnValue(FALSE));
    $this->setExpectedException('LogicException', 'Entity type ' . $this->entityTypeId . ' does not support revisions.');
    $this->entity->setNewRevision();
  }

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
  /**
   * @covers ::isDefaultRevision
   */
  public function testIsDefaultRevision() {
    // The default value is TRUE.
    $this->assertTrue($this->entity->isDefaultRevision());
    // Change the default revision, verify that the old value is returned.
    $this->assertTrue($this->entity->isDefaultRevision(FALSE));
    // The last call changed the return value for this call.
    $this->assertFalse($this->entity->isDefaultRevision());
  }

  /**
   * @covers ::getRevisionId
   */
  public function testGetRevisionId() {
    // The default getRevisionId() implementation returns NULL.
    $this->assertNull($this->entity->getRevisionId());
  }

  /**
   * @covers ::isTranslatable
   */
  public function testIsTranslatable() {
279
    $this->entityManager->expects($this->any())
280
281
282
283
284
285
286
      ->method('getBundleInfo')
      ->with($this->entityTypeId)
      ->will($this->returnValue(array(
        $this->bundle => array(
          'translatable' => TRUE,
        ),
      )));
287
288
289
    $this->languageManager->expects($this->any())
      ->method('isMultilingual')
      ->will($this->returnValue(TRUE));
290
    $this->assertTrue($this->entity->language()->getId() == 'en');
291
    $this->assertFalse($this->entity->language()->isLocked());
292
    $this->assertTrue($this->entity->isTranslatable());
293

294
    $this->assertTrue($this->entityUnd->language()->getId() == LanguageInterface::LANGCODE_NOT_SPECIFIED);
295
    $this->assertTrue($this->entityUnd->language()->isLocked());
296
297
298
299
300
301
302
303
304
305
    $this->assertFalse($this->entityUnd->isTranslatable());
  }

  /**
   * @covers ::isTranslatable
   */
  public function testIsTranslatableForMonolingual() {
    $this->languageManager->expects($this->any())
      ->method('isMultilingual')
      ->will($this->returnValue(FALSE));
306
307
308
309
310
311
312
313
    $this->assertFalse($this->entity->isTranslatable());
  }

  /**
   * @covers ::preSaveRevision
   */
  public function testPreSaveRevision() {
    // This method is internal, so check for errors on calling it only.
314
    $storage = $this->getMock('\Drupal\Core\Entity\EntityStorageInterface');
315
    $record = new \stdClass();
316
317
    // Our mocked entity->preSaveRevision() returns NULL, so assert that.
    $this->assertNull($this->entity->preSaveRevision($storage, $record));
318
319
320
321
322
323
  }

  /**
   * @covers ::validate
   */
  public function testValidate() {
324
    $validator = $this->getMock('\Symfony\Component\Validator\ValidatorInterface');
325
326
327
328
329
330
331
332
333
    /** @var \Symfony\Component\Validator\ConstraintViolationList|\PHPUnit_Framework_MockObject_MockObject $empty_violation_list */
    $empty_violation_list = $this->getMockBuilder('\Symfony\Component\Validator\ConstraintViolationList')
      ->setMethods(NULL)
      ->getMock();
    $non_empty_violation_list = clone $empty_violation_list;
    $violation = $this->getMock('\Symfony\Component\Validator\ConstraintViolationInterface');
    $non_empty_violation_list->add($violation);
    $validator->expects($this->at(0))
      ->method('validate')
334
      ->with($this->entity->getTypedData())
335
336
337
      ->will($this->returnValue($empty_violation_list));
    $validator->expects($this->at(1))
      ->method('validate')
338
      ->with($this->entity->getTypedData())
339
340
341
342
343
344
345
346
      ->will($this->returnValue($non_empty_violation_list));
    $this->typedDataManager->expects($this->exactly(2))
      ->method('getValidator')
      ->will($this->returnValue($validator));
    $this->assertSame(0, count($this->entity->validate()));
    $this->assertSame(1, count($this->entity->validate()));
  }

347
348
349
350
351
352
353
354
355
356
357
358
359
  /**
   * Tests required validation.
   *
   * @covers ::validate
   * @covers ::isValidationRequired
   * @covers ::setValidationRequired
   * @covers ::save
   * @covers ::preSave
   *
   * @expectedException \LogicException
   * @expectedExceptionMessage Entity validation was skipped.
   */
  public function testRequiredValidation() {
360
    $validator = $this->getMock('\Symfony\Component\Validator\ValidatorInterface');
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
    /** @var \Symfony\Component\Validator\ConstraintViolationList|\PHPUnit_Framework_MockObject_MockObject $empty_violation_list */
    $empty_violation_list = $this->getMockBuilder('\Symfony\Component\Validator\ConstraintViolationList')
      ->setMethods(NULL)
      ->getMock();
    $validator->expects($this->at(0))
      ->method('validate')
      ->with($this->entity->getTypedData())
      ->will($this->returnValue($empty_violation_list));
    $this->typedDataManager->expects($this->any())
      ->method('getValidator')
      ->will($this->returnValue($validator));

    /** @var \Drupal\Core\Entity\EntityStorageInterface|\PHPUnit_Framework_MockObject_MockObject $storage */
    $storage = $this->getMock('\Drupal\Core\Entity\EntityStorageInterface');
    $storage->expects($this->any())
      ->method('save')
      ->willReturnCallback(function (ContentEntityInterface $entity) use ($storage) {
        $entity->preSave($storage);
      });

    $this->entityManager->expects($this->any())
      ->method('getStorage')
      ->with($this->entityTypeId)
      ->will($this->returnValue($storage));

    // Check that entities can be saved normally when validation is not
    // required.
    $this->assertFalse($this->entity->isValidationRequired());
    $this->entity->save();

    // Make validation required and check that if the entity is validated, it
    // can be saved normally.
    $this->entity->setValidationRequired(TRUE);
    $this->assertTrue($this->entity->isValidationRequired());
    $this->entity->validate();
    $this->entity->save();

    // Check that the "validated" status is reset after saving the entity and
    // that trying to save a non-validated entity when validation is required
    // results in an exception.
    $this->assertTrue($this->entity->isValidationRequired());
    $this->entity->save();
  }

405
406
407
408
409
410
411
412
413
414
415
  /**
   * @covers ::bundle
   */
  public function testBundle() {
    $this->assertSame($this->bundle, $this->entity->bundle());
  }

  /**
   * @covers ::access
   */
  public function testAccess() {
416
    $access = $this->getMock('\Drupal\Core\Entity\EntityAccessControlHandlerInterface');
417
    $operation = $this->randomMachineName();
418
419
420
421
422
    $access->expects($this->at(0))
      ->method('access')
      ->with($this->entity, $operation)
      ->will($this->returnValue(TRUE));
    $access->expects($this->at(1))
423
424
425
426
      ->method('access')
      ->with($this->entity, $operation)
      ->will($this->returnValue(AccessResult::allowed()));
    $access->expects($this->at(2))
427
428
      ->method('createAccess')
      ->will($this->returnValue(TRUE));
429
430
431
432
    $access->expects($this->at(3))
      ->method('createAccess')
      ->will($this->returnValue(AccessResult::allowed()));
    $this->entityManager->expects($this->exactly(4))
433
      ->method('getAccessControlHandler')
434
435
      ->will($this->returnValue($access));
    $this->assertTrue($this->entity->access($operation));
436
    $this->assertEquals(AccessResult::allowed(), $this->entity->access($operation, NULL, TRUE));
437
    $this->assertTrue($this->entity->access('create'));
438
    $this->assertEquals(AccessResult::allowed(), $this->entity->access('create', NULL, TRUE));
439
440
441
442
443
444
445
446
447
  }

  /**
   * @covers ::label
   */
  public function testLabel() {
    // Make a mock with one method that we use as the entity's label callback.
    // We check that it is called, and that the entity's label is the callback's
    // return value.
448
    $callback_label = $this->randomMachineName();
449
450
451
452
453
454
455
456
457
458
    $callback_container = $this->getMock(get_class());
    $callback_container->expects($this->once())
      ->method(__FUNCTION__)
      ->will($this->returnValue($callback_label));
    $this->entityType->expects($this->once())
      ->method('getLabelCallback')
      ->will($this->returnValue(array($callback_container, __FUNCTION__)));

    $this->assertSame($callback_label, $this->entity->label());
  }
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
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
585
586
587
588
589
590
591
592
593
594

  /**
   * Data provider for testGet().
   *
   * @returns
   *   - Expected output from get().
   *   - Field name parameter to get().
   *   - Language code for $activeLanguage.
   *   - Fields array for $fields.
   */
  public function providerGet() {
    return [
      // Populated fields array.
      ['result', 'field_name', 'langcode', ['field_name' => ['langcode' => 'result']]],
      // Incomplete fields array.
      ['getTranslatedField_result', 'field_name', 'langcode', ['field_name' => 'no_langcode']],
      // Empty fields array.
      ['getTranslatedField_result', 'field_name', 'langcode', []],
    ];
  }

  /**
   * @covers ::get
   * @dataProvider providerGet
   */
  public function testGet($expected, $field_name, $active_langcode, $fields) {
    // Mock ContentEntityBase.
    $mock_base = $this->getMockBuilder('Drupal\Core\Entity\ContentEntityBase')
      ->disableOriginalConstructor()
      ->setMethods(array('getTranslatedField'))
      ->getMockForAbstractClass();

    // Set up expectations for getTranslatedField() method. In get(),
    // getTranslatedField() is only called if the field name and language code
    // are not present as keys in the fields array.
    if (isset($fields[$field_name][$active_langcode])) {
      $mock_base->expects($this->never())
        ->method('getTranslatedField');
    }
    else {
      $mock_base->expects($this->once())
        ->method('getTranslatedField')
        ->with(
          $this->equalTo($field_name),
          $this->equalTo($active_langcode)
        )
        ->willReturn($expected);
    }

    // Poke in activeLangcode.
    $ref_langcode = new \ReflectionProperty($mock_base, 'activeLangcode');
    $ref_langcode->setAccessible(TRUE);
    $ref_langcode->setValue($mock_base, $active_langcode);

    // Poke in fields.
    $ref_fields = new \ReflectionProperty($mock_base, 'fields');
    $ref_fields->setAccessible(TRUE);
    $ref_fields->setValue($mock_base, $fields);

    // Exercise get().
    $this->assertEquals($expected, $mock_base->get($field_name));
  }

  /**
   * Data provider for testGetFields().
   *
   * @returns array
   *   - Expected output from getFields().
   *   - $include_computed value to pass to getFields().
   *   - Value to mock from all field definitions for isComputed().
   *   - Array of field names to return from mocked getFieldDefinitions(). A
   *     Drupal\Core\Field\FieldDefinitionInterface object will be mocked for
   *     each name.
   */
  public function providerGetFields() {
    return [
      [[], FALSE, FALSE, []],
      [['field' => 'field', 'field2' => 'field2'], TRUE, FALSE, ['field', 'field2']],
      [['field3' => 'field3'], TRUE, TRUE, ['field3']],
      [[], FALSE, TRUE, ['field4']],
    ];
  }

  /**
   * @covers ::getFields
   * @dataProvider providerGetFields
   */
  public function testGetFields($expected, $include_computed, $is_computed, $field_definitions) {
    // Mock ContentEntityBase.
    $mock_base = $this->getMockBuilder('Drupal\Core\Entity\ContentEntityBase')
      ->disableOriginalConstructor()
      ->setMethods(array('getFieldDefinitions', 'get'))
      ->getMockForAbstractClass();

    // Mock field definition objects for each element of $field_definitions.
    $mocked_field_definitions = array();
    foreach ($field_definitions as $name) {
      $mock_definition = $this->getMockBuilder('Drupal\Core\Field\FieldDefinitionInterface')
        ->setMethods(array('isComputed'))
        ->getMockForAbstractClass();
      // Set expectations for isComputed(). isComputed() gets called whenever
      // $include_computed is FALSE, but not otherwise. It returns the value of
      // $is_computed.
      $mock_definition->expects($this->exactly(
        $include_computed ? 0 : 1
        ))
        ->method('isComputed')
        ->willReturn($is_computed);
      $mocked_field_definitions[$name] = $mock_definition;
    }

    // Set up expectations for getFieldDefinitions().
    $mock_base->expects($this->once())
      ->method('getFieldDefinitions')
      ->willReturn($mocked_field_definitions);

    // How many time will we call get()? Since we are rigging all defined fields
    // to be computed based on $is_computed, then if $include_computed is FALSE,
    // get() will never be called.
    $get_count = 0;
    if ($include_computed) {
      $get_count = count($field_definitions);
    }

    // Set up expectations for get(). It simply returns the name passed in.
    $mock_base->expects($this->exactly($get_count))
      ->method('get')
      ->willReturnArgument(0);

    // Exercise getFields().
    $this->assertArrayEquals(
      $expected,
      $mock_base->getFields($include_computed)
    );
  }

595
596
597
598
599
600
601
602
603
604
605
  /**
   * @covers ::set
   */
  public function testSet() {
    // Exercise set(), check if it returns $this
    $this->assertSame(
      $this->entity,
      $this->entity->set('id', 0)
    );
  }

606
}