Merge "Type hint against LinkTarget in WatchedItemStore"
[lhc/web/wiklou.git] / tests / phpunit / unit / includes / utils / AvroValidatorTest.php
1 <?php
2 /**
3 * Tests for IP validity functions.
4 *
5 * Ported from /t/inc/IP.t by avar.
6 *
7 * @todo Test methods in this call should be split into a method and a
8 * dataprovider.
9 */
10
11 /**
12 * @group IP
13 * @covers AvroValidator
14 */
15 class AvroValidatorTest extends MediaWikiUnitTestCase {
16
17 public function setUp() {
18 if ( !class_exists( 'AvroSchema' ) ) {
19 $this->markTestSkipped( 'Avro is required to run the AvroValidatorTest' );
20 }
21 parent::setUp();
22 }
23
24 public function getErrorsProvider() {
25 $stringSchema = AvroSchema::parse( json_encode( [ 'type' => 'string' ] ) );
26 $stringArraySchema = AvroSchema::parse( json_encode( [
27 'type' => 'array',
28 'items' => 'string',
29 ] ) );
30 $recordSchema = AvroSchema::parse( json_encode( [
31 'type' => 'record',
32 'name' => 'ut',
33 'fields' => [
34 [ 'name' => 'id', 'type' => 'int', 'required' => true ],
35 ],
36 ] ) );
37 $enumSchema = AvroSchema::parse( json_encode( [
38 'type' => 'record',
39 'name' => 'ut',
40 'fields' => [
41 [ 'name' => 'count', 'type' => [ 'int', 'null' ] ],
42 ],
43 ] ) );
44
45 return [
46 [
47 'No errors with a simple string serialization',
48 $stringSchema, 'foobar', [],
49 ],
50
51 [
52 'Cannot serialize integer into string',
53 $stringSchema, 5, 'Expected string, but recieved integer',
54 ],
55
56 [
57 'Cannot serialize array into string',
58 $stringSchema, [], 'Expected string, but recieved array',
59 ],
60
61 [
62 'allows and ignores extra fields',
63 $recordSchema, [ 'id' => 4, 'foo' => 'bar' ], [],
64 ],
65
66 [
67 'detects missing fields',
68 $recordSchema, [], [ 'id' => 'Missing expected field' ],
69 ],
70
71 [
72 'handles first element in enum',
73 $enumSchema, [ 'count' => 4 ], [],
74 ],
75
76 [
77 'handles second element in enum',
78 $enumSchema, [ 'count' => null ], [],
79 ],
80
81 [
82 'rejects element not in union',
83 $enumSchema, [ 'count' => 'invalid' ], [ 'count' => [
84 'Expected any one of these to be true',
85 [
86 'Expected integer, but recieved string',
87 'Expected null, but recieved string',
88 ]
89 ] ]
90 ],
91 [
92 'Empty array is accepted',
93 $stringArraySchema, [], []
94 ],
95 [
96 'correct array element accepted',
97 $stringArraySchema, [ 'fizzbuzz' ], []
98 ],
99 [
100 'incorrect array element rejected',
101 $stringArraySchema, [ '12', 34 ], [ 'Expected string, but recieved integer' ]
102 ],
103 ];
104 }
105
106 /**
107 * @dataProvider getErrorsProvider
108 */
109 public function testGetErrors( $message, $schema, $datum, $expected ) {
110 $this->assertEquals(
111 $expected,
112 AvroValidator::getErrors( $schema, $datum ),
113 $message
114 );
115 }
116 }