class TimestampNormalizerTest

Same name in other branches
  1. 9 core/modules/serialization/tests/src/Unit/Normalizer/TimestampNormalizerTest.php \Drupal\Tests\serialization\Unit\Normalizer\TimestampNormalizerTest
  2. 8.9.x core/modules/serialization/tests/src/Unit/Normalizer/TimestampNormalizerTest.php \Drupal\Tests\serialization\Unit\Normalizer\TimestampNormalizerTest
  3. 10 core/modules/serialization/tests/src/Unit/Normalizer/TimestampNormalizerTest.php \Drupal\Tests\serialization\Unit\Normalizer\TimestampNormalizerTest

Unit test coverage for the "Timestamp" @DataType.

@group serialization @coversDefaultClass \Drupal\serialization\Normalizer\TimestampNormalizer

Hierarchy

Expanded class hierarchy of TimestampNormalizerTest

See also

\Drupal\Core\TypedData\Plugin\DataType\Timestamp

File

core/modules/serialization/tests/src/Unit/Normalizer/TimestampNormalizerTest.php, line 24

Namespace

Drupal\Tests\serialization\Unit\Normalizer
View source
class TimestampNormalizerTest extends UnitTestCase {
    use JsonSchemaTestTrait;
    
    /**
     * The tested data type's normalizer.
     *
     * @var \Drupal\serialization\Normalizer\TimestampNormalizer
     */
    protected $normalizer;
    
    /**
     * The tested data type.
     *
     * @var \Drupal\Core\Field\Plugin\Field\FieldType\TimestampItem
     */
    protected $data;
    
    /**
     * {@inheritdoc}
     */
    protected function setUp() : void {
        parent::setUp();
        $this->normalizer = new TimestampNormalizer($this->prophesize(ConfigFactoryInterface::class)
            ->reveal());
        $this->data = $this->prophesize(Timestamp::class);
    }
    
    /**
     * @covers ::supportsNormalization
     */
    public function testSupportsNormalization() : void {
        $this->assertTrue($this->normalizer
            ->supportsNormalization($this->data
            ->reveal()));
        $integer = $this->prophesize(IntegerData::class);
        $this->assertFalse($this->normalizer
            ->supportsNormalization($integer->reveal()));
        $datetime = $this->prophesize(DateTimeInterface::class);
        $this->assertFalse($this->normalizer
            ->supportsNormalization($datetime->reveal()));
    }
    
    /**
     * @covers ::supportsDenormalization
     */
    public function testSupportsDenormalization() : void {
        $this->assertTrue($this->normalizer
            ->supportsDenormalization($this->data
            ->reveal(), Timestamp::class));
    }
    
    /**
     * @covers ::normalize
     */
    public function testNormalize() : void {
        $random_rfc_3339_string = $this->randomMachineName();
        $drupal_date_time = $this->prophesize(TimestampNormalizerTestDrupalDateTime::class);
        $drupal_date_time->setTimezone(new \DateTimeZone('UTC'))
            ->willReturn($drupal_date_time->reveal());
        $drupal_date_time->format(\DateTime::RFC3339)
            ->willReturn($random_rfc_3339_string);
        $this->data
            ->getDateTime()
            ->willReturn($drupal_date_time->reveal());
        $normalized = $this->normalizer
            ->normalize($this->data
            ->reveal());
        $this->assertSame($random_rfc_3339_string, $normalized);
    }
    
    /**
     * Tests the denormalize function with good data.
     *
     * @covers ::denormalize
     * @dataProvider providerTestDenormalizeValidFormats
     */
    public function testDenormalizeValidFormats($normalized, $expected) : void {
        $denormalized = $this->normalizer
            ->denormalize($normalized, Timestamp::class, NULL, []);
        $this->assertSame($expected, $denormalized);
    }
    
    /**
     * Data provider for testDenormalizeValidFormats.
     *
     * @return array
     *   An array of test data.
     */
    public static function providerTestDenormalizeValidFormats() {
        $expected_stamp = 1478422920;
        $data = [];
        $data['U'] = [
            $expected_stamp,
            $expected_stamp,
        ];
        $data['RFC3339'] = [
            '2016-11-06T09:02:00+00:00',
            $expected_stamp,
        ];
        $data['RFC3339 +0100'] = [
            '2016-11-06T09:02:00+01:00',
            $expected_stamp - 1 * 3600,
        ];
        $data['RFC3339 -0600'] = [
            '2016-11-06T09:02:00-06:00',
            $expected_stamp + 6 * 3600,
        ];
        $data['ISO8601'] = [
            '2016-11-06T09:02:00+0000',
            $expected_stamp,
        ];
        $data['ISO8601 +0100'] = [
            '2016-11-06T09:02:00+0100',
            $expected_stamp - 1 * 3600,
        ];
        $data['ISO8601 -0600'] = [
            '2016-11-06T09:02:00-0600',
            $expected_stamp + 6 * 3600,
        ];
        return $data;
    }
    
    /**
     * Tests the denormalize function with bad data.
     *
     * @covers ::denormalize
     */
    public function testDenormalizeException() : void {
        $this->expectException(UnexpectedValueException::class);
        $this->expectExceptionMessage('The specified date "2016/11/06 09:02am GMT" is not in an accepted format: "U" (UNIX timestamp), "Y-m-d\\TH:i:sO" (ISO 8601), "Y-m-d\\TH:i:sP" (RFC 3339).');
        $normalized = '2016/11/06 09:02am GMT';
        $this->normalizer
            ->denormalize($normalized, Timestamp::class, NULL, []);
    }
    
    /**
     * {@inheritdoc}
     */
    public static function jsonSchemaDataProvider() : array {
        $case = function (UnitTestCase $test) {
            assert(in_array(JsonSchemaTestTrait::class, class_uses($test)));
            $drupal_date_time = $test->doProphesize(TimestampNormalizerTestDrupalDateTime::class);
            $drupal_date_time->setTimezone(new \DateTimeZone('UTC'))
                ->willReturn($drupal_date_time->reveal());
            $drupal_date_time->format(\DateTime::RFC3339)
                ->willReturn('1983-07-12T09:05:00-05:00');
            $data = $test->doProphesize(Timestamp::class);
            $data->getDateTime()
                ->willReturn($drupal_date_time->reveal());
            return $data->reveal();
        };
        return [
            'RFC 3339' => [
                fn(UnitTestCase $test) => $case($test),
            ],
        ];
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
ExpectDeprecationTrait::expectDeprecation public function Adds an expected deprecation.
ExpectDeprecationTrait::setUpErrorHandler public function Sets up the test error handler.
ExpectDeprecationTrait::tearDownErrorHandler public function Tears down the test error handler.
JsonSchemaTestTrait::doCheckSchemaAgainstMetaSchema protected function Check a schema is valid against the meta-schema.
JsonSchemaTestTrait::doProphesize public function Method to make prophecy public for use in data provider closures.
JsonSchemaTestTrait::doTestJsonSchemaIsValid public function Validate the normalizer's JSON schema.
JsonSchemaTestTrait::getJsonSchemaTestNormalizationFormat protected function Format that should be used when performing test normalizations. 1
JsonSchemaTestTrait::getNormalizationForValue protected function Get the normalization for a value.
JsonSchemaTestTrait::getNormalizer protected function Helper method to retrieve the normalizer. 1
JsonSchemaTestTrait::getValidator protected function Get the JSON Schema Validator. 1
JsonSchemaTestTrait::supportedTypesDataProvider public static function
JsonSchemaTestTrait::testNormalizedValuesAgainstJsonSchema public function Test normalized values against the JSON schema.
JsonSchemaTestTrait::testSupportedTypesSchemaIsValid public function Test that a valid schema is returned for the explicitly supported types.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
TimestampNormalizerTest::$data protected property The tested data type.
TimestampNormalizerTest::$normalizer protected property The tested data type's normalizer.
TimestampNormalizerTest::jsonSchemaDataProvider public static function Overrides JsonSchemaTestTrait::jsonSchemaDataProvider
TimestampNormalizerTest::providerTestDenormalizeValidFormats public static function Data provider for testDenormalizeValidFormats.
TimestampNormalizerTest::setUp protected function Overrides UnitTestCase::setUp
TimestampNormalizerTest::testDenormalizeException public function Tests the denormalize function with bad data.
TimestampNormalizerTest::testDenormalizeValidFormats public function Tests the denormalize function with good data.
TimestampNormalizerTest::testNormalize public function @covers ::normalize
TimestampNormalizerTest::testSupportsDenormalization public function @covers ::supportsDenormalization
TimestampNormalizerTest::testSupportsNormalization public function @covers ::supportsNormalization
UnitTestCase::$root protected property The app root.
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::setDebugDumpHandler public static function Registers the dumper CLI handler when the DebugDump extension is enabled.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.