Merge "Provide command to adjust phpunit.xml for code coverage"
[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 $optionsWithoutArgs = [ 'verbose' ];
27 require_once __DIR__ . '/commandLine.inc';
28
29 $wgHooks['BeforeParserFetchTemplateAndtitle'][] = 'PPFuzzTester::templateHook';
30
31 class PPFuzzTester {
32 public $hairs = [
33 '[[', ']]', '{{', '{{', '}}', '}}', '{{{', '}}}',
34 '<', '>', '<nowiki', '<gallery', '</nowiki>', '</gallery>', '<nOwIkI>', '</NoWiKi>',
35 '<!--', '-->',
36 "\n==", "==\n",
37 '|', '=', "\n", ' ', "\t", "\x7f",
38 '~~', '~~~', '~~~~', 'subst:',
39 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
40 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
41
42 // extensions
43 // '<ref>', '</ref>', '<references/>',
44 ];
45 public $minLength = 0;
46 public $maxLength = 20;
47 public $maxTemplates = 5;
48 // public $outputTypes = [ 'OT_HTML', 'OT_WIKI', 'OT_PREPROCESS' ];
49 public $entryPoints = [ 'testSrvus', 'testPst', 'testPreprocess' ];
50 public $verbose = false;
51
52 /**
53 * @var bool|PPFuzzTest
54 */
55 private static $currentTest = false;
56
57 function execute() {
58 if ( !file_exists( 'results' ) ) {
59 mkdir( 'results' );
60 }
61 if ( !is_dir( 'results' ) ) {
62 echo "Unable to create 'results' directory\n";
63 exit( 1 );
64 }
65 $overallStart = microtime( true );
66 $reportInterval = 1000;
67 for ( $i = 1; true; $i++ ) {
68 $t = -microtime( true );
69 try {
70 self::$currentTest = new PPFuzzTest( $this );
71 self::$currentTest->execute();
72 $passed = 'passed';
73 } catch ( Exception $e ) {
74 $testReport = self::$currentTest->getReport();
75 $exceptionReport = $e instanceof MWException ? $e->getText() : (string)$e;
76 $hash = md5( $testReport );
77 file_put_contents( "results/ppft-$hash.in", serialize( self::$currentTest ) );
78 file_put_contents( "results/ppft-$hash.fail",
79 "Input:\n$testReport\n\nException report:\n$exceptionReport\n" );
80 print "Test $hash failed\n";
81 $passed = 'failed';
82 }
83 $t += microtime( true );
84
85 if ( $this->verbose ) {
86 printf( "Test $passed in %.3f seconds\n", $t );
87 print self::$currentTest->getReport();
88 }
89
90 $reportMetric = ( microtime( true ) - $overallStart ) / $i * $reportInterval;
91 if ( $reportMetric > 25 ) {
92 if ( substr( $reportInterval, 0, 1 ) === '1' ) {
93 $reportInterval /= 2;
94 } else {
95 $reportInterval /= 5;
96 }
97 } elseif ( $reportMetric < 4 ) {
98 if ( substr( $reportInterval, 0, 1 ) === '1' ) {
99 $reportInterval *= 5;
100 } else {
101 $reportInterval *= 2;
102 }
103 }
104 if ( $i % $reportInterval == 0 ) {
105 print "$i tests done\n";
106 /*
107 $testReport = self::$currentTest->getReport();
108 $filename = 'results/ppft-' . md5( $testReport ) . '.pass';
109 file_put_contents( $filename, "Input:\n$testReport\n" );*/
110 }
111 }
112 }
113
114 function makeInputText( $max = false ) {
115 if ( $max === false ) {
116 $max = $this->maxLength;
117 }
118 $length = mt_rand( $this->minLength, $max );
119 $s = '';
120 for ( $i = 0; $i < $length; $i++ ) {
121 $hairIndex = mt_rand( 0, count( $this->hairs ) - 1 );
122 $s .= $this->hairs[$hairIndex];
123 }
124 // Send through the UTF-8 normaliser
125 // This resolves a few differences between the old preprocessor and the
126 // XML-based one, which doesn't like illegals and converts line endings.
127 // It's done by the MW UI, so it's a reasonably legitimate thing to do.
128 $s = MediaWikiServices::getInstance()->getContentLanguage()->normalize( $s );
129
130 return $s;
131 }
132
133 function makeTitle() {
134 return Title::newFromText( mt_rand( 0, 1000000 ), mt_rand( 0, 10 ) );
135 }
136
137 /*
138 function pickOutputType() {
139 $count = count( $this->outputTypes );
140 return $this->outputTypes[ mt_rand( 0, $count - 1 ) ];
141 }*/
142
143 function pickEntryPoint() {
144 $count = count( $this->entryPoints );
145
146 return $this->entryPoints[mt_rand( 0, $count - 1 )];
147 }
148 }
149
150 class PPFuzzTest {
151 public $templates, $mainText, $title, $entryPoint, $output;
152
153 /** @var PPFuzzTester */
154 private $parent;
155 /** @var string */
156 public $nickname;
157 /** @var bool */
158 public $fancySig;
159
160 /**
161 * @param PPFuzzTester $tester
162 */
163 function __construct( $tester ) {
164 global $wgMaxSigChars;
165 $this->parent = $tester;
166 $this->mainText = $tester->makeInputText();
167 $this->title = $tester->makeTitle();
168 // $this->outputType = $tester->pickOutputType();
169 $this->entryPoint = $tester->pickEntryPoint();
170 $this->nickname = $tester->makeInputText( $wgMaxSigChars + 10 );
171 $this->fancySig = (bool)mt_rand( 0, 1 );
172 $this->templates = [];
173 }
174
175 /**
176 * @param Title $title
177 * @return array
178 */
179 function templateHook( $title ) {
180 $titleText = $title->getPrefixedDBkey();
181
182 if ( !isset( $this->templates[$titleText] ) ) {
183 $finalTitle = $title;
184 if ( count( $this->templates ) >= $this->parent->maxTemplates ) {
185 // Too many templates
186 $text = false;
187 } else {
188 if ( !mt_rand( 0, 1 ) ) {
189 // Redirect
190 $finalTitle = $this->parent->makeTitle();
191 }
192 if ( !mt_rand( 0, 5 ) ) {
193 // Doesn't exist
194 $text = false;
195 } else {
196 $text = $this->parent->makeInputText();
197 }
198 }
199 $this->templates[$titleText] = [
200 'text' => $text,
201 'finalTitle' => $finalTitle ];
202 }
203
204 return $this->templates[$titleText];
205 }
206
207 function execute() {
208 global $wgUser;
209
210 $wgUser = new PPFuzzUser;
211 $wgUser->mName = 'Fuzz';
212 $wgUser->mFrom = 'name';
213 $wgUser->ppfz_test = $this;
214
215 $options = ParserOptions::newFromUser( $wgUser );
216 $options->setTemplateCallback( [ $this, 'templateHook' ] );
217 $options->setTimestamp( wfTimestampNow() );
218 $this->output = call_user_func(
219 [ MediaWikiServices::getInstance()->getParser(), $this->entryPoint ],
220 $this->mainText,
221 $this->title,
222 $options
223 );
224
225 return $this->output;
226 }
227
228 function getReport() {
229 $s = "Title: " . $this->title->getPrefixedDBkey() . "\n" .
230 // "Output type: {$this->outputType}\n" .
231 "Entry point: {$this->entryPoint}\n" .
232 "User: " . ( $this->fancySig ? 'fancy' : 'no-fancy' ) .
233 ' ' . var_export( $this->nickname, true ) . "\n" .
234 "Main text: " . var_export( $this->mainText, true ) . "\n";
235 foreach ( $this->templates as $titleText => $template ) {
236 $finalTitle = $template['finalTitle'];
237 if ( $finalTitle != $titleText ) {
238 $s .= "[[$titleText]] -> [[$finalTitle]]: " . var_export( $template['text'], true ) . "\n";
239 } else {
240 $s .= "[[$titleText]]: " . var_export( $template['text'], true ) . "\n";
241 }
242 }
243 $s .= "Output: " . var_export( $this->output, true ) . "\n";
244
245 return $s;
246 }
247 }
248
249 class PPFuzzUser extends User {
250 public $ppfz_test, $mDataLoaded;
251
252 function load( $flags = null ) {
253 if ( $this->mDataLoaded ) {
254 return;
255 }
256 $this->mDataLoaded = true;
257 $this->loadDefaults( $this->mName );
258 }
259
260 function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
261 if ( $oname === 'fancysig' ) {
262 return $this->ppfz_test->fancySig;
263 } elseif ( $oname === 'nickname' ) {
264 return $this->ppfz_test->nickname;
265 } else {
266 return parent::getOption( $oname, $defaultOverride, $ignoreHidden );
267 }
268 }
269 }
270
271 ini_set( 'memory_limit', '50M' );
272 if ( isset( $args[0] ) ) {
273 $testText = file_get_contents( $args[0] );
274 if ( !$testText ) {
275 print "File not found\n";
276 exit( 1 );
277 }
278 $test = unserialize( $testText );
279 $result = $test->execute();
280 print "Test passed.\n";
281 } else {
282 $tester = new PPFuzzTester;
283 $tester->verbose = isset( $options['verbose'] );
284 $tester->execute();
285 }