-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSchemaTest.php
143 lines (124 loc) · 3.24 KB
/
SchemaTest.php
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<?php
use North\Schema\Schema;
use PHPUnit\Framework\TestCase;
interface Stringable
{
public function string();
}
class Person implements Stringable
{
public $name = '';
public function __construct($o)
{
foreach ($o as $k => $v) {
$this->$k = $v;
}
}
public function string()
{
return $this->name;
}
}
class SchemaTest extends TestCase
{
public function testSchema()
{
$schema = new Schema([
'name' => 'string',
'age' => 'integer',
'item' => [
'id' => 'int',
'name' => 'is_string',
],
'is_admin' => 'boolean?',
'md5' => function ($value) {
return is_string($value) && preg_match('/^[a-f0-9]{32}$/', $value);
},
'names' => ['string'],
'objs' => [
[
'name' => 'string',
'age' => 'int',
],
],
'func' => 'function',
'closure' => 'closure',
'person' => 'type:Person',
'implements' => 'implements:Stringable',
'defaults' => [
'name' => 'string',
'age' => 'integer',
],
], [
'defaults' => [
'name' => 'default',
'age' => 27,
],
]);
$schema->addType('exact', function ($t, $v) {
return $t === $v;
});
$schema->addSchema([
'item' => [
'exact' => 'exact:test'
],
]);
$this->assertTrue($schema->valid([
'name' => 'jimmy',
'age' => 24,
'item' => [
'id' => 2,
'name' => 'Test',
'exact' => 'test',
],
'md5' => '5d41402abc4b2a76b9719d911017c592',
'names' => ['foo', 'bar', 'baz'],
'objs' => [
[
'name' => 'jimmy',
'age' => 24,
],
],
'func' => 'is_string',
'closure' => function ($x) {
},
'person' => new Person(['name' => 'Fredrik']),
'implements' => new Person(['name' => 'Fredrik']),
]));
}
public function testDefaultSchema()
{
$expected = [
'name' => 'jimmy',
'age' => 24,
];
$schema = new Schema([
'name' => 'string',
'age' => 'integer',
], $expected);
$this->assertSame($expected, $schema->resolve([
'name' => 'jimmy',
]));
}
public function testJsonSchema()
{
$schema = new Schema(__DIR__ . '/testdata/user.json');
$this->assertTrue($schema->valid([
'name' => 'jimmy',
'age' => 24,
]));
}
public function testEmptySchema()
{
$schema = new Schema;
$this->assertTrue($schema->valid([]));
}
public function testClassSchema()
{
$schema = new Schema([
'name' => 'string',
]);
$class = new Person(['name' => 'Fredrik']);
$this->assertTrue($schema->valid($class));
}
}