Debian Codegraph @

tests/phpunit/includes/libs/serialization/SerializationTestTrait.php

raw symbols SCIP
1 <?php
2
3 // phpcs:disable MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
4 // phpcs:disable MediaWiki.Commenting.FunctionComment.MissingParamTag -- Traits are not excluded
5
6 namespace Wikimedia\Tests;
7
8 use Generator;
9 use ReflectionClass;
10
11 trait SerializationTestTrait {
12
13 /**
14 * Data provider for deserialization test.
15 * - For each supported serialization format defined by ::getSupportedSerializationFormats
16 * - For each acceptance test instance defined by ::getTestInstancesAndAssertions
17 * - For each object deserialized from stored file for a particular MW version
18 * @return Generator for [ callable $deserializer, object $expectedObject, string $dataToDeserialize ]
19 */
20 public function provideTestDeserialization(): Generator {
21 // Creation of dynamic property is deprecated, can happen as backward-compatibility check
22 $this->markTestSkippedIfPhp( '>=', '8.2' );
23
24 $className = self::getClassToTest();
25 foreach ( self::getSupportedSerializationFormats() as $serializationFormat ) {
26 $serializationUtils = new SerializationTestUtils(
27 self::getSerializedDataPath(),
28 self::getTestInstances( self::getTestInstancesAndAssertions() ),
29 $serializationFormat['ext'],
30 $serializationFormat['serializer'],
31 $serializationFormat['deserializer']
32 );
33 foreach ( $serializationUtils->getTestInstances() as $testCaseName => $expectedObject ) {
34 $deserializationFixtures = $serializationUtils->getFixturesForTestCase(
35 $className,
36 $testCaseName
37 );
38 foreach ( $deserializationFixtures as $deserializedObjectInfo ) {
39 yield "{$className}:{$testCaseName}, " .
40 "deserialized from {$deserializedObjectInfo->ext}, " .
41 "{$deserializedObjectInfo->version}" =>
42 [ $serializationFormat['deserializer'], $expectedObject, $deserializedObjectInfo->data ];
43 }
44 }
45 }
46 }
47
48 /**
49 * Tests that $deserialized objects retrieved from stored files for various MW versions
50 * equal to the $expected
51 * @dataProvider provideTestDeserialization
52 */
53 public function testDeserialization( callable $deserializer, object $expected, string $data ) {
54 $deserialized = $deserializer( $data );
55 $this->assertInstanceOf( self::getClassToTest(), $deserialized );
56 $this->validateObjectEquality( $expected, $deserialized );
57 }
58
59 /**
60 * Data provider for serialization test.
61 * - For each supported serialization format defined by ::getSupportedSerializationFormats
62 * - For each acceptance test instance defined by ::getTestInstancesAndAssertions
63 * @return Generator for [ callable $serializer, string $expectedSerialization, object $testInstanceToSerialize ]
64 */
65 public function provideSerialization(): Generator {
66 // Creation of dynamic property is deprecated, can happen as backward-compatibility check
67 $this->markTestSkippedIfPhp( '>=', '8.2' );
68
69 $className = self::getClassToTest();
70 foreach ( self::getSupportedSerializationFormats() as $serializationFormat ) {
71 $serializationUtils = new SerializationTestUtils(
72 self::getSerializedDataPath(),
73 self::getTestInstances( self::getTestInstancesAndAssertions() ),
74 $serializationFormat['ext'],
75 $serializationFormat['serializer'],
76 $serializationFormat['deserializer']
77 );
78 foreach ( $serializationUtils->getTestInstances() as $testCaseName => $testInstance ) {
79 $expected = $serializationUtils->getStoredSerializedInstance( $className, $testCaseName );
80
81 if ( $expected->data === null ) {
82 // The fixture file is missing. This will be detected and reported elsewhere.
83 // No need to cause an error here.
84 continue;
85 }
86
87 yield "{$className}:{$testCaseName}, " .
88 "serialized with {$serializationFormat['ext']}" =>
89 [
90 $serializationFormat['serializer'],
91 $serializationFormat['deserializer'],
92 $expected->data,
93 $testInstance
94 ];
95 }
96 }
97 }
98
99 /**
100 * Test that the current master $serialized instances are
101 * equal to stored $expected instances.
102 * Serialization formats might change in backwards compatible ways
103 * (in particular, php 8.1 orders protected instance variables differently
104 * than earlier php), so do the comparision on the deserialized version.
105 * @dataProvider provideSerialization
106 */
107 public function testSerialization( callable $serializer, callable $deserializer, string $expected, object $testInstance ) {
108 $serTestInstance = $serializer( $testInstance );
109 $deserExpected = $deserializer( $expected );
110 $this->assertNotEmpty( $deserExpected );
111 $deserTestInstance = $deserializer( $serTestInstance );
112 $this->assertNotEmpty( $deserTestInstance );
113
114 $this->validateObjectEquality( $deserExpected, $deserTestInstance );
115 }
116
117 /**
118 * Data provider for serialization round trip test.
119 * - For each supported serialization format defined by ::getSupportedSerializationFormats
120 * - For each test instance defined by ::getTestInstances
121 * @return Generator for [ object $instance, callable $serializer, callable $deserializer ]
122 */
123 public static function provideSerializationRoundTrip(): Generator {
124 $testCases = self::getTestInstancesAndAssertions();
125 $className = self::getClassToTest();
126 foreach ( self::getSupportedSerializationFormats() as $serializationFormat ) {
127 foreach ( $testCases as $testCaseName => [ 'instance' => $instance ] ) {
128 yield "{$className}:{$testCaseName}, " .
129 "serialized with {$serializationFormat['ext']}" => [
130 $instance,
131 $serializationFormat['serializer'],
132 $serializationFormat['deserializer']
133 ];
134 }
135 }
136 }
137
138 /**
139 * Test that the $expected instance can be serialized and successfully be deserialized again.
140 *
141 * @dataProvider provideSerializationRoundTrip
142 */
143 public function testSerializationRoundTrip(
144 object $instance,
145 callable $serializer,
146 callable $deserializer
147 ) {
148 $blob = $serializer( $instance );
149 $this->assertNotEmpty( $blob );
150
151 $actual = $deserializer( $blob );
152 $this->assertNotEmpty( $actual );
153
154 $this->validateObjectEquality( $instance, $actual );
155 }
156
157 /**
158 * @param mixed $expected
159 * @param mixed $actual
160 * @param string|null $propName
161 */
162 private function validateArrayEquality( $expected, $actual, ?string $propName = null ) {
163 $this->assertIsArray( $actual, "$propName: Expected array." );
164 $eKeys = array_keys( $expected );
165 $aKeys = array_keys( $actual );
166 $this->assertSame( count( $eKeys ), count( $aKeys ), "$propName: Expected equal-sized arrays." );
167 $i = 0;
168 foreach ( $expected as $k => $v ) {
169 $this->validateEquality( $k, $aKeys[$i], "$propName:$i" );
170 $this->validateEquality( $v, $actual[$k], $k );
171 $i++;
172 }
173 }
174
175 /**
176 * @param mixed $expected
177 * @param mixed $actual
178 * @param string|null $propName
179 */
180 private function validateEquality( $expected, $actual, ?string $propName = null ) {
181 if ( is_array( $expected ) ) {
182 $this->validateArrayEquality( $expected, $actual, $propName );
183 } elseif ( is_object( $expected ) ) {
184 $this->assertIsObject( $actual, "Expected an object, but found: " . get_debug_type( $actual ) );
185 $this->validateObjectEquality( $expected, $actual );
186 } else {
187 $this->assertSame( $expected, $actual, $propName );
188 }
189 }
190
191 /**
192 * Asserts that all the fields across class hierarchy for
193 * provided objects are equal.
194 * @param object $expected
195 * @param object $actual
196 * @param ReflectionClass|null $class
197 */
198 private function validateObjectEquality(
199 object $expected,
200 object $actual,
201 ?ReflectionClass $class = null
202 ) {
203 if ( !$class ) {
204 $class = new ReflectionClass( $expected );
205 }
206
207 foreach ( $class->getProperties() as $prop ) {
208 $this->validateEquality(
209 $prop->getValue( $expected ),
210 $prop->getValue( $actual ),
211 $prop->getName()
212 );
213 }
214
215 $parent = $class->getParentClass();
216 if ( $parent ) {
217 $this->validateObjectEquality( $expected, $actual, $parent );
218 }
219 }
220
221 /**
222 * Data provider for acceptance testing, returning object instances created by current code.
223 * - For each acceptance test instance defined by ::getTestInstancesAndAssertions
224 * @return Generator for [ $instance which to run assertions on, $assertionsCallback ]
225 */
226 public static function provideCurrentVersionTestObjects(): Generator {
227 $className = self::getClassToTest();
228 $testCases = self::getTestInstancesAndAssertions();
229 foreach ( $testCases as $testCaseName => $testCase ) {
230 yield "{$className}:{$testCaseName}, current" =>
231 [ $testCase['instance'], $testCase['assertions'] ];
232 }
233 }
234
235 /**
236 * Data provider for acceptance testing, returning instances deserialized
237 * from stored files for various MW versions.
238 * - For each supported serialization format defined by ::getSupportedSerializationFormats
239 * - For each object deserialized from stored file for a particular MW version
240 * @return Generator for [ $instance which to run assertions on, $assertionsCallback ]
241 */
242 public function provideDeserializedTestObjects(): Generator {
243 // Creation of dynamic property is deprecated, can happen as backward-compatibility check
244 $this->markTestSkippedIfPhp( '>=', '8.2' );
245
246 $className = self::getClassToTest();
247 $testCases = self::getTestInstancesAndAssertions();
248 $testObjects = self::getTestInstances( $testCases );
249 foreach ( self::getSupportedSerializationFormats() as $serializationFormat ) {
250 $serializationUtils = new SerializationTestUtils(
251 self::getSerializedDataPath(),
252 $testObjects,
253 $serializationFormat['ext'],
254 $serializationFormat['serializer'],
255 $serializationFormat['deserializer']
256 );
257 foreach ( $testCases as $testCaseName => [ 'assertions' => $assertions ] ) {
258 $deserializedObjects = $serializationUtils->getDeserializedInstancesForTestCase(
259 $className,
260 $testCaseName
261 );
262 foreach ( $deserializedObjects as $deserializedObjectInfo ) {
263 yield "{$className}:{$testCaseName}, " .
264 "deserialized from {$deserializedObjectInfo->ext}, " .
265 "{$deserializedObjectInfo->version}" =>
266 [
267 $deserializedObjectInfo->object,
268 $assertions
269 ];
270 }
271 }
272 }
273 }
274
275 /**
276 * Tests that assertions in $assertionsCallback succeed on $testInstance.
277 * @see self::getTestInstancesAndAssertions()
278 * @dataProvider provideDeserializedTestObjects
279 * @dataProvider provideCurrentVersionTestObjects
280 */
281 public function testAcceptanceOfDeserializedInstances(
282 object $testInstance,
283 callable $assertionsCallback
284 ) {
285 call_user_func( $assertionsCallback, $this, $testInstance );
286 }
287
288 /**
289 * Returns a map of $testCaseName to an instance to test.
290 * @param array[] $instancesAndAssertions
291 * @return array
292 */
293 private static function getTestInstances( array $instancesAndAssertions ): array {
294 return array_map( static function ( $testCase ) {
295 return $testCase['instance'];
296 }, $instancesAndAssertions );
297 }
298
299 /**
300 * @return string the name of the class to test.
301 */
302 abstract public static function getClassToTest(): string;
303
304 /**
305 * @return string the path to serialized data.
306 */
307 abstract public static function getSerializedDataPath(): string;
308
309 /**
310 * @return array a map of $testCaseName to a map, containing the following keys:
311 * - 'instance' => an instance of the object to perform assertions on.
312 * - 'assertions' => a callable that performs assertions on the deserialized objects.
313 * Callable signature: ( MediaWikiIntegrationTestCase $testCase, object $instance )
314 */
315 abstract public static function getTestInstancesAndAssertions(): array;
316
317 /**
318 * Get a list of serialization formats supported by the tested class.
319 * @return string[][] a list of supported serialization formats info map,
320 * containing the following keys:
321 * - 'ext' => string file extension for stored serializations
322 * - 'serializer' => callable to serialize objects
323 * - 'deserializer' => callable to deserialize objects
324 */
325 abstract public static function getSupportedSerializationFormats(): array;
326 }