testHelpers.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. <?php
  2. /**
  3. * Recording for passing/failing tests.
  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 Testing
  22. */
  23. /**
  24. * Interface to record parser test results.
  25. *
  26. * The ITestRecorder is a very simple interface to record the result of
  27. * MediaWiki parser tests. One should call start() before running the
  28. * full parser tests and end() once all the tests have been finished.
  29. * After each test, you should use record() to keep track of your tests
  30. * results. Finally, report() is used to generate a summary of your
  31. * test run, one could dump it to the console for human consumption or
  32. * register the result in a database for tracking purposes.
  33. *
  34. * @since 1.22
  35. */
  36. interface ITestRecorder {
  37. /** Called at beginning of the parser test run */
  38. public function start();
  39. /** Called after each test */
  40. public function record( $test, $result );
  41. /** Called before finishing the test run */
  42. public function report();
  43. /** Called at the end of the parser test run */
  44. public function end();
  45. }
  46. class TestRecorder implements ITestRecorder {
  47. var $parent;
  48. var $term;
  49. function __construct( $parent ) {
  50. $this->parent = $parent;
  51. $this->term = $parent->term;
  52. }
  53. function start() {
  54. $this->total = 0;
  55. $this->success = 0;
  56. }
  57. function record( $test, $result ) {
  58. $this->total++;
  59. $this->success += ( $result ? 1 : 0 );
  60. }
  61. function end() {
  62. // dummy
  63. }
  64. function report() {
  65. if ( $this->total > 0 ) {
  66. $this->reportPercentage( $this->success, $this->total );
  67. } else {
  68. throw new MWException( "No tests found.\n" );
  69. }
  70. }
  71. function reportPercentage( $success, $total ) {
  72. $ratio = wfPercent( 100 * $success / $total );
  73. print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
  74. if ( $success == $total ) {
  75. print $this->term->color( 32 ) . "ALL TESTS PASSED!";
  76. } else {
  77. $failed = $total - $success;
  78. print $this->term->color( 31 ) . "$failed tests failed!";
  79. }
  80. print $this->term->reset() . "\n";
  81. return ( $success == $total );
  82. }
  83. }
  84. class DbTestPreviewer extends TestRecorder {
  85. protected $lb; // /< Database load balancer
  86. protected $db; // /< Database connection to the main DB
  87. protected $curRun; // /< run ID number for the current run
  88. protected $prevRun; // /< run ID number for the previous run, if any
  89. protected $results; // /< Result array
  90. /**
  91. * This should be called before the table prefix is changed
  92. */
  93. function __construct( $parent ) {
  94. parent::__construct( $parent );
  95. $this->lb = wfGetLBFactory()->newMainLB();
  96. // This connection will have the wiki's table prefix, not parsertest_
  97. $this->db = $this->lb->getConnection( DB_MASTER );
  98. }
  99. /**
  100. * Set up result recording; insert a record for the run with the date
  101. * and all that fun stuff
  102. */
  103. function start() {
  104. parent::start();
  105. if ( !$this->db->tableExists( 'testrun', __METHOD__ )
  106. || !$this->db->tableExists( 'testitem', __METHOD__ )
  107. ) {
  108. print "WARNING> `testrun` table not found in database.\n";
  109. $this->prevRun = false;
  110. } else {
  111. // We'll make comparisons against the previous run later...
  112. $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
  113. }
  114. $this->results = array();
  115. }
  116. function record( $test, $result ) {
  117. parent::record( $test, $result );
  118. $this->results[$test] = $result;
  119. }
  120. function report() {
  121. if ( $this->prevRun ) {
  122. // f = fail, p = pass, n = nonexistent
  123. // codes show before then after
  124. $table = array(
  125. 'fp' => 'previously failing test(s) now PASSING! :)',
  126. 'pn' => 'previously PASSING test(s) removed o_O',
  127. 'np' => 'new PASSING test(s) :)',
  128. 'pf' => 'previously passing test(s) now FAILING! :(',
  129. 'fn' => 'previously FAILING test(s) removed O_o',
  130. 'nf' => 'new FAILING test(s) :(',
  131. 'ff' => 'still FAILING test(s) :(',
  132. );
  133. $prevResults = array();
  134. $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
  135. array( 'ti_run' => $this->prevRun ), __METHOD__ );
  136. foreach ( $res as $row ) {
  137. if ( !$this->parent->regex
  138. || preg_match( "/{$this->parent->regex}/i", $row->ti_name )
  139. ) {
  140. $prevResults[$row->ti_name] = $row->ti_success;
  141. }
  142. }
  143. $combined = array_keys( $this->results + $prevResults );
  144. # Determine breakdown by change type
  145. $breakdown = array();
  146. foreach ( $combined as $test ) {
  147. if ( !isset( $prevResults[$test] ) ) {
  148. $before = 'n';
  149. } elseif ( $prevResults[$test] == 1 ) {
  150. $before = 'p';
  151. } else /* if ( $prevResults[$test] == 0 )*/ {
  152. $before = 'f';
  153. }
  154. if ( !isset( $this->results[$test] ) ) {
  155. $after = 'n';
  156. } elseif ( $this->results[$test] == 1 ) {
  157. $after = 'p';
  158. } else /*if ( $this->results[$test] == 0 ) */ {
  159. $after = 'f';
  160. }
  161. $code = $before . $after;
  162. if ( isset( $table[$code] ) ) {
  163. $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
  164. }
  165. }
  166. # Write out results
  167. foreach ( $table as $code => $label ) {
  168. if ( !empty( $breakdown[$code] ) ) {
  169. $count = count( $breakdown[$code] );
  170. printf( "\n%4d %s\n", $count, $label );
  171. foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
  172. print " * $differing_test_name [$statusInfo]\n";
  173. }
  174. }
  175. }
  176. } else {
  177. print "No previous test runs to compare against.\n";
  178. }
  179. print "\n";
  180. parent::report();
  181. }
  182. /**
  183. * Returns a string giving information about when a test last had a status change.
  184. * Could help to track down when regressions were introduced, as distinct from tests
  185. * which have never passed (which are more change requests than regressions).
  186. */
  187. private function getTestStatusInfo( $testname, $after ) {
  188. // If we're looking at a test that has just been removed, then say when it first appeared.
  189. if ( $after == 'n' ) {
  190. $changedRun = $this->db->selectField( 'testitem',
  191. 'MIN(ti_run)',
  192. array( 'ti_name' => $testname ),
  193. __METHOD__ );
  194. $appear = $this->db->selectRow( 'testrun',
  195. array( 'tr_date', 'tr_mw_version' ),
  196. array( 'tr_id' => $changedRun ),
  197. __METHOD__ );
  198. return "First recorded appearance: "
  199. . date( "d-M-Y H:i:s", strtotime( $appear->tr_date ) )
  200. . ", " . $appear->tr_mw_version;
  201. }
  202. // Otherwise, this test has previous recorded results.
  203. // See when this test last had a different result to what we're seeing now.
  204. $conds = array(
  205. 'ti_name' => $testname,
  206. 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
  207. if ( $this->curRun ) {
  208. $conds[] = "ti_run != " . $this->db->addQuotes( $this->curRun );
  209. }
  210. $changedRun = $this->db->selectField( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
  211. // If no record of ever having had a different result.
  212. if ( is_null( $changedRun ) ) {
  213. if ( $after == "f" ) {
  214. return "Has never passed";
  215. } else {
  216. return "Has never failed";
  217. }
  218. }
  219. // Otherwise, we're looking at a test whose status has changed.
  220. // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
  221. // In this situation, give as much info as we can as to when it changed status.
  222. $pre = $this->db->selectRow( 'testrun',
  223. array( 'tr_date', 'tr_mw_version' ),
  224. array( 'tr_id' => $changedRun ),
  225. __METHOD__ );
  226. $post = $this->db->selectRow( 'testrun',
  227. array( 'tr_date', 'tr_mw_version' ),
  228. array( "tr_id > " . $this->db->addQuotes( $changedRun ) ),
  229. __METHOD__,
  230. array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
  231. );
  232. if ( $post ) {
  233. $postDate = date( "d-M-Y H:i:s", strtotime( $post->tr_date ) ) . ", {$post->tr_mw_version}";
  234. } else {
  235. $postDate = 'now';
  236. }
  237. return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
  238. . date( "d-M-Y H:i:s", strtotime( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
  239. . " and $postDate";
  240. }
  241. /**
  242. * Commit transaction and clean up for result recording
  243. */
  244. function end() {
  245. $this->lb->commitMasterChanges();
  246. $this->lb->closeAll();
  247. parent::end();
  248. }
  249. }
  250. class DbTestRecorder extends DbTestPreviewer {
  251. var $version;
  252. /**
  253. * Set up result recording; insert a record for the run with the date
  254. * and all that fun stuff
  255. */
  256. function start() {
  257. $this->db->begin( __METHOD__ );
  258. if ( !$this->db->tableExists( 'testrun' )
  259. || !$this->db->tableExists( 'testitem' )
  260. ) {
  261. print "WARNING> `testrun` table not found in database. Trying to create table.\n";
  262. $this->db->sourceFile( $this->db->patchPath( 'patch-testrun.sql' ) );
  263. echo "OK, resuming.\n";
  264. }
  265. parent::start();
  266. $this->db->insert( 'testrun',
  267. array(
  268. 'tr_date' => $this->db->timestamp(),
  269. 'tr_mw_version' => $this->version,
  270. 'tr_php_version' => phpversion(),
  271. 'tr_db_version' => $this->db->getServerVersion(),
  272. 'tr_uname' => php_uname()
  273. ),
  274. __METHOD__ );
  275. if ( $this->db->getType() === 'postgres' ) {
  276. $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
  277. } else {
  278. $this->curRun = $this->db->insertId();
  279. }
  280. }
  281. /**
  282. * Record an individual test item's success or failure to the db
  283. *
  284. * @param $test String
  285. * @param $result Boolean
  286. */
  287. function record( $test, $result ) {
  288. parent::record( $test, $result );
  289. $this->db->insert( 'testitem',
  290. array(
  291. 'ti_run' => $this->curRun,
  292. 'ti_name' => $test,
  293. 'ti_success' => $result ? 1 : 0,
  294. ),
  295. __METHOD__ );
  296. }
  297. }
  298. class TestFileIterator implements Iterator {
  299. private $file;
  300. private $fh;
  301. private $parserTest; /* An instance of ParserTest (parserTests.php) or MediaWikiParserTest (phpunit) */
  302. private $index = 0;
  303. private $test;
  304. private $section = null;
  305. /** String|null: current test section being analyzed */
  306. private $sectionData = array();
  307. private $lineNum;
  308. private $eof;
  309. function __construct( $file, $parserTest ) {
  310. $this->file = $file;
  311. $this->fh = fopen( $this->file, "rt" );
  312. if ( !$this->fh ) {
  313. throw new MWException( "Couldn't open file '$file'\n" );
  314. }
  315. $this->parserTest = $parserTest;
  316. $this->lineNum = $this->index = 0;
  317. }
  318. function rewind() {
  319. if ( fseek( $this->fh, 0 ) ) {
  320. throw new MWException( "Couldn't fseek to the start of '$this->file'\n" );
  321. }
  322. $this->index = -1;
  323. $this->lineNum = 0;
  324. $this->eof = false;
  325. $this->next();
  326. return true;
  327. }
  328. function current() {
  329. return $this->test;
  330. }
  331. function key() {
  332. return $this->index;
  333. }
  334. function next() {
  335. if ( $this->readNextTest() ) {
  336. $this->index++;
  337. return true;
  338. } else {
  339. $this->eof = true;
  340. }
  341. }
  342. function valid() {
  343. return $this->eof != true;
  344. }
  345. function readNextTest() {
  346. $this->clearSection();
  347. # Create a fake parser tests which never run anything unless
  348. # asked to do so. This will avoid running hooks for a disabled test
  349. $delayedParserTest = new DelayedParserTest();
  350. while ( false !== ( $line = fgets( $this->fh ) ) ) {
  351. $this->lineNum++;
  352. $matches = array();
  353. if ( preg_match( '/^!!\s*(\S+)/', $line, $matches ) ) {
  354. $this->section = strtolower( $matches[1] );
  355. if ( $this->section == 'endarticle' ) {
  356. $this->checkSection( 'text' );
  357. $this->checkSection( 'article' );
  358. $this->parserTest->addArticle( ParserTest::chomp( $this->sectionData['article'] ), $this->sectionData['text'], $this->lineNum );
  359. $this->clearSection();
  360. continue;
  361. }
  362. if ( $this->section == 'endhooks' ) {
  363. $this->checkSection( 'hooks' );
  364. foreach ( explode( "\n", $this->sectionData['hooks'] ) as $line ) {
  365. $line = trim( $line );
  366. if ( $line ) {
  367. $delayedParserTest->requireHook( $line );
  368. }
  369. }
  370. $this->clearSection();
  371. continue;
  372. }
  373. if ( $this->section == 'endfunctionhooks' ) {
  374. $this->checkSection( 'functionhooks' );
  375. foreach ( explode( "\n", $this->sectionData['functionhooks'] ) as $line ) {
  376. $line = trim( $line );
  377. if ( $line ) {
  378. $delayedParserTest->requireFunctionHook( $line );
  379. }
  380. }
  381. $this->clearSection();
  382. continue;
  383. }
  384. if ( $this->section == 'end' ) {
  385. $this->checkSection( 'test' );
  386. // "input" and "result" are old section names allowed
  387. // for backwards-compatibility.
  388. $input = $this->checkSection( array( 'wikitext', 'input' ), false );
  389. $result = $this->checkSection( array( 'html/php', 'html/*', 'html', 'result' ), false );
  390. if ( !isset( $this->sectionData['options'] ) ) {
  391. $this->sectionData['options'] = '';
  392. }
  393. if ( !isset( $this->sectionData['config'] ) ) {
  394. $this->sectionData['config'] = '';
  395. }
  396. if ( $input == false || $result == false ||
  397. ( ( preg_match( '/\\bdisabled\\b/i', $this->sectionData['options'] ) && !$this->parserTest->runDisabled )
  398. || ( preg_match( '/\\bparsoid\\b/i', $this->sectionData['options'] ) && $result != 'html/php' && !$this->parserTest->runParsoid )
  399. || !preg_match( "/" . $this->parserTest->regex . "/i", $this->sectionData['test'] ) )
  400. ) {
  401. # disabled test
  402. $this->clearSection();
  403. # Forget any pending hooks call since test is disabled
  404. $delayedParserTest->reset();
  405. continue;
  406. }
  407. # We are really going to run the test, run pending hooks and hooks function
  408. wfDebug( __METHOD__ . " unleashing delayed test for: {$this->sectionData['test']}" );
  409. $hooksResult = $delayedParserTest->unleash( $this->parserTest );
  410. if ( !$hooksResult ) {
  411. # Some hook reported an issue. Abort.
  412. return false;
  413. }
  414. $this->test = array(
  415. 'test' => ParserTest::chomp( $this->sectionData['test'] ),
  416. 'input' => ParserTest::chomp( $this->sectionData[ $input ] ),
  417. 'result' => ParserTest::chomp( $this->sectionData[ $result ] ),
  418. 'options' => ParserTest::chomp( $this->sectionData['options'] ),
  419. 'config' => ParserTest::chomp( $this->sectionData['config'] ),
  420. );
  421. return true;
  422. }
  423. if ( isset( $this->sectionData[$this->section] ) ) {
  424. throw new MWException( "duplicate section '$this->section' at line {$this->lineNum} of $this->file\n" );
  425. }
  426. $this->sectionData[$this->section] = '';
  427. continue;
  428. }
  429. if ( $this->section ) {
  430. $this->sectionData[$this->section] .= $line;
  431. }
  432. }
  433. return false;
  434. }
  435. /**
  436. * Clear section name and its data
  437. */
  438. private function clearSection() {
  439. $this->sectionData = array();
  440. $this->section = null;
  441. }
  442. /**
  443. * Verify the current section data has some value for the given token
  444. * name(s) (first parameter).
  445. * Throw an exception if it is not set, referencing current section
  446. * and adding the current file name and line number
  447. *
  448. * @param $token String|Array: expected token(s) that should have been
  449. * mentioned before closing this section
  450. * @param $fatal Boolean: true iff an exception should be thrown if
  451. * the section is not found.
  452. */
  453. private function checkSection( $tokens, $fatal = true ) {
  454. if ( is_null( $this->section ) ) {
  455. throw new MWException( __METHOD__ . " can not verify a null section!\n" );
  456. }
  457. if ( !is_array( $tokens ) ) {
  458. $tokens = array( $tokens );
  459. }
  460. if ( count( $tokens ) == 0 ) {
  461. throw new MWException( __METHOD__ . " can not verify zero sections!\n" );
  462. }
  463. $data = $this->sectionData;
  464. $tokens = array_filter( $tokens, function ( $token ) use ( $data ) {
  465. return isset( $data[ $token ] );
  466. } );
  467. if ( count( $tokens ) == 0 ) {
  468. if ( !$fatal ) {
  469. return false;
  470. }
  471. throw new MWException( sprintf(
  472. "'%s' without '%s' at line %s of %s\n",
  473. $this->section,
  474. implode( ',', $tokens ),
  475. $this->lineNum,
  476. $this->file
  477. ) );
  478. }
  479. if ( count( $tokens ) > 1 ) {
  480. throw new MWException( sprintf(
  481. "'%s' with unexpected tokens '%s' at line %s of %s\n",
  482. $this->section,
  483. implode( ',', $tokens ),
  484. $this->lineNum,
  485. $this->file
  486. ) );
  487. }
  488. $tokens = array_values( $tokens );
  489. return $tokens[ 0 ];
  490. }
  491. }
  492. /**
  493. * A class to delay execution of a parser test hooks.
  494. */
  495. class DelayedParserTest {
  496. /** Initialized on construction */
  497. private $hooks;
  498. private $fnHooks;
  499. public function __construct() {
  500. $this->reset();
  501. }
  502. /**
  503. * Init/reset or forgot about the current delayed test.
  504. * Call to this will erase any hooks function that were pending.
  505. */
  506. public function reset() {
  507. $this->hooks = array();
  508. $this->fnHooks = array();
  509. }
  510. /**
  511. * Called whenever we actually want to run the hook.
  512. * Should be the case if we found the parserTest is not disabled
  513. */
  514. public function unleash( &$parserTest ) {
  515. if ( !( $parserTest instanceof ParserTest || $parserTest instanceof NewParserTest ) ) {
  516. throw new MWException( __METHOD__ . " must be passed an instance of ParserTest or NewParserTest classes\n" );
  517. }
  518. # Trigger delayed hooks. Any failure will make us abort
  519. foreach ( $this->hooks as $hook ) {
  520. $ret = $parserTest->requireHook( $hook );
  521. if ( !$ret ) {
  522. return false;
  523. }
  524. }
  525. # Trigger delayed function hooks. Any failure will make us abort
  526. foreach ( $this->fnHooks as $fnHook ) {
  527. $ret = $parserTest->requireFunctionHook( $fnHook );
  528. if ( !$ret ) {
  529. return false;
  530. }
  531. }
  532. # Delayed execution was successful.
  533. return true;
  534. }
  535. /**
  536. * Similar to ParserTest object but does not run anything
  537. * Use unleash() to really execute the hook
  538. */
  539. public function requireHook( $hook ) {
  540. $this->hooks[] = $hook;
  541. }
  542. /**
  543. * Similar to ParserTest object but does not run anything
  544. * Use unleash() to really execute the hook function
  545. */
  546. public function requireFunctionHook( $fnHook ) {
  547. $this->fnHooks[] = $fnHook;
  548. }
  549. }