Debian Codegraph @

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

raw symbols SCIP
1 <?php
2
3 // phpcs:disable MediaWiki.Commenting.FunctionComment.ObjectTypeHintReturn
4
5 /**
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Cache Parser
23 */
24
25 namespace Wikimedia\Tests;
26
27 use InvalidArgumentException;
28 use Psr\Log\LoggerInterface;
29 use Psr\Log\NullLogger;
30
31 /**
32 * Utilities for testing forward and backward compatibility serialized objects.
33 */
34 class SerializationTestUtils {
35
36 /** @var string */
37 private $serializedDataPath;
38
39 /** @var string */
40 private $ext;
41
42 /** @var callable */
43 private $serializer;
44
45 /** @var callable */
46 private $deserializer;
47
48 /** @var array */
49 private $testInstances;
50
51 /** @var LoggerInterface */
52 private $logger;
53
54 /**
55 * @param string $serializedDataPath absolute path to the directory with serialized objects.
56 * @param array $testInstances map of test names to test objects.
57 * @param string $ext file extension for serialized instance files
58 * @param callable $serializer
59 * @param callable $deserializer
60 */
61 public function __construct(
62 string $serializedDataPath,
63 array $testInstances,
64 string $ext,
65 callable $serializer,
66 callable $deserializer
67 ) {
68 if ( !is_dir( $serializedDataPath ) ) {
69 throw new InvalidArgumentException( "{$serializedDataPath} does not exist" );
70 }
71 $this->serializedDataPath = $serializedDataPath;
72 $this->ext = $ext;
73 $this->serializer = $serializer;
74 $this->deserializer = $deserializer;
75 $this->testInstances = $testInstances;
76 $this->logger = new NullLogger();
77 }
78
79 /**
80 * @param LoggerInterface $logger
81 */
82 public function setLogger( LoggerInterface $logger ): void {
83 $this->logger = $logger;
84 }
85
86 /**
87 * Get the files with stored serialized instances of $class with extension $ext.
88 * @param class-string $class
89 * @param string $ext
90 * @return array
91 */
92 private function getMatchingFiles( string $class, string $ext ): array {
93 $classFile = self::classToFile( $class );
94 $glob = $this->serializedDataPath . "/*-{$classFile}-*.$ext";
95 $matches = glob( $glob );
96
97 if ( !$matches ) {
98 $this->log( 'No matches found for ' . $glob );
99 return [];
100 }
101
102 // File names should look something like this: "1.35-CacheTime-empty.serialized".
103 $pattern = '!/([^/-]+)-' . preg_quote( $classFile, '!' ) . '-([^/-]+)\.[^/]+$!';
104
105 $files = [];
106 foreach ( $matches as $path ) {
107 if ( !preg_match( $pattern, $path, $m ) ) {
108 $this->logger->warning( 'Skipping file with malformed name: ' . $path );
109 continue;
110 }
111 $version = $m[1];
112 $testCaseName = $m[2];
113
114 $files[] = $this->getStoredSerializedInstance( $class, $testCaseName, $version );
115 }
116
117 return $files;
118 }
119
120 /**
121 * Get an array of test instances for $class keyed with test case name.
122 * @return object[]
123 */
124 public function getTestInstances(): array {
125 return $this->testInstances;
126 }
127
128 /**
129 * Get a test instance of $class for test case named $testCaseName.
130 * @param string $testCaseName
131 * @return object
132 */
133 public function getTestInstanceForTestCase( string $testCaseName ): object {
134 $instances = $this->getTestInstances();
135 if ( !array_key_exists( $testCaseName, $instances ) ) {
136 throw new InvalidArgumentException(
137 "Test instance not found for test case {$testCaseName}"
138 );
139 }
140 return $instances[$testCaseName];
141 }
142
143 /**
144 * Get an array of instances of $class deserialized from
145 * files for different code versions, keyed by the test case name.
146 * @param class-string $class
147 * @return array
148 */
149 private function getDeserializedInstances( string $class ): array {
150 return array_map( function ( $fileInfo ) {
151 $fileInfo->object = call_user_func( $this->deserializer, $fileInfo->data );
152 return $fileInfo;
153 }, $this->getMatchingFiles( $class, $this->ext ) );
154 }
155
156 /**
157 * Get an array of serialization fixtures for $class stored in files
158 * for different MW versions, for test case name $testCaseName.
159 * @param class-string $class
160 * @param string $testCaseName
161 * @return array
162 */
163 public function getFixturesForTestCase( string $class, string $testCaseName ): array {
164 return array_filter(
165 $this->getMatchingFiles( $class, $this->ext ),
166 static function ( $fileInfo ) use ( $testCaseName ) {
167 return $fileInfo->testCaseName === $testCaseName;
168 } );
169 }
170
171 /**
172 * Get an array of instances of $class deserialized from stored files
173 * for different MW versions, for test case named $testCaseName.
174 * @param class-string $class
175 * @param string $testCaseName
176 * @return array
177 */
178 public function getDeserializedInstancesForTestCase( string $class, string $testCaseName ): array {
179 return array_filter( $this->getDeserializedInstances( $class ),
180 static function ( $fileInfo ) use ( $testCaseName ) {
181 return $fileInfo->testCaseName === $testCaseName;
182 }
183 );
184 }
185
186 /**
187 * Get test objects of $class, serialized using $serializer,
188 * keyed by test case name.
189 * @return array
190 */
191 public function getSerializedInstances(): array {
192 $instances = $this->getTestInstances();
193 return array_map( function ( $object ) {
194 return call_user_func( $this->serializer, $object );
195 }, $instances );
196 }
197
198 /**
199 * Get the file info about a stored serialized instance of $class,
200 * for test case $testCaseName with extension $ext for $version of MW.
201 * @param class-string $class
202 * @param string $testCaseName
203 * @param string|null $version
204 * @return \stdClass
205 */
206 public function getStoredSerializedInstance(
207 string $class,
208 string $testCaseName,
209 ?string $version = null
210 ) {
211 $classFile = self::classToFile( $class );
212 $curPath = "$this->serializedDataPath/{$this->getCurrentVersion()}-$classFile-$testCaseName.$this->ext";
213 if ( $version ) {
214 $path = "$this->serializedDataPath/$version-$classFile-$testCaseName.$this->ext";
215 } else {
216 // Find the latest version we have saved.
217 $savedFiles = glob( "$this->serializedDataPath/?.??*-$classFile-$testCaseName.$this->ext" );
218 if ( count( $savedFiles ) > 0 ) {
219 // swap _ and - to ensure that 1.43-foo sorts after 1.43_wmf...-foo
220 usort(
221 $savedFiles,
222 fn ( $a, $b ) => strtr( $a, '-_', '_-' ) <=> strtr( $b, '-_', '_-' )
223 );
224 $path = end( $savedFiles );
225 } else {
226 // Handle creation of a new test case from scratch (no prior
227 // serialization file exists)
228 $path = $curPath;
229 }
230 }
231
232 return (object)[
233 'version' => $version,
234 'class' => $class,
235 'testCaseName' => $testCaseName,
236 'ext' => $this->ext,
237 'path' => $path,
238 'currentVersionPath' => $curPath,
239 'data' => is_file( $path ) ? file_get_contents( $path ) : null,
240 ];
241 }
242
243 /**
244 * Returns the current version of MediaWiki in `1.xx` format.
245 * @return string
246 */
247 private function getCurrentVersion(): string {
248 return preg_replace( '/^(\d\.\d+).*$/', '$1', MW_VERSION );
249 }
250
251 /**
252 * Clean up the class name to make a filename.
253 *
254 * At the moment this strips the namespace prefix; in the future
255 * we might consider keeping it but replacing backslashes with
256 * dashes or some such.
257 *
258 * @param class-string $class
259 * @return string A cleaned-up filename
260 */
261 private static function classToFile( string $class ): string {
262 $arr = explode( '\\', $class );
263 return end( $arr );
264 }
265
266 private function log( $msg ) {
267 $this->logger->info( $msg );
268 }
269 }