HummingBirdAnimeClient/tests/Ion/JsonTest.php

89 lines
2.1 KiB
PHP
Raw Permalink Normal View History

<?php declare(strict_types=1);
/**
2020-03-12 11:45:11 -04:00
* Hummingbird Anime List Client
*
2020-03-12 11:45:11 -04:00
* An API client for Kitsu to manage anime and manga watch lists
*
2023-07-13 11:08:05 -04:00
* PHP version 8.1
*
2023-07-13 11:08:05 -04:00
* @copyright 2015 - 2023 Timothy J. Warren <tim@timshome.page>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
2020-12-10 17:06:50 -05:00
* @version 5.2
2023-07-13 11:08:05 -04:00
* @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\Ion\Tests;
use Aviat\Ion\{Json, JsonException};
2022-03-04 12:19:47 -05:00
use function Aviat\Ion\_dir;
2022-03-04 12:19:47 -05:00
/**
* @internal
*/
final class JsonTest extends IonTestCase
{
public function testEncode()
{
$data = (object) [
2022-03-04 12:19:47 -05:00
'foo' => [1, 2, 3, 4],
];
$expected = '{"foo":[1,2,3,4]}';
2022-03-04 12:19:47 -05:00
$this->assertSame($expected, Json::encode($data));
}
2023-05-09 12:46:52 -04:00
public static function dataEncodeDecode(): array
{
return [
'set1' => [
'data' => [
'apple' => [
2022-03-04 12:19:47 -05:00
'sauce' => ['foo', 'bar', 'baz'],
],
],
'expected_size' => 39,
2022-03-04 12:19:47 -05:00
'expected_json' => '{"apple":{"sauce":["foo","bar","baz"]}}',
],
];
}
2023-05-09 12:46:52 -04:00
#[\PHPUnit\Framework\Attributes\DataProvider('dataEncodeDecode')]
public function testEncodeDecodeFile(array $data, int $expected_size, string $expected_json): void
{
$target_file = _dir(self::TEST_DATA_DIR, 'json_write.json');
2023-05-09 12:46:52 -04:00
$actual_size = Json::encodeFile($target_file, $data);
$actual_json = file_get_contents($target_file);
2023-05-09 12:46:52 -04:00
$this->assertTrue(Json::isJson($actual_json));
$this->assertSame($expected_size, $actual_size);
$this->assertSame($expected_json, $actual_json);
2023-05-09 12:46:52 -04:00
$this->assertEquals($data, Json::decodeFile($target_file));
2023-05-09 12:46:52 -04:00
unlink($target_file);
}
public function testDecode()
{
$json = '{"foo":[1,2,3,4]}';
$expected = [
2022-03-04 12:19:47 -05:00
'foo' => [1, 2, 3, 4],
];
2022-03-04 12:19:47 -05:00
$this->assertSame($expected, Json::decode($json));
$this->assertEquals((object) $expected, Json::decode($json, FALSE));
$badJson = '{foo:{1|2}}';
2023-05-19 10:56:23 -04:00
$this->expectException(\Aviat\Ion\JsonException::class);
$this->expectExceptionMessage('JSON_ERROR_SYNTAX - Syntax error');
$this->expectExceptionCode(JSON_ERROR_SYNTAX);
Json::decode($badJson);
}
public function testDecodeNull()
{
$this->assertNull(Json::decode(NULL));
}
2022-03-04 12:19:47 -05:00
}