Browse Source

Logger Unit tests

Roman 1 year ago
parent
commit
b549af3166
2 changed files with 36 additions and 1 deletions
  1. 30 0
      core/Driver/Logger/Logger.class.php
  2. 6 1
      test/DatabaseEntity.test.php

+ 30 - 0
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;
+  }
 }

+ 6 - 1
test/DatabaseEntity.test.php

@@ -1,6 +1,5 @@
 <?php
 
-// TODO: disable logging for tests
 class DatabaseEntityTest extends \PHPUnit\Framework\TestCase {
 
   static \Objects\User $USER;
@@ -12,6 +11,7 @@ class DatabaseEntityTest extends \PHPUnit\Framework\TestCase {
     self::$USER = new Objects\User(new \Configuration\Configuration());
     self::$SQL = self::$USER->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() {