You are here

public function JsonTest::testStructuredReversibility in Zircon Profile 8

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

Test the reversibility of structured data

File

core/tests/Drupal/Tests/Component/Serialization/JsonTest.php, line 105
Contains \Drupal\Tests\Component\Serialization\JsonTest.

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 = array(
    TRUE,
    FALSE,
    0,
    1,
    '0',
    '1',
    $this->string,
    array(
      'key1' => $this->string,
      'key2' => array(
        'nested' => TRUE,
      ),
    ),
  );
  $json = Json::encode($source);
  foreach ($this->htmlUnsafe as $char) {
    $this
      ->assertTrue(strpos($json, $char) === FALSE, 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
      ->assertTrue(strpos($json, $char) > 0, 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.');
}