Merge "Increase cleanupTitles.php batch size"
[lhc/web/wiklou.git] / tests / phpunit / structure / AutoLoaderTest.php
1 <?php
2
3 class AutoLoaderTest extends MediaWikiTestCase {
4 protected function setUp() {
5 parent::setUp();
6
7 // Fancy dance to trigger a rebuild of AutoLoader::$autoloadLocalClassesLower
8 $this->mergeMwGlobalArrayValue( 'wgAutoloadLocalClasses', [
9 'TestAutoloadedLocalClass' =>
10 __DIR__ . '/../data/autoloader/TestAutoloadedLocalClass.php',
11 'TestAutoloadedCamlClass' =>
12 __DIR__ . '/../data/autoloader/TestAutoloadedCamlClass.php',
13 'TestAutoloadedSerializedClass' =>
14 __DIR__ . '/../data/autoloader/TestAutoloadedSerializedClass.php',
15 ] );
16 AutoLoader::resetAutoloadLocalClassesLower();
17
18 $this->mergeMwGlobalArrayValue( 'wgAutoloadClasses', [
19 'TestAutoloadedClass' => __DIR__ . '/../data/autoloader/TestAutoloadedClass.php',
20 ] );
21 }
22
23 /**
24 * Assert that there were no classes loaded that are not registered with the AutoLoader.
25 *
26 * For example foo.php having class Foo and class Bar but only registering Foo.
27 * This is important because we should not be relying on Foo being used before Bar.
28 */
29 public function testAutoLoadConfig() {
30 $results = self::checkAutoLoadConf();
31
32 $this->assertEquals(
33 $results['expected'],
34 $results['actual']
35 );
36 }
37
38 public function providePSR4Completeness() {
39 foreach ( AutoLoader::$psr4Namespaces as $prefix => $dir ) {
40 foreach ( $this->recurseFiles( $dir ) as $file ) {
41 yield [ $prefix, $file ];
42 }
43 }
44 }
45
46 private function recurseFiles( $dir ) {
47 return ( new File_Iterator_Facade() )->getFilesAsArray( $dir, [ '.php' ] );
48 }
49
50 /**
51 * @coversNothing
52 * @dataProvider providePSR4Completeness
53 */
54 public function testPSR4Completeness( $prefix, $file ) {
55 global $wgAutoloadLocalClasses, $wgAutoloadClasses;
56 $contents = file_get_contents( $file );
57 list( $classesInFile, $aliasesInFile ) = self::parseFile( $contents );
58 $classes = array_keys( $classesInFile );
59 $this->assertCount( 1, $classes,
60 "Only one class per file in PSR-4 autoloaded classes ($file)" );
61
62 $this->assertStringStartsWith( $prefix, $classes[0] );
63 $this->assertTrue(
64 class_exists( $classes[0] ) || interface_exists( $classes[0] ) || trait_exists( $classes[0] ),
65 "Class {$classes[0]} not autoloaded properly"
66 );
67
68 $otherClasses = $wgAutoloadLocalClasses + $wgAutoloadClasses;
69 foreach ( $aliasesInFile as $alias => $class ) {
70 $this->assertArrayHasKey( $alias, $otherClasses,
71 'Alias must be in the classmap autoloader'
72 );
73 }
74 }
75
76 private static function parseFile( $contents ) {
77 // We could use token_get_all() here, but this is faster
78 // Note: Keep in sync with ClassCollector
79 $matches = [];
80 preg_match_all( '/
81 ^ [\t ]* (?:
82 (?:final\s+)? (?:abstract\s+)? (?:class|interface|trait) \s+
83 (?P<class> [a-zA-Z0-9_]+)
84 |
85 class_alias \s* \( \s*
86 ([\'"]) (?P<original> [^\'"]+) \g{-2} \s* , \s*
87 ([\'"]) (?P<alias> [^\'"]+ ) \g{-2} \s*
88 \) \s* ;
89 |
90 class_alias \s* \( \s*
91 (?P<originalStatic> [a-zA-Z0-9_]+)::class \s* , \s*
92 ([\'"]) (?P<aliasString> [^\'"]+ ) \g{-2} \s*
93 \) \s* ;
94 )
95 /imx', $contents, $matches, PREG_SET_ORDER );
96
97 $namespaceMatch = [];
98 preg_match( '/
99 ^ [\t ]*
100 namespace \s+
101 ([a-zA-Z0-9_]+(\\\\[a-zA-Z0-9_]+)*)
102 \s* ;
103 /imx', $contents, $namespaceMatch );
104 $fileNamespace = $namespaceMatch ? $namespaceMatch[1] . '\\' : '';
105
106 $classesInFile = [];
107 $aliasesInFile = [];
108
109 foreach ( $matches as $match ) {
110 if ( !empty( $match['class'] ) ) {
111 // 'class Foo {}'
112 $class = $fileNamespace . $match['class'];
113 $classesInFile[$class] = true;
114 } else {
115 if ( !empty( $match['original'] ) ) {
116 // 'class_alias( "Foo", "Bar" );'
117 $aliasesInFile[$match['alias']] = $match['original'];
118 } else {
119 // 'class_alias( Foo::class, "Bar" );'
120 $aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic'];
121 }
122 }
123 }
124
125 return [ $classesInFile, $aliasesInFile ];
126 }
127
128 protected static function checkAutoLoadConf() {
129 global $wgAutoloadLocalClasses, $wgAutoloadClasses, $IP;
130
131 // wgAutoloadLocalClasses has precedence, just like in includes/AutoLoader.php
132 $expected = $wgAutoloadLocalClasses + $wgAutoloadClasses;
133 $actual = [];
134
135 $files = array_unique( $expected );
136
137 foreach ( $files as $class => $file ) {
138 // Only prefix $IP if it doesn't have it already.
139 // Generally local classes don't have it, and those from extensions and test suites do.
140 if ( substr( $file, 0, 1 ) != '/' && substr( $file, 1, 1 ) != ':' ) {
141 $filePath = "$IP/$file";
142 } else {
143 $filePath = $file;
144 }
145
146 if ( !file_exists( $filePath ) ) {
147 $actual[$class] = "[file '$filePath' does not exist]";
148 continue;
149 }
150
151 Wikimedia\suppressWarnings();
152 $contents = file_get_contents( $filePath );
153 Wikimedia\restoreWarnings();
154
155 if ( $contents === false ) {
156 $actual[$class] = "[couldn't read file '$filePath']";
157 continue;
158 }
159
160 list( $classesInFile, $aliasesInFile ) = self::parseFile( $contents );
161
162 foreach ( $classesInFile as $className => $ignore ) {
163 $actual[$className] = $file;
164 }
165
166 // Only accept aliases for classes in the same file, because for correct
167 // behavior, all aliases for a class must be set up when the class is loaded
168 // (see <https://bugs.php.net/bug.php?id=61422>).
169 foreach ( $aliasesInFile as $alias => $class ) {
170 if ( isset( $classesInFile[$class] ) ) {
171 $actual[$alias] = $file;
172 } else {
173 $actual[$alias] = "[original class not in $file]";
174 }
175 }
176 }
177
178 return [
179 'expected' => $expected,
180 'actual' => $actual,
181 ];
182 }
183
184 function testCoreClass() {
185 $this->assertTrue( class_exists( 'TestAutoloadedLocalClass' ) );
186 }
187
188 function testExtensionClass() {
189 $this->assertTrue( class_exists( 'TestAutoloadedClass' ) );
190 }
191
192 function testWrongCaseClass() {
193 $this->setMwGlobals( 'wgAutoloadAttemptLowercase', true );
194
195 $this->assertTrue( class_exists( 'testautoLoadedcamlCLASS' ) );
196 }
197
198 function testWrongCaseSerializedClass() {
199 $this->setMwGlobals( 'wgAutoloadAttemptLowercase', true );
200
201 $dummyCereal = 'O:29:"testautoloadedserializedclass":0:{}';
202 $uncerealized = unserialize( $dummyCereal );
203 $this->assertFalse( $uncerealized instanceof __PHP_Incomplete_Class,
204 "unserialize() can load classes case-insensitively." );
205 }
206
207 function testAutoloadOrder() {
208 $path = realpath( __DIR__ . '/../../..' );
209 $oldAutoload = file_get_contents( $path . '/autoload.php' );
210 $generator = new AutoloadGenerator( $path, 'local' );
211 $generator->setExcludePaths( array_values( AutoLoader::getAutoloadNamespaces() ) );
212 $generator->initMediaWikiDefault();
213 $newAutoload = $generator->getAutoload( 'maintenance/generateLocalAutoload.php' );
214
215 $this->assertEquals( $oldAutoload, $newAutoload, 'autoload.php does not match' .
216 ' output of generateLocalAutoload.php script.' );
217 }
218 }