From b549af3166233715ca277200906990bea304b5dd Mon Sep 17 00:00:00 2001 From: Roman Date: Fri, 17 Jun 2022 23:36:04 +0200 Subject: [PATCH] Logger Unit tests --- core/Driver/Logger/Logger.class.php | 30 +++++++++++++++++++++++++++++ test/DatabaseEntity.test.php | 7 ++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/core/Driver/Logger/Logger.class.php b/core/Driver/Logger/Logger.class.php index 66fe763..c8374be 100644 --- a/core/Driver/Logger/Logger.class.php +++ b/core/Driver/Logger/Logger.class.php @@ -20,9 +20,17 @@ class Logger { private ?SQL $sql; private string $module; + // unit tests + private bool $unitTestMode; + private ?string $lastMessage; + private ?string $lastLevel; + public function __construct(string $module = "Unknown", ?SQL $sql = null) { $this->module = $module; $this->sql = $sql; + $this->unitTestMode = false; + $this->lastMessage = null; + $this->lastLevel = null; } protected function getStackTrace(int $pop = 2): string { @@ -42,6 +50,12 @@ class Logger { $message .= "\n" . $this->getStackTrace(); } + if ($this->unitTestMode) { + $this->lastMessage = $message; + $this->lastLevel = $severity; + return; + } + if ($this->sql !== null && $this->sql->isConnected()) { $success = $this->sql->insert("SystemLog", ["module", "message", "severity"]) ->addRow($this->module, $message, $severity) @@ -91,4 +105,20 @@ class Logger { return self::$INSTANCE; } + + /** + * Calling this method will prevent the logger from persisting log messages (writing to database/file), + * and allow to access the last logged message via #getLastMessage() and #getLastLevel() + */ + public function unitTestMode() { + $this->unitTestMode = true; + } + + public function getLastMessage(): ?string { + return $this->lastMessage; + } + + public function getLastLevel(): ?string { + return $this->lastLevel; + } } \ No newline at end of file diff --git a/test/DatabaseEntity.test.php b/test/DatabaseEntity.test.php index 73c1509..dce45ec 100644 --- a/test/DatabaseEntity.test.php +++ b/test/DatabaseEntity.test.php @@ -1,6 +1,5 @@ getSQL(); self::$HANDLER = TestEntity::getHandler(self::$SQL); + self::$HANDLER->getLogger()->unitTestMode(); } public function testCreateTable() { @@ -75,6 +75,11 @@ class DatabaseEntityTest extends \PHPUnit\Framework\TestCase { public function testInsertFail() { $entity = new TestEntity(); $this->assertFalse($entity->save(self::$SQL)); + $this->assertTrue(startsWith( + self::$HANDLER->getLogger()->getLastMessage(), + "Cannot insert entity: property 'a' was not initialized yet." + )); + $this->assertEquals("error", self::$HANDLER->getLogger()->getLastLevel()); } public function testDropTable() {