Deprecate Parser implementation methods (will be private in next release)
[lhc/web/wiklou.git] / maintenance / preprocessorFuzzTest.php
1 <?php
2 /**
3 * Performs fuzz-style testing of MediaWiki's preprocessor.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Maintenance
22 */
23
24 use MediaWiki\MediaWikiServices;
25
26 use Wikimedia\TestingAccessWrapper;
27
28 $optionsWithoutArgs = [ 'verbose' ];
29 require_once __DIR__ . '/commandLine.inc';
30
31 $wgHooks['BeforeParserFetchTemplateAndtitle'][] = 'PPFuzzTester::templateHook';
32
33 class PPFuzzTester {
34 public $hairs = [
35 '[[', ']]', '{{', '{{', '}}', '}}', '{{{', '}}}',
36 '<', '>', '<nowiki', '<gallery', '</nowiki>', '</gallery>', '<nOwIkI>', '</NoWiKi>',
37 '<!--', '-->',
38 "\n==", "==\n",
39 '|', '=', "\n", ' ', "\t", "\x7f",
40 '~~', '~~~', '~~~~', 'subst:',
41 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
42 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
43
44 // extensions
45 // '<ref>', '</ref>', '<references/>',
46 ];
47 public $minLength = 0;
48 public $maxLength = 20;
49 public $maxTemplates = 5;
50 // public $outputTypes = [ 'OT_HTML', 'OT_WIKI', 'OT_PREPROCESS' ];
51 public $entryPoints = [ 'fuzzTestSrvus', 'fuzzTestPst', 'fuzzTestPreprocess' ];
52 public $verbose = false;
53
54 /**
55 * @var bool|PPFuzzTest
56 */
57 private static $currentTest = false;
58
59 function execute() {
60 if ( !file_exists( 'results' ) ) {
61 mkdir( 'results' );
62 }
63 if ( !is_dir( 'results' ) ) {
64 echo "Unable to create 'results' directory\n";
65 exit( 1 );
66 }
67 $overallStart = microtime( true );
68 $reportInterval = 1000;
69 for ( $i = 1; true; $i++ ) {
70 $t = -microtime( true );
71 try {
72 self::$currentTest = new PPFuzzTest( $this );
73 self::$currentTest->execute();
74 $passed = 'passed';
75 } catch ( Exception $e ) {
76 $testReport = self::$currentTest->getReport();
77 $exceptionReport = $e instanceof MWException ? $e->getText() : (string)$e;
78 $hash = md5( $testReport );
79 file_put_contents( "results/ppft-$hash.in", serialize( self::$currentTest ) );
80 file_put_contents( "results/ppft-$hash.fail",
81 "Input:\n$testReport\n\nException report:\n$exceptionReport\n" );
82 print "Test $hash failed\n";
83 $passed = 'failed';
84 }
85 $t += microtime( true );
86
87 if ( $this->verbose ) {
88 printf( "Test $passed in %.3f seconds\n", $t );
89 print self::$currentTest->getReport();
90 }
91
92 $reportMetric = ( microtime( true ) - $overallStart ) / $i * $reportInterval;
93 if ( $reportMetric > 25 ) {
94 if ( substr( $reportInterval, 0, 1 ) === '1' ) {
95 $reportInterval /= 2;
96 } else {
97 $reportInterval /= 5;
98 }
99 } elseif ( $reportMetric < 4 ) {
100 if ( substr( $reportInterval, 0, 1 ) === '1' ) {
101 $reportInterval *= 5;
102 } else {
103 $reportInterval *= 2;
104 }
105 }
106 if ( $i % $reportInterval == 0 ) {
107 print "$i tests done\n";
108 /*
109 $testReport = self::$currentTest->getReport();
110 $filename = 'results/ppft-' . md5( $testReport ) . '.pass';
111 file_put_contents( $filename, "Input:\n$testReport\n" );*/
112 }
113 }
114 }
115
116 function makeInputText( $max = false ) {
117 if ( $max === false ) {
118 $max = $this->maxLength;
119 }
120 $length = mt_rand( $this->minLength, $max );
121 $s = '';
122 for ( $i = 0; $i < $length; $i++ ) {
123 $hairIndex = mt_rand( 0, count( $this->hairs ) - 1 );
124 $s .= $this->hairs[$hairIndex];
125 }
126 // Send through the UTF-8 normaliser
127 // This resolves a few differences between the old preprocessor and the
128 // XML-based one, which doesn't like illegals and converts line endings.
129 // It's done by the MW UI, so it's a reasonably legitimate thing to do.
130 $s = MediaWikiServices::getInstance()->getContentLanguage()->normalize( $s );
131
132 return $s;
133 }
134
135 function makeTitle() {
136 return Title::newFromText( mt_rand( 0, 1000000 ), mt_rand( 0, 10 ) );
137 }
138
139 /*
140 function pickOutputType() {
141 $count = count( $this->outputTypes );
142 return $this->outputTypes[ mt_rand( 0, $count - 1 ) ];
143 }*/
144
145 function pickEntryPoint() {
146 $count = count( $this->entryPoints );
147
148 return $this->entryPoints[mt_rand( 0, $count - 1 )];
149 }
150 }
151
152 class PPFuzzTest {
153 public $templates, $mainText, $title, $entryPoint, $output;
154
155 /** @var PPFuzzTester */
156 private $parent;
157 /** @var string */
158 public $nickname;
159 /** @var bool */
160 public $fancySig;
161
162 /**
163 * @param PPFuzzTester $tester
164 */
165 function __construct( $tester ) {
166 global $wgMaxSigChars;
167 $this->parent = $tester;
168 $this->mainText = $tester->makeInputText();
169 $this->title = $tester->makeTitle();
170 // $this->outputType = $tester->pickOutputType();
171 $this->entryPoint = $tester->pickEntryPoint();
172 $this->nickname = $tester->makeInputText( $wgMaxSigChars + 10 );
173 $this->fancySig = (bool)mt_rand( 0, 1 );
174 $this->templates = [];
175 }
176
177 /**
178 * @param Title $title
179 * @return array
180 */
181 function templateHook( $title ) {
182 $titleText = $title->getPrefixedDBkey();
183
184 if ( !isset( $this->templates[$titleText] ) ) {
185 $finalTitle = $title;
186 if ( count( $this->templates ) >= $this->parent->maxTemplates ) {
187 // Too many templates
188 $text = false;
189 } else {
190 if ( !mt_rand( 0, 1 ) ) {
191 // Redirect
192 $finalTitle = $this->parent->makeTitle();
193 }
194 if ( !mt_rand( 0, 5 ) ) {
195 // Doesn't exist
196 $text = false;
197 } else {
198 $text = $this->parent->makeInputText();
199 }
200 }
201 $this->templates[$titleText] = [
202 'text' => $text,
203 'finalTitle' => $finalTitle ];
204 }
205
206 return $this->templates[$titleText];
207 }
208
209 function execute() {
210 global $wgUser;
211
212 $wgUser = new PPFuzzUser;
213 $wgUser->mName = 'Fuzz';
214 $wgUser->mFrom = 'name';
215 $wgUser->ppfz_test = $this;
216
217 $options = ParserOptions::newFromUser( $wgUser );
218 $options->setTemplateCallback( [ $this, 'templateHook' ] );
219 $options->setTimestamp( wfTimestampNow() );
220 $this->output = call_user_func(
221 [ TestingAccessWrapper::newFromObject(
222 MediaWikiServices::getInstance()->getParser()
223 ), $this->entryPoint ],
224 $this->mainText,
225 $this->title,
226 $options
227 );
228
229 return $this->output;
230 }
231
232 function getReport() {
233 $s = "Title: " . $this->title->getPrefixedDBkey() . "\n" .
234 // "Output type: {$this->outputType}\n" .
235 "Entry point: {$this->entryPoint}\n" .
236 "User: " . ( $this->fancySig ? 'fancy' : 'no-fancy' ) .
237 ' ' . var_export( $this->nickname, true ) . "\n" .
238 "Main text: " . var_export( $this->mainText, true ) . "\n";
239 foreach ( $this->templates as $titleText => $template ) {
240 $finalTitle = $template['finalTitle'];
241 if ( $finalTitle != $titleText ) {
242 $s .= "[[$titleText]] -> [[$finalTitle]]: " . var_export( $template['text'], true ) . "\n";
243 } else {
244 $s .= "[[$titleText]]: " . var_export( $template['text'], true ) . "\n";
245 }
246 }
247 $s .= "Output: " . var_export( $this->output, true ) . "\n";
248
249 return $s;
250 }
251 }
252
253 class PPFuzzUser extends User {
254 public $ppfz_test, $mDataLoaded;
255
256 function load( $flags = null ) {
257 if ( $this->mDataLoaded ) {
258 return;
259 }
260 $this->mDataLoaded = true;
261 $this->loadDefaults( $this->mName );
262 }
263
264 function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
265 if ( $oname === 'fancysig' ) {
266 return $this->ppfz_test->fancySig;
267 } elseif ( $oname === 'nickname' ) {
268 return $this->ppfz_test->nickname;
269 } else {
270 return parent::getOption( $oname, $defaultOverride, $ignoreHidden );
271 }
272 }
273 }
274
275 ini_set( 'memory_limit', '50M' );
276 if ( isset( $args[0] ) ) {
277 $testText = file_get_contents( $args[0] );
278 if ( !$testText ) {
279 print "File not found\n";
280 exit( 1 );
281 }
282 $test = unserialize( $testText );
283 $result = $test->execute();
284 print "Test passed.\n";
285 } else {
286 $tester = new PPFuzzTester;
287 $tester->verbose = isset( $options['verbose'] );
288 $tester->execute();
289 }