View source
<?php
declare (strict_types=1);
namespace Drupal\Tests\mongodb_watchdog\Kernel;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\mongodb\MongoDb;
use Drupal\mongodb_watchdog\Logger;
use Drupal\Tests\mongodb\Kernel\MongoDbTestBase;
class LoggerTest extends MongoDbTestBase {
use StringTranslationTrait;
protected $collection;
protected static $modules = [
'system',
MongoDb::MODULE,
Logger::MODULE,
];
public function setUp() : void {
parent::setUp();
$this
->installConfig(Logger::MODULE);
}
protected function getSettingsArray() : array {
$settings = parent::getSettingsArray();
$settings['databases'][Logger::DB_LOGGER] = [
static::CLIENT_TEST_ALIAS,
$this
->getDatabasePrefix(),
];
return $settings;
}
public function assertEntry($message) {
$logged = $this
->find($message);
$this
->assertNotNull($logged, (string) $this
->t('Event %message is logged', [
'%message' => $message,
]));
$this
->assertTrue(isset($logged['message']) && $logged['message'] == $message, (string) $this
->t('Logged message is unchanged'));
}
public function assertNoEntry($message) {
$logged = $this
->find($message);
$this
->assertNull($logged, (string) $this
->t('Event %message is not logged', [
'%message' => $message,
]));
}
public static function debrace(string $message) : string {
return str_replace([
'{',
'}',
], [
'<',
'>',
], $message);
}
protected function find($message) {
$ret = $this->collection
->findOne([
'message' => $message,
]);
return $ret;
}
public function testLogClosure() {
$logger = $this->container
->get(Logger::SERVICE_LOGGER);
$closure = function () use ($logger) {
$logger
->notice("This fails on PHP below 7.0, and 5.6 needs to be supported for Drupal 8. The alcaeus adapter passes the version check, but does not address this.");
return 1;
};
$this
->assertEquals(1, $closure());
}
public function testWatchdogLimit() {
$config = $this
->config(Logger::CONFIG_NAME);
$limit = $config
->get(Logger::CONFIG_LIMIT);
$this
->assertEquals(RfcLogLevel::DEBUG, $limit, (string) $this
->t('%name defaults to @level', [
'%name' => Logger::CONFIG_LIMIT,
'@level' => RfcLogLevel::DEBUG,
]));
$logger = $this->container
->get(Logger::SERVICE_LOGGER);
$database = $this->container
->get(MongoDb::SERVICE_DB_FACTORY)
->get(Logger::DB_LOGGER);
$this->collection = $database
->selectCollection(Logger::TEMPLATE_COLLECTION);
$this->collection
->drop();
$message = static::debrace($this
->randomString(32));
$logger
->log($limit, $message);
$this
->assertEntry($message);
$logger
->setLimit(RfcLogLevel::INFO);
$this->collection
->drop();
$message = $this
->randomMachineName(32);
$logger
->debug($message);
$this
->assertNoEntry($message);
$message = $this
->randomMachineName(32);
$logger
->notice($message);
$this
->assertEntry($message);
$message = $this
->randomMachineName(32);
$logger
->error($message);
$this
->assertEntry($message);
}
}