View source
<?php
namespace Drupal\Tests\Component\Serialization;
use Drupal\Component\Serialization\Json;
use PHPUnit\Framework\TestCase;
class JsonTest extends TestCase {
protected $string;
protected $htmlUnsafe;
protected $htmlUnsafeEscaped;
protected function setUp() : void {
parent::setUp();
$this->string = '';
for ($i = 1; $i < 128; $i++) {
$this->string .= chr($i);
}
$this->htmlUnsafe = [
'<',
'>',
'\'',
'&',
];
$this->htmlUnsafeEscaped = [
'\\u003C',
'\\u003E',
'\\u0027',
'\\u0026',
'\\u0022',
];
}
public function testEncodingAscii() {
$this
->assertSame(127, strlen($this->string), 'A string with the full ASCII table has the correct length.');
foreach ($this->htmlUnsafe as $char) {
$this
->assertStringContainsString($char, $this->string, sprintf('A string with the full ASCII table includes %s.', $char));
}
}
public function testEncodingLength() {
$json = Json::encode($this->string);
$this
->assertGreaterThan(strlen($this->string), strlen($json));
}
public function testEncodingStartEnd() {
$json = Json::encode($this->string);
$this
->assertStringStartsWith('"', $json, 'A JSON encoded string begins with ".');
$this
->assertStringEndsWith('"', $json, 'A JSON encoded string ends with ".');
$this
->assertSame(2, substr_count($json, '"'), 'A JSON encoded string contains exactly two ".');
}
public function testReversibility() {
$json = Json::encode($this->string);
$json_decoded = Json::decode($json);
$this
->assertSame($this->string, $json_decoded, 'Encoding a string to JSON and decoding back results in the original string.');
}
public function testStructuredReversibility() {
$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));
}
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.');
}
}