diff --git a/_test/core/DokuWikiTest.php b/_test/core/DokuWikiTest.php index c67d84847..5bafd8757 100644 --- a/_test/core/DokuWikiTest.php +++ b/_test/core/DokuWikiTest.php @@ -3,6 +3,8 @@ use dokuwiki\Extension\PluginController; use dokuwiki\Extension\Event; use dokuwiki\Extension\EventHandler; +use dokuwiki\Logger; + /** * Helper class to provide basic functionality for tests * @@ -266,4 +268,17 @@ abstract class DokuWikiTest extends PHPUnit\Framework\TestCase { $property->setAccessible(true); $property->setValue($obj, $value); } + + /** + * Expect the next log message to contain $message + * + * @param string $facility + * @param string $message + * @return void + */ + protected function expectLogMessage(string $message, string $facility = Logger::LOG_ERROR): void + { + $logger = Logger::getInstance($facility); + $logger->expect($message); + } } diff --git a/inc/Logger.php b/inc/Logger.php index 4c38224c5..1b29a698e 100644 --- a/inc/Logger.php +++ b/inc/Logger.php @@ -21,6 +21,9 @@ class Logger protected $isLogging = true; + /** @var string[] a list of expected log messages, only used during unit testing */ + protected $expected = []; + /** * Logger constructor. * @@ -165,6 +168,17 @@ class Logger return $this->isLogging; } + /** + * Tests may register log expectations + * + * @param string $log + * @return void + */ + public function expect($log) + { + $this->expected[] = $log; + } + /** * Formats the given data as loglines * @@ -228,10 +242,23 @@ class Logger protected function writeLogLines($lines, $logfile) { if (defined('DOKU_UNITTEST')) { - $stderr = fopen('php://stderr', 'w'); - fwrite($stderr, "\n[" . $this->facility . '] ' . implode("\n", $lines) . "\n"); - fclose($stderr); + // our tests may expect certain log messages + if($this->expected) { + $expected = array_shift($this->expected); + if(!str_contains($lines[0], $expected)) { + throw new \RuntimeException( + "Log expectation failed:\n". + "Expected: $expected\n". + "Actual: {$lines[0]}" + ); + } + } else { + $stderr = fopen('php://stderr', 'w'); + fwrite($stderr, "\n[" . $this->facility . '] ' . implode("\n", $lines) . "\n"); + fclose($stderr); + } } + return io_saveFile($logfile, implode("\n", $lines) . "\n", true); } }