You are here

public function JsonTest::testStructuredReversibility in Drupal 10

Same name and namespace in other branches
  1. 8 core/tests/Drupal/Tests/Component/Serialization/JsonTest.php \Drupal\Tests\Component\Serialization\JsonTest::testStructuredReversibility()
  2. 9 core/tests/Drupal/Tests/Component/Serialization/JsonTest.php \Drupal\Tests\Component\Serialization\JsonTest::testStructuredReversibility()

Tests the reversibility of structured data.

File

core/tests/Drupal/Tests/Component/Serialization/JsonTest.php, line 100

Class

JsonTest
@coversDefaultClass \Drupal\Component\Serialization\Json @group Serialization

Namespace

Drupal\Tests\Component\Serialization

Code

public function testStructuredReversibility() {

  // Verify reversibility for structured data. Also verify that necessary
  // characters are escaped.
  $source = [
    TRUE,
    FALSE,
    0,
    1,
    '0',
    '1',
    $this->string,
    [
      'key1' => $this->string,
      'key2' => [
        'nested' => TRUE,
      ],
    ],
  ];
  $json = Json::encode($source);
  foreach ($this->htmlUnsafe as $char) {
    $this
      ->assertStringNotContainsString($char, $json, sprintf('A JSON encoded string does not contain %s.', $char));
  }

  // Verify that JSON encoding escapes the HTML unsafe characters
  foreach ($this->htmlUnsafeEscaped as $char) {
    $this
      ->assertStringContainsString($char, $json, sprintf('A JSON encoded string contains %s.', $char));
  }
  $json_decoded = Json::decode($json);
  $this
    ->assertNotSame($source, $json, 'An array encoded in JSON is identical to the source.');
  $this
    ->assertSame($source, $json_decoded, 'Encoding structured data to JSON and decoding back not results in the original data.');
}