You are here

public function ControllerTest::testLoggerAddAndUiClear in MongoDB 8.2

Test the UI clearing feature.

File

modules/mongodb_watchdog/tests/src/Functional/ControllerTest.php, line 507

Class

ControllerTest
Test the MongoDB report controllers.

Namespace

Drupal\Tests\mongodb_watchdog\Functional

Code

public function testLoggerAddAndUiClear() {

  // Drop the logger database to ensure no collections.
  $this->container
    ->get(MongoDb::SERVICE_DB_FACTORY)
    ->get(Logger::DB_LOGGER)
    ->drop();

  /** @var \Drupal\Core\Logger\LoggerChannelInterface $loggerChannel */
  $loggerChannel = $this->container
    ->get(Logger::SERVICE_CHANNEL);

  // Add a watchdog entry. Be sure not to include placeholder delimiters.
  $message = static::neuter($this
    ->randomString(32));
  $loggerChannel
    ->notice($message);

  // Make sure the collections were updated.

  /** @var \Drupal\mongodb_watchdog\Logger $logger */
  $logger = $this->container
    ->get(Logger::SERVICE_LOGGER);
  $templates = $logger
    ->templateCollection();
  $this
    ->assertEquals(1, $templates
    ->countDocuments(), 'Logging created templates collection and added a template to it.');
  $template = $templates
    ->findOne([
    'message' => $message,
  ], MongoDb::ID_PROJECTION);
  $this
    ->assertNotNull($template, "Logged message was found: [{$message}]");
  $templateId = $template['_id'];
  $events = $logger
    ->eventCollection($templateId);
  $this
    ->assertEquals(1, $events
    ->countDocuments(), 'Logging created events collection and added a template to it.');

  // Login the admin user.
  $this
    ->drupalLogin($this->adminUser);

  // Now post to clear the db table.
  $this
    ->drupalGet('admin/reports/mongodb/confirm');
  $this
    ->submitForm([], 'Confirm');

  // Make the sure logs were dropped. After a UI clear, the templates
  // collection should exist, since it is recreated as a capped collection as
  // part of the clear, but be empty, and there should be no event collection.
  $count = $templates
    ->countDocuments();
  $failMessage = 'Logger templates collection was cleared';
  if ($count > 0) {
    $options = [
      'projection' => [
        '_id' => 0,
        'message' => 1,
      ],
    ];
    $messages = iterator_to_array($templates
      ->find([], $options));
    $failMessage = "Logger templates collection still contains messages: " . json_encode($messages);
  }
  $this
    ->assertEquals(0, $count, $failMessage);
  $this
    ->assertFalse($logger
    ->eventCollections()
    ->valid(), "Event collections were dropped");
}