Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -0,0 +1,6 @@
name: 'FieldItem normalization test support'
type: module
description: 'Provides test support for fieldItem normalization test support.'
package: Testing
version: VERSION
core: 8.x

View file

@ -0,0 +1,6 @@
services:
serializer.normalizer.silly_fielditem:
class: Drupal\field_normalization_test\Normalization\TextItemSillyNormalizer
tags:
# The priority must be higher than serialization.normalizer.field_item.
- { name: normalizer , priority: 9 }

View file

@ -0,0 +1,36 @@
<?php
namespace Drupal\field_normalization_test\Normalization;
use Drupal\serialization\Normalizer\FieldItemNormalizer;
use Drupal\text\Plugin\Field\FieldType\TextItemBase;
/**
* A test TextItem normalizer to test denormalization.
*/
class TextItemSillyNormalizer extends FieldItemNormalizer {
/**
* {@inheritdoc}
*/
protected $supportedInterfaceOrClass = TextItemBase::class;
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []) {
$data = parent::normalize($object, $format, $context);
$data['value'] .= '::silly_suffix';
return $data;
}
/**
* {@inheritdoc}
*/
protected function constructValue($data, $context) {
$value = parent::constructValue($data, $context);
$value['value'] = str_replace('::silly_suffix', '', $value['value']);
return $value;
}
}

View file

@ -16,7 +16,7 @@ class SerializationTestEncoder implements EncoderInterface {
/**
* {@inheritdoc}
*/
public function encode($data, $format, array $context = array()) {
public function encode($data, $format, array $context = []) {
// @see \Drupal\serialization_test\SerializationTestNormalizer::normalize().
return 'Normalized by ' . $data['normalized_by'] . ', Encoded by SerializationTestEncoder';
}

View file

@ -25,7 +25,7 @@ class SerializationTestNormalizer implements NormalizerInterface {
* An array containing a normalized representation of $object, appropriate
* for encoding to the requested format.
*/
public function normalize($object, $format = NULL, array $context = array()) {
public function normalize($object, $format = NULL, array $context = []) {
$normalized = (array) $object;
// Add identifying value that can be used to verify that the expected
// normalizer was invoked.

View file

@ -34,14 +34,14 @@ class EntityResolverTest extends NormalizerTestBase {
\Drupal::service('router.builder')->rebuild();
// Create the test field storage.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'entity_type' => 'entity_test_mulrev',
'field_name' => 'field_test_entity_reference',
'type' => 'entity_reference',
'settings' => array(
'settings' => [
'target_type' => 'entity_test_mulrev',
),
))->save();
],
])->save();
// Create the test field.
FieldConfig::create([
@ -54,41 +54,41 @@ class EntityResolverTest extends NormalizerTestBase {
/**
* Test that fields referencing UUIDs can be denormalized.
*/
function testUuidEntityResolver() {
public function testUuidEntityResolver() {
// Create an entity to get the UUID from.
$entity = EntityTestMulRev::create(array('type' => 'entity_test_mulrev'));
$entity = EntityTestMulRev::create(['type' => 'entity_test_mulrev']);
$entity->set('name', 'foobar');
$entity->set('field_test_entity_reference', array(array('target_id' => 1)));
$entity->set('field_test_entity_reference', [['target_id' => 1]]);
$entity->save();
$field_uri = Url::fromUri('base:rest/relation/entity_test_mulrev/entity_test_mulrev/field_test_entity_reference', array('absolute' => TRUE))->toString();
$field_uri = Url::fromUri('base:rest/relation/entity_test_mulrev/entity_test_mulrev/field_test_entity_reference', ['absolute' => TRUE])->toString();
$data = array(
'_links' => array(
'type' => array(
'href' => Url::fromUri('base:rest/type/entity_test_mulrev/entity_test_mulrev', array('absolute' => TRUE))->toString(),
),
$field_uri => array(
array(
$data = [
'_links' => [
'type' => [
'href' => Url::fromUri('base:rest/type/entity_test_mulrev/entity_test_mulrev', ['absolute' => TRUE])->toString(),
],
$field_uri => [
[
'href' => $entity->url(),
),
),
),
'_embedded' => array(
$field_uri => array(
array(
'_links' => array(
],
],
],
'_embedded' => [
$field_uri => [
[
'_links' => [
'self' => $entity->url(),
),
'uuid' => array(
array(
],
'uuid' => [
[
'value' => $entity->uuid(),
),
),
),
),
),
);
],
],
],
],
],
];
$denormalized = $this->container->get('serializer')->denormalize($data, 'Drupal\entity_test\Entity\EntityTestMulRev', $this->format);
$field_value = $denormalized->get('field_test_entity_reference')->getValue();

View file

@ -17,7 +17,7 @@ class EntitySerializationTest extends NormalizerTestBase {
*
* @var array
*/
public static $modules = array('serialization', 'system', 'field', 'entity_test', 'text', 'filter', 'user', 'entity_serialization_test');
public static $modules = ['serialization', 'system', 'field', 'entity_test', 'text', 'filter', 'user', 'entity_serialization_test'];
/**
* The test values.
@ -29,7 +29,7 @@ class EntitySerializationTest extends NormalizerTestBase {
/**
* The test entity.
*
* @var \Drupal\Core\Entity\ContentEntityBase
* @var \Drupal\Core\Entity\ContentEntityInterface
*/
protected $entity;
@ -58,7 +58,7 @@ class EntitySerializationTest extends NormalizerTestBase {
parent::setUp();
// User create needs sequence table.
$this->installSchema('system', array('sequences'));
$this->installSchema('system', ['sequences']);
// Create a test user to use as the entity owner.
$this->user = \Drupal::entityManager()->getStorage('user')->create([
@ -69,74 +69,75 @@ class EntitySerializationTest extends NormalizerTestBase {
$this->user->save();
// Create a test entity to serialize.
$this->values = array(
$this->values = [
'name' => $this->randomMachineName(),
'user_id' => $this->user->id(),
'field_test_text' => array(
'field_test_text' => [
'value' => $this->randomMachineName(),
'format' => 'full_html',
),
);
],
];
$this->entity = EntityTestMulRev::create($this->values);
$this->entity->save();
$this->serializer = $this->container->get('serializer');
$this->installConfig(array('field'));
$this->installConfig(['field']);
}
/**
* Test the normalize function.
*/
public function testNormalize() {
$expected = array(
'id' => array(
array('value' => 1),
),
'uuid' => array(
array('value' => $this->entity->uuid()),
),
'langcode' => array(
array('value' => 'en'),
),
'name' => array(
array('value' => $this->values['name']),
),
'type' => array(
array('value' => 'entity_test_mulrev'),
),
'created' => array(
array('value' => $this->entity->created->value),
),
'user_id' => array(
array(
'target_id' => $this->user->id(),
$expected = [
'id' => [
['value' => 1],
],
'uuid' => [
['value' => $this->entity->uuid()],
],
'langcode' => [
['value' => 'en'],
],
'name' => [
['value' => $this->values['name']],
],
'type' => [
['value' => 'entity_test_mulrev'],
],
'created' => [
['value' => $this->entity->created->value],
],
'user_id' => [
[
// id() will return the string value as it comes from the database.
'target_id' => (int) $this->user->id(),
'target_type' => $this->user->getEntityTypeId(),
'target_uuid' => $this->user->uuid(),
'url' => $this->user->url(),
),
),
'revision_id' => array(
array('value' => 1),
),
'default_langcode' => array(
array('value' => TRUE),
),
'non_rev_field' => array(),
'field_test_text' => array(
array(
],
],
'revision_id' => [
['value' => 1],
],
'default_langcode' => [
['value' => TRUE],
],
'non_rev_field' => [],
'field_test_text' => [
[
'value' => $this->values['field_test_text']['value'],
'format' => $this->values['field_test_text']['format'],
),
),
);
],
],
];
$normalized = $this->serializer->normalize($this->entity);
foreach (array_keys($expected) as $fieldName) {
$this->assertEqual($expected[$fieldName], $normalized[$fieldName], "ComplexDataNormalizer produces expected array for $fieldName.");
$this->assertSame($expected[$fieldName], $normalized[$fieldName], "Normalization produces expected array for $fieldName.");
}
$this->assertEqual(array_diff_key($normalized, $expected), array(), 'No unexpected data is added to the normalized array.');
$this->assertEqual(array_diff_key($normalized, $expected), [], 'No unexpected data is added to the normalized array.');
}
/**
@ -181,7 +182,7 @@ class EntitySerializationTest extends NormalizerTestBase {
// Generate the expected xml in a way that allows changes to entity property
// order.
$expected = array(
$expected = [
'id' => '<id><value>' . $this->entity->id() . '</value></id>',
'uuid' => '<uuid><value>' . $this->entity->uuid() . '</value></uuid>',
'langcode' => '<langcode><value>en</value></langcode>',
@ -193,7 +194,7 @@ class EntitySerializationTest extends NormalizerTestBase {
'default_langcode' => '<default_langcode><value>1</value></default_langcode>',
'non_rev_field' => '<non_rev_field/>',
'field_test_text' => '<field_test_text><value>' . $this->values['field_test_text']['value'] . '</value><format>' . $this->values['field_test_text']['format'] . '</format></field_test_text>',
);
];
// Sort it in the same order as normalised.
$expected = array_merge($normalized, $expected);
// Add header and footer.
@ -214,9 +215,9 @@ class EntitySerializationTest extends NormalizerTestBase {
public function testDenormalize() {
$normalized = $this->serializer->normalize($this->entity);
foreach (array('json', 'xml') as $type) {
$denormalized = $this->serializer->denormalize($normalized, $this->entityClass, $type, array('entity_type' => 'entity_test_mulrev'));
$this->assertTrue($denormalized instanceof $this->entityClass, SafeMarkup::format('Denormalized entity is an instance of @class', array('@class' => $this->entityClass)));
foreach (['json', 'xml'] as $type) {
$denormalized = $this->serializer->denormalize($normalized, $this->entityClass, $type, ['entity_type' => 'entity_test_mulrev']);
$this->assertTrue($denormalized instanceof $this->entityClass, SafeMarkup::format('Denormalized entity is an instance of @class', ['@class' => $this->entityClass]));
$this->assertIdentical($denormalized->getEntityTypeId(), $this->entity->getEntityTypeId(), 'Expected entity type found.');
$this->assertIdentical($denormalized->bundle(), $this->entity->bundle(), 'Expected entity bundle found.');
$this->assertIdentical($denormalized->uuid(), $this->entity->uuid(), 'Expected entity UUID found.');

View file

@ -0,0 +1,135 @@
<?php
namespace Drupal\Tests\serialization\Kernel;
use Drupal\entity_test\Entity\EntityTestMulRev;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
* Test field level normalization process.
*
* @group serialization
*/
class FieldItemSerializationTest extends NormalizerTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['serialization', 'system', 'field', 'entity_test', 'text', 'filter', 'user', 'field_normalization_test'];
/**
* The class name of the test class.
*
* @var string
*/
protected $entityClass = 'Drupal\entity_test\Entity\EntityTestMulRev';
/**
* The test values.
*
* @var array
*/
protected $values;
/**
* The test entity.
*
* @var \Drupal\Core\Entity\ContentEntityBase
*/
protected $entity;
/**
* The serializer service.
*
* @var \Symfony\Component\Serializer\Serializer.
*/
protected $serializer;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Auto-create a field for testing default field values.
FieldStorageConfig::create([
'entity_type' => 'entity_test_mulrev',
'field_name' => 'field_test_text_default',
'type' => 'text',
'cardinality' => 1,
'translatable' => FALSE,
])->save();
FieldConfig::create([
'entity_type' => 'entity_test_mulrev',
'field_name' => 'field_test_text_default',
'bundle' => 'entity_test_mulrev',
'label' => 'Test text-field with default',
'default_value' => [
[
'value' => 'This is the default',
'format' => 'full_html',
],
],
'widget' => [
'type' => 'text_textfield',
'weight' => 0,
],
])->save();
// Create a test entity to serialize.
$this->values = [
'name' => $this->randomMachineName(),
'field_test_text' => [
'value' => $this->randomMachineName(),
'format' => 'full_html',
],
];
$this->entity = EntityTestMulRev::create($this->values);
$this->entity->save();
$this->serializer = $this->container->get('serializer');
$this->installConfig(['field']);
}
/**
* Tests normalizing and denormalizing an entity with field item normalizer.
*/
public function testFieldNormalizeDenormalize() {
$normalized = $this->serializer->normalize($this->entity, 'json');
$expected_field_value = $this->entity->field_test_text[0]->getValue()['value'] . '::silly_suffix';
$this->assertEquals($expected_field_value, $normalized['field_test_text'][0]['value'], 'Text field item normalized');
$denormalized = $this->serializer->denormalize($normalized, $this->entityClass, 'json');
$this->assertEquals($denormalized->field_test_text[0]->getValue(), $this->entity->field_test_text[0]->getValue(), 'Text field item denormalized.');
$this->assertEquals($denormalized->field_test_text_default[0]->getValue(), $this->entity->field_test_text_default[0]->getValue(), 'Text field item with default denormalized.');
// Unset the values for text field that has a default value.
unset($normalized['field_test_text_default']);
$denormalized_without_all_fields = $this->serializer->denormalize($normalized, $this->entityClass, 'json');
// Check that denormalized entity is still the same even if not all fields
// are not provided.
$this->assertEquals($denormalized_without_all_fields->field_test_text[0]->getValue(), $this->entity->field_test_text[0]->getValue(), 'Text field item denormalized.');
// Even though field_test_text_default value was unset before
// denormalization it should still have the default values for the field.
$this->assertEquals($denormalized_without_all_fields->field_test_text_default[0]->getValue(), $this->entity->field_test_text_default[0]->getValue(), 'Text field item with default denormalized.');
}
/**
* Tests denormalizing using a scalar field value.
*/
public function testFieldDenormalizeWithScalarValue() {
$this->setExpectedException(UnexpectedValueException::class, 'Field values for "uuid" must use an array structure');
$normalized = $this->serializer->normalize($this->entity, 'json');
// Change the UUID value to use the UUID directly. No array structure.
$normalized['uuid'] = $normalized['uuid'][0]['value'];
$this->serializer->denormalize($normalized, $this->entityClass, 'json');
}
}

View file

@ -16,35 +16,35 @@ abstract class NormalizerTestBase extends KernelTestBase {
*
* @var array
*/
public static $modules = array('serialization', 'system', 'field', 'entity_test', 'text', 'filter', 'user');
public static $modules = ['serialization', 'system', 'field', 'entity_test', 'text', 'filter', 'user'];
protected function setUp() {
parent::setUp();
$this->installEntitySchema('entity_test_mulrev');
$this->installEntitySchema('user');
$this->installConfig(array('field'));
$this->installConfig(['field']);
\Drupal::service('router.builder')->rebuild();
\Drupal::moduleHandler()->invoke('rest', 'install');
// Auto-create a field for testing.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'entity_type' => 'entity_test_mulrev',
'field_name' => 'field_test_text',
'type' => 'text',
'cardinality' => 1,
'translatable' => FALSE,
))->save();
FieldConfig::create(array(
])->save();
FieldConfig::create([
'entity_type' => 'entity_test_mulrev',
'field_name' => 'field_test_text',
'bundle' => 'entity_test_mulrev',
'label' => 'Test text-field',
'widget' => array(
'widget' => [
'type' => 'text_textfield',
'weight' => 0,
),
))->save();
],
])->save();
}
}

View file

@ -17,7 +17,7 @@ class SerializationTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('serialization', 'serialization_test');
public static $modules = ['serialization', 'serialization_test'];
/**
* The serializer service to test.

View file

@ -0,0 +1,45 @@
<?php
namespace Drupal\Tests\serialization\Unit\CompilerPass;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\serialization\RegisterSerializationClassesCompilerPass;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Serializer\Serializer;
/**
* @coversDefaultClass \Drupal\serialization\RegisterSerializationClassesCompilerPass
* @group serialization
*/
class RegisterSerializationClassesCompilerPassTest extends \PHPUnit_Framework_TestCase {
/**
* @covers ::process
*/
public function testEncoders() {
$container = new ContainerBuilder();
$container->setDefinition('serializer', new Definition(Serializer::class, [[], []]));
$definition = new Definition('TestClass');
$definition->addTag('encoder', ['format' => 'xml']);
$definition->addTag('_provider', ['provider' => 'test_provider_a']);
$container->setDefinition('encoder_1', $definition);
$definition = new Definition('TestClass');
$definition->addTag('encoder', ['format' => 'json']);
$definition->addTag('_provider', ['provider' => 'test_provider_a']);
$container->setDefinition('encoder_2', $definition);
$definition = new Definition('TestClass');
$definition->addTag('encoder', ['format' => 'hal_json']);
$definition->addTag('_provider', ['provider' => 'test_provider_b']);
$container->setDefinition('encoder_3', $definition);
$compiler_pass = new RegisterSerializationClassesCompilerPass();
$compiler_pass->process($container);
$this->assertEquals(['xml', 'json', 'hal_json'], $container->getParameter('serializer.formats'));
$this->assertEquals(['xml' => 'test_provider_a', 'json' => 'test_provider_a', 'hal_json' => 'test_provider_b'], $container->getParameter('serializer.format_providers'));
}
}

View file

@ -28,7 +28,7 @@ class XmlEncoderTest extends UnitTestCase {
*
* @var array
*/
protected $testArray = array('test' => 'test');
protected $testArray = ['test' => 'test'];
protected function setUp() {
$this->baseEncoder = $this->getMock('Symfony\Component\Serializer\Encoder\XmlEncoder');
@ -58,7 +58,7 @@ class XmlEncoderTest extends UnitTestCase {
public function testEncode() {
$this->baseEncoder->expects($this->once())
->method('encode')
->with($this->testArray, 'test', array())
->with($this->testArray, 'test', [])
->will($this->returnValue('test'));
$this->assertEquals('test', $this->encoder->encode($this->testArray, 'test'));
@ -70,7 +70,7 @@ class XmlEncoderTest extends UnitTestCase {
public function testDecode() {
$this->baseEncoder->expects($this->once())
->method('decode')
->with('test', 'test', array())
->with('test', 'test', [])
->will($this->returnValue($this->testArray));
$this->assertEquals($this->testArray, $this->encoder->decode('test', 'test'));

View file

@ -47,10 +47,10 @@ class ChainEntityResolverTest extends UnitTestCase {
* @covers ::resolve
*/
public function testResolverWithNoneResolved() {
$resolvers = array(
$resolvers = [
$this->createEntityResolverMock(),
$this->createEntityResolverMock(),
);
];
$resolver = new ChainEntityResolver($resolvers);
@ -78,10 +78,10 @@ class ChainEntityResolverTest extends UnitTestCase {
* @covers ::resolve
*/
public function testResolverWithFirstResolved() {
$resolvers = array(
$resolvers = [
$this->createEntityResolverMock(10),
$this->createEntityResolverMock(NULL, FALSE),
);
];
$resolver = new ChainEntityResolver($resolvers);
@ -95,10 +95,10 @@ class ChainEntityResolverTest extends UnitTestCase {
* @covers ::resolve
*/
public function testResolverWithLastResolved() {
$resolvers = array(
$resolvers = [
$this->createEntityResolverMock(),
$this->createEntityResolverMock(10),
);
];
$resolver = new ChainEntityResolver($resolvers);
@ -112,10 +112,10 @@ class ChainEntityResolverTest extends UnitTestCase {
* @covers ::resolve
*/
public function testResolverWithResolvedToZero() {
$resolvers = array(
$resolvers = [
$this->createEntityResolverMock(0),
$this->createEntityResolverMock(NULL, FALSE),
);
];
$resolver = new ChainEntityResolver($resolvers);

View file

@ -44,7 +44,7 @@ class UuidResolverTest extends UnitTestCase {
->method('loadEntityByUuid');
$normalizer = $this->getMock('Symfony\Component\Serializer\Normalizer\NormalizerInterface');
$this->assertNull($this->resolver->resolve($normalizer, array(), 'test_type'));
$this->assertNull($this->resolver->resolve($normalizer, [], 'test_type'));
}
/**
@ -57,9 +57,9 @@ class UuidResolverTest extends UnitTestCase {
$normalizer = $this->getMock('Drupal\serialization\EntityResolver\UuidReferenceInterface');
$normalizer->expects($this->once())
->method('getUuid')
->with(array())
->with([])
->will($this->returnValue(NULL));
$this->assertNull($this->resolver->resolve($normalizer, array(), 'test_type'));
$this->assertNull($this->resolver->resolve($normalizer, [], 'test_type'));
}
/**
@ -76,10 +76,10 @@ class UuidResolverTest extends UnitTestCase {
$normalizer = $this->getMock('Drupal\serialization\EntityResolver\UuidReferenceInterface');
$normalizer->expects($this->once())
->method('getUuid')
->with(array())
->with([])
->will($this->returnValue($uuid));
$this->assertNull($this->resolver->resolve($normalizer, array(), 'test_type'));
$this->assertNull($this->resolver->resolve($normalizer, [], 'test_type'));
}
/**
@ -101,9 +101,9 @@ class UuidResolverTest extends UnitTestCase {
$normalizer = $this->getMock('Drupal\serialization\EntityResolver\UuidReferenceInterface');
$normalizer->expects($this->once())
->method('getUuid')
->with(array())
->with([])
->will($this->returnValue($uuid));
$this->assertSame(1, $this->resolver->resolve($normalizer, array(), 'test_type'));
$this->assertSame(1, $this->resolver->resolve($normalizer, [], 'test_type'));
}
}

View file

@ -0,0 +1,42 @@
<?php
namespace Drupal\Tests\serialization\Unit\EventSubscriber;
use Drupal\serialization\Encoder\JsonEncoder;
use Drupal\serialization\EventSubscriber\DefaultExceptionSubscriber;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Serializer\Serializer;
/**
* @coversDefaultClass \Drupal\serialization\EventSubscriber\DefaultExceptionSubscriber
* @group serialization
*/
class DefaultExceptionSubscriberTest extends UnitTestCase {
/**
* @covers ::on4xx
*/
public function testOn4xx() {
$kernel = $this->prophesize(HttpKernelInterface::class);
$request = Request::create('/test');
$request->setRequestFormat('json');
$e = new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message');
$event = new GetResponseForExceptionEvent($kernel->reveal(), $request, 'GET', $e);
$subscriber = new DefaultExceptionSubscriber(new Serializer([], [new JsonEncoder()]), []);
$subscriber->on4xx($event);
$response = $event->getResponse();
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals('{"message":"test message"}', $response->getContent());
$this->assertEquals(405, $response->getStatusCode());
$this->assertEquals('POST, PUT', $response->headers->get('Allow'));
$this->assertEquals('application/json', $response->headers->get('Content-Type'));
}
}

View file

@ -17,7 +17,7 @@ class ConfigEntityNormalizerTest extends UnitTestCase {
* @covers ::normalize
*/
public function testNormalize() {
$test_export_properties = array('test' => 'test');
$test_export_properties = ['test' => 'test'];
$entity_manager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
$normalizer = new ConfigEntityNormalizer($entity_manager);

View file

@ -40,7 +40,7 @@ class ContentEntityNormalizerTest extends UnitTestCase {
$this->contentEntityNormalizer = new ContentEntityNormalizer($this->entityManager);
$this->serializer = $this->getMockBuilder('Symfony\Component\Serializer\Serializer')
->disableOriginalConstructor()
->setMethods(array('normalize'))
->setMethods(['normalize'])
->getMock();
$this->contentEntityNormalizer->setSerializer($this->serializer);
}
@ -66,10 +66,10 @@ class ContentEntityNormalizerTest extends UnitTestCase {
->with($this->containsOnlyInstancesOf('Drupal\Core\Field\FieldItemListInterface'), 'test_format', ['account' => NULL])
->will($this->returnValue('test'));
$definitions = array(
$definitions = [
'field_1' => $this->createMockFieldListItem(),
'field_2' => $this->createMockFieldListItem(FALSE),
);
];
$content_entity_mock = $this->createMockForContentEntity($definitions);
$normalized = $this->contentEntityNormalizer->normalize($content_entity_mock, 'test_format');
@ -98,10 +98,10 @@ class ContentEntityNormalizerTest extends UnitTestCase {
// The mock account should get passed directly into the access() method on
// field items from $context['account'].
$definitions = array(
$definitions = [
'field_1' => $this->createMockFieldListItem(TRUE, $mock_account),
'field_2' => $this->createMockFieldListItem(FALSE, $mock_account),
);
];
$content_entity_mock = $this->createMockForContentEntity($definitions);
$normalized = $this->contentEntityNormalizer->normalize($content_entity_mock, 'test_format', $context);
@ -121,7 +121,7 @@ class ContentEntityNormalizerTest extends UnitTestCase {
public function createMockForContentEntity($definitions) {
$content_entity_mock = $this->getMockBuilder('Drupal\Core\Entity\ContentEntityBase')
->disableOriginalConstructor()
->setMethods(array('getFields'))
->setMethods(['getFields'])
->getMockForAbstractClass();
$content_entity_mock->expects($this->once())
->method('getFields')

View file

@ -2,8 +2,11 @@
namespace Drupal\Tests\serialization\Unit\Normalizer;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\serialization\Normalizer\EntityNormalizer;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
* @coversDefaultClass \Drupal\serialization\Normalizer\EntityNormalizer
@ -49,14 +52,14 @@ class EntityNormalizerTest extends UnitTestCase {
$list_item_1 = $this->getMock('Drupal\Core\TypedData\TypedDataInterface');
$list_item_2 = $this->getMock('Drupal\Core\TypedData\TypedDataInterface');
$definitions = array(
$definitions = [
'field_1' => $list_item_1,
'field_2' => $list_item_2,
);
];
$content_entity = $this->getMockBuilder('Drupal\Core\Entity\ContentEntityBase')
->disableOriginalConstructor()
->setMethods(array('getFields'))
->setMethods(['getFields'])
->getMockForAbstractClass();
$content_entity->expects($this->once())
->method('getFields')
@ -64,7 +67,7 @@ class EntityNormalizerTest extends UnitTestCase {
$serializer = $this->getMockBuilder('Symfony\Component\Serializer\Serializer')
->disableOriginalConstructor()
->setMethods(array('normalize'))
->setMethods(['normalize'])
->getMock();
$serializer->expects($this->at(0))
->method('normalize')
@ -82,11 +85,10 @@ class EntityNormalizerTest extends UnitTestCase {
* Tests the denormalize() method with no entity type provided in context.
*
* @covers ::denormalize
*
* @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
*/
public function testDenormalizeWithNoEntityType() {
$this->entityNormalizer->denormalize(array(), 'Drupal\Core\Entity\ContentEntityBase');
$this->setExpectedException(UnexpectedValueException::class);
$this->entityNormalizer->denormalize([], 'Drupal\Core\Entity\ContentEntityBase');
}
/**
@ -104,6 +106,10 @@ class EntityNormalizerTest extends UnitTestCase {
];
$entity_type = $this->getMock('Drupal\Core\Entity\EntityTypeInterface');
$entity_type->expects($this->once())
->method('id')
->willReturn('test');
$entity_type->expects($this->once())
->method('hasKey')
->with('bundle')
@ -112,6 +118,11 @@ class EntityNormalizerTest extends UnitTestCase {
->method('getKey')
->with('bundle')
->will($this->returnValue('test_type'));
$entity_type->expects($this->once())
->method('isSubClassOf')
->with(FieldableEntityInterface::class)
->willReturn(TRUE);
$entity_type->expects($this->once())
->method('getBundleEntityType')
->will($this->returnValue('test_bundle'));
@ -154,32 +165,56 @@ class EntityNormalizerTest extends UnitTestCase {
->with('test_bundle')
->will($this->returnValue($entity_type_storage));
// The expected test data should have a modified test_type property.
$expected_test_data = array(
'key_1' => 'value_1',
'key_2' => 'value_2',
'test_type' => 'test_bundle',
);
$key_1 = $this->getMock(FieldItemListInterface::class);
$key_2 = $this->getMock(FieldItemListInterface::class);
$entity = $this->getMock(FieldableEntityInterface::class);
$entity->expects($this->at(0))
->method('get')
->with('key_1')
->willReturn($key_1);
$entity->expects($this->at(1))
->method('get')
->with('key_2')
->willReturn($key_2);
$storage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
// Create should only be called with the bundle property at first.
$expected_test_data = [
'test_type' => 'test_bundle',
];
$storage->expects($this->once())
->method('create')
->with($expected_test_data)
->will($this->returnValue($this->getMock('Drupal\Core\Entity\EntityInterface')));
->will($this->returnValue($entity));
$this->entityManager->expects($this->at(3))
->method('getStorage')
->with('test')
->will($this->returnValue($storage));
// Setup expectations for the serializer. This will be called for each field
// item.
$serializer = $this->getMockBuilder('Symfony\Component\Serializer\Serializer')
->disableOriginalConstructor()
->setMethods(['denormalize'])
->getMock();
$serializer->expects($this->at(0))
->method('denormalize')
->with('value_1', get_class($key_1), NULL, ['target_instance' => $key_1, 'entity_type' => 'test']);
$serializer->expects($this->at(1))
->method('denormalize')
->with('value_2', get_class($key_2), NULL, ['target_instance' => $key_2, 'entity_type' => 'test']);
$this->entityNormalizer->setSerializer($serializer);
$this->assertNotNull($this->entityNormalizer->denormalize($test_data, 'Drupal\Core\Entity\ContentEntityBase', NULL, ['entity_type' => 'test']));
}
/**
* Tests the denormalize method with a bundle property.
*
* @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
*
* @covers ::denormalize
*/
public function testDenormalizeWithInvalidBundle() {
@ -192,6 +227,10 @@ class EntityNormalizerTest extends UnitTestCase {
];
$entity_type = $this->getMock('Drupal\Core\Entity\EntityTypeInterface');
$entity_type->expects($this->once())
->method('id')
->willReturn('test');
$entity_type->expects($this->once())
->method('hasKey')
->with('bundle')
@ -200,6 +239,11 @@ class EntityNormalizerTest extends UnitTestCase {
->method('getKey')
->with('bundle')
->will($this->returnValue('test_type'));
$entity_type->expects($this->once())
->method('isSubClassOf')
->with(FieldableEntityInterface::class)
->willReturn(TRUE);
$entity_type->expects($this->once())
->method('getBundleEntityType')
->will($this->returnValue('test_bundle'));
@ -242,7 +286,7 @@ class EntityNormalizerTest extends UnitTestCase {
->with('test_bundle')
->will($this->returnValue($entity_type_storage));
$this->setExpectedException(UnexpectedValueException::class);
$this->entityNormalizer->denormalize($test_data, 'Drupal\Core\Entity\ContentEntityBase', NULL, ['entity_type' => 'test']);
}
@ -252,10 +296,10 @@ class EntityNormalizerTest extends UnitTestCase {
* @covers ::denormalize
*/
public function testDenormalizeWithNoBundle() {
$test_data = array(
$test_data = [
'key_1' => 'value_1',
'key_2' => 'value_2',
);
];
$entity_type = $this->getMock('Drupal\Core\Entity\EntityTypeInterface');
$entity_type->expects($this->once())
@ -284,7 +328,7 @@ class EntityNormalizerTest extends UnitTestCase {
$this->entityManager->expects($this->never())
->method('getBaseFieldDefinitions');
$this->assertNotNull($this->entityNormalizer->denormalize($test_data, 'Drupal\Core\Entity\ContentEntityBase', NULL, array('entity_type' => 'test')));
$this->assertNotNull($this->entityNormalizer->denormalize($test_data, 'Drupal\Core\Entity\ContentEntityBase', NULL, ['entity_type' => 'test']));
}
}

View file

@ -34,7 +34,7 @@ class ListNormalizerTest extends UnitTestCase {
*
* @var array
*/
protected $expectedListValues = array('test', 'test', 'test');
protected $expectedListValues = ['test', 'test', 'test'];
/**
* The mocked typed data.
@ -54,7 +54,7 @@ class ListNormalizerTest extends UnitTestCase {
// Set up a mock container as ItemList() will call for the 'typed_data_manager'
// service.
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')
->setMethods(array('get'))
->setMethods(['get'])
->getMock();
$container->expects($this->any())
->method('get')

View file

@ -45,20 +45,20 @@ class NormalizerBaseTest extends UnitTestCase {
* An array of provider data for testSupportsNormalization.
*/
public function providerTestSupportsNormalization() {
return array(
return [
// Something that is not an object should return FALSE immediately.
array(FALSE, array()),
[FALSE, []],
// An object with no class set should return FALSE.
array(FALSE, new \stdClass()),
[FALSE, new \stdClass()],
// Set a supported Class.
array(TRUE, new \stdClass(), 'stdClass'),
[TRUE, new \stdClass(), 'stdClass'],
// Set a supported interface.
array(TRUE, new \RecursiveArrayIterator(), 'RecursiveIterator'),
[TRUE, new \RecursiveArrayIterator(), 'RecursiveIterator'],
// Set a different class.
array(FALSE, new \stdClass(), 'ArrayIterator'),
[FALSE, new \stdClass(), 'ArrayIterator'],
// Set a different interface.
array(FALSE, new \stdClass(), 'RecursiveIterator'),
);
[FALSE, new \stdClass(), 'RecursiveIterator'],
];
}
}

View file

@ -0,0 +1,101 @@
<?php
namespace Drupal\Tests\serialization\Unit\Normalizer;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\Plugin\DataType\BooleanData;
use Drupal\Core\TypedData\Plugin\DataType\IntegerData;
use Drupal\Core\TypedData\Plugin\DataType\StringData;
use Drupal\Tests\UnitTestCase;
use Drupal\serialization\Normalizer\PrimitiveDataNormalizer;
/**
* @coversDefaultClass \Drupal\serialization\Normalizer\PrimitiveDataNormalizer
* @group serialization
*/
class PrimitiveDataNormalizerTest extends UnitTestCase {
/**
* The TypedDataNormalizer instance.
*
* @var \Drupal\serialization\Normalizer\TypedDataNormalizer
*/
protected $normalizer;
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->normalizer = new PrimitiveDataNormalizer();
}
/**
* @covers ::supportsNormalization
* @dataProvider dataProviderPrimitiveData
*/
public function testSupportsNormalization($primitive_data, $expected) {
$this->assertTrue($this->normalizer->supportsNormalization($primitive_data));
}
/**
* @covers ::supportsNormalization
*/
public function testSupportsNormalizationFail() {
// Test that an object not implementing PrimitiveInterface fails.
$this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
}
/**
* @covers ::normalize
* @dataProvider dataProviderPrimitiveData
*/
public function testNormalize($primitive_data, $expected) {
$this->assertSame($expected, $this->normalizer->normalize($primitive_data));
}
/**
* Data provider for testNormalize().
*/
public function dataProviderPrimitiveData() {
$data = [];
$definition = DataDefinition::createFromDataType('string');
$string = new StringData($definition, 'string');
$string->setValue('test');
$data['string'] = [$string, 'test'];
$definition = DataDefinition::createFromDataType('string');
$string = new StringData($definition, 'string');
$string->setValue(NULL);
$data['string-null'] = [$string, NULL];
$definition = DataDefinition::createFromDataType('integer');
$integer = new IntegerData($definition, 'integer');
$integer->setValue(5);
$data['integer'] = [$integer, 5];
$definition = DataDefinition::createFromDataType('integer');
$integer = new IntegerData($definition, 'integer');
$integer->setValue(NULL);
$data['integer-null'] = [$integer, NULL];
$definition = DataDefinition::createFromDataType('boolean');
$boolean = new BooleanData($definition, 'boolean');
$boolean->setValue(TRUE);
$data['boolean'] = [$boolean, TRUE];
$definition = DataDefinition::createFromDataType('boolean');
$boolean = new BooleanData($definition, 'boolean');
$boolean->setValue(NULL);
$data['boolean-null'] = [$boolean, NULL];
return $data;
}
}