Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiLoggerPHPUnitTestListener.php
1 <?php
2
3 use MediaWiki\Logger\LoggerFactory;
4 use MediaWiki\Logger\Spi;
5 use MediaWiki\Logger\LogCapturingSpi;
6
7 /**
8 * Replaces the logging SPI on each test run. This allows
9 * another component (the printer) to fetch the logs when
10 * reporting why a test failed.
11 */
12 class MediaWikiLoggerPHPUnitTestListener extends PHPUnit_Framework_BaseTestListener {
13 /** @var Spi|null */
14 private $originalSpi;
15 /** @var Spi|null */
16 private $spi;
17
18 /**
19 * A test started.
20 *
21 * @param PHPUnit_Framework_Test $test
22 */
23 public function startTest( PHPUnit_Framework_Test $test ) {
24 $this->lastTestLogs = null;
25 $this->originalSpi = LoggerFactory::getProvider();
26 $this->spi = new LogCapturingSpi( $this->originalSpi );
27 LoggerFactory::registerProvider( $this->spi );
28 }
29
30 public function addRiskyTest( PHPUnit_Framework_Test $test, Exception $e, $time ) {
31 $this->augmentTestWithLogs( $test );
32 }
33
34 public function addIncompleteTest( PHPUnit_Framework_Test $test, Exception $e, $time ) {
35 $this->augmentTestWithLogs( $test );
36 }
37
38 public function addSkippedTest( PHPUnit_Framework_Test $test, Exception $e, $time ) {
39 $this->augmentTestWithLogs( $test );
40 }
41
42 public function addError( PHPUnit_Framework_Test $test, Exception $e, $time ) {
43 $this->augmentTestWithLogs( $test );
44 }
45
46 public function addWarning( PHPUnit_Framework_Test $test, PHPUnit\Framework\Warning $e, $time ) {
47 $this->augmentTestWithLogs( $test );
48 }
49
50 public function addFailure( PHPUnit_Framework_Test $test,
51 PHPUnit_Framework_AssertionFailedError $e, $time
52 ) {
53 $this->augmentTestWithLogs( $test );
54 }
55
56 private function augmentTestWithLogs( PHPUnit_Framework_Test $test ) {
57 if ( $this->spi ) {
58 $logs = $this->spi->getLogs();
59 $formatted = $this->formatLogs( $logs );
60 $test->_formattedMediaWikiLogs = $formatted;
61 }
62 }
63
64 /**
65 * A test ended.
66 *
67 * @param PHPUnit_Framework_Test $test
68 * @param float $time
69 */
70 public function endTest( PHPUnit_Framework_Test $test, $time ) {
71 LoggerFactory::registerProvider( $this->originalSpi );
72 $this->originalSpi = null;
73 $this->spi = null;
74 }
75
76 /**
77 * Get string formatted logs generated during the last
78 * test to execute.
79 *
80 * @param array $logs
81 * @return string
82 */
83 private function formatLogs( array $logs ) {
84 $message = [];
85 foreach ( $logs as $log ) {
86 if ( $log['channel'] === 'PHPUnitCommand' ) {
87 // Don't print the log of PHPUnit events while running PHPUnit,
88 // because PHPUnit is already printing those already.
89 continue;
90 }
91 $message[] = sprintf(
92 '[%s] [%s] %s %s',
93 $log['channel'],
94 $log['level'],
95 $log['message'],
96 json_encode( $log['context'] )
97 );
98 }
99 return implode( "\n", $message );
100 }
101 }