Repository navigation
Expand file tree
/
Copy pathJsonTest.php
More file actions
109 lines (94 loc) · 2.78 KB
/
Copy pathJsonTest.php
File metadata and controls
109 lines (94 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace HyperfTest\Codec;
use Hyperf\Codec\Exception\InvalidArgumentException;
use Hyperf\Codec\Json;
use HyperfTest\Codec\Stub\Car;
use HyperfTest\Codec\Stub\StringCodeException;
use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\TestCase;
use Throwable;
use function Hyperf\Coroutine\go;
/**
* @internal
* @coversNothing
*/
#[CoversNothing]
class JsonTest extends TestCase
{
public function testEncode()
{
$data = [
'name' => 'Hyperf',
];
$json = '{"name":"Hyperf"}';
$this->assertSame($json, Json::encode($data));
}
public function testDecode()
{
$data = [
'name' => 'Hyperf',
];
$json = '{"name":"Hyperf"}';
$this->assertSame($data, Json::decode($json));
}
public function testDecodeToObject()
{
$data = [
'name' => 'Hyperf',
];
$json = '{"name":"Hyperf"}';
$this->assertEquals((object) $data, Json::decode($json, false));
}
public function testDecodeException()
{
$json = '{"name":"Hyperf}';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Control character error, possibly incorrectly encoded');
Json::decode($json);
}
public function testEncodeException()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Type is not supported');
Json::encode(fopen('php://temp', 'r+'));
}
public function testJsonEncodeInCoroutine()
{
$result = null;
go(function () use (&$result) {
$result = Json::encode([1, 2, 3]);
});
$this->assertSame('[1,2,3]', $result);
go(function () use (&$result) {
$result = Json::decode('[1,2,3]');
});
$this->assertSame([1, 2, 3], $result);
}
public function testJsonEncodeNull()
{
$res = Json::encode(null);
$this->assertSame('null', $res);
$this->assertSame(null, Json::decode('null'));
}
public function testJsonExceptionWhichCodeIsString()
{
try {
Json::encode(new Car());
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
$this->assertSame(0, $exception->getCode());
$previous = $exception->getPrevious();
$this->assertInstanceOf(StringCodeException::class, $previous);
$this->assertSame('A0001', $previous->getCode());
}
}
}