Passed
Pull Request — 8.x-2.x (#71)
by Frédéric G.
05:50
created

ControllerTest::verifyReports()   B

Complexity

Conditions 9
Paths 96

Size

Total Lines 89
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 59
c 1
b 0
f 0
nc 96
nop 1
dl 0
loc 89
rs 7.3389

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\Tests\mongodb_watchdog\Functional;
6
7
use Drupal\Core\Logger\RfcLogLevel;
0 ignored issues
show
Bug introduced by
The type Drupal\Core\Logger\RfcLogLevel was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Drupal\Core\Site\Settings;
0 ignored issues
show
Bug introduced by
The type Drupal\Core\Site\Settings was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use Drupal\Core\StringTranslation\StringTranslationTrait;
0 ignored issues
show
Bug introduced by
The type Drupal\Core\StringTransl...\StringTranslationTrait was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Drupal\mongodb\MongoDb;
11
use Drupal\mongodb_watchdog\Logger;
12
use Drupal\Tests\BrowserTestBase;
0 ignored issues
show
Bug introduced by
The type Drupal\Tests\BrowserTestBase was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Psr\Log\LoggerInterface;
0 ignored issues
show
Bug introduced by
The type Psr\Log\LoggerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use Psr\Log\LogLevel;
0 ignored issues
show
Bug introduced by
The type Psr\Log\LogLevel was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use Symfony\Component\HttpFoundation\Response;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFoundation\Response was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
17
/**
18
 * Test the MongoDB report controllers.
19
 *
20
 * @group MongoDB
21
 */
22
class ControllerTest extends BrowserTestBase {
23
24
  use StringTranslationTrait;
25
26
  const DEFAULT_URI = 'mongodb://localhost:27017';
27
28
  const CLIENT_TEST_ALIAS = 'test';
29
30
  const DB_DEFAULT_ALIAS = 'default';
31
32
  const PATH_DENIED = '/admin/reports/mongodb/watchdog/access-denied';
33
34
  const PATH_EVENT_BASE = "/admin/reports/mongodb/watchdog/";
35
36
  const PATH_NOT_FOUND = '/admin/reports/mongodb/watchdog/page-not-found';
37
38
  const PATH_OVERVIEW = 'admin/reports/mongodb/watchdog';
39
40
  /**
41
   * Map of PSR3 log constants to RFC 5424 log constants.
42
   *
43
   * @var array
44
   */
45
  const LEVEL_TRANSLATION = [
46
    LogLevel::EMERGENCY => RfcLogLevel::EMERGENCY,
47
    LogLevel::ALERT => RfcLogLevel::ALERT,
48
    LogLevel::CRITICAL => RfcLogLevel::CRITICAL,
49
    LogLevel::ERROR => RfcLogLevel::ERROR,
50
    LogLevel::WARNING => RfcLogLevel::WARNING,
51
    LogLevel::NOTICE => RfcLogLevel::NOTICE,
52
    LogLevel::INFO => RfcLogLevel::INFO,
53
    LogLevel::DEBUG => RfcLogLevel::DEBUG,
54
  ];
55
56
  /**
57
   * These modules need to be enabled.
58
   *
59
   * @var array
60
   */
61
  protected static $modules = [
62
    // Needed to check admin/help/mongodb.
63
    'help',
64
    MongoDb::MODULE,
65
    Logger::MODULE,
66
  ];
67
68
  /**
69
   * An administrator account.
70
   *
71
   * @var \Drupal\user\Entity\User
0 ignored issues
show
Bug introduced by
The type Drupal\user\Entity\User was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
72
   */
73
  protected $adminUser;
74
75
  /**
76
   * A basic authenticated user account.
77
   *
78
   * @var \Drupal\user\Entity\User
79
   */
80
  protected $anyUser;
81
82
  /**
83
   * An administrator-type user account, but not an administrator.
84
   *
85
   * @var \Drupal\user\Entity\User
86
   */
87
  protected $bigUser;
88
89
  /**
90
   * The event templates collection.
91
   *
92
   * @var \MongoDB\Collection
93
   */
94
  protected $collection;
95
96
  /**
97
   * The default theme, needed after 8.8.0.
98
   *
99
   * @var string
100
   *
101
   * @see https://www.drupal.org/node/3083055
102
   */
103
  protected $defaultTheme = 'stark';
104
105
  /**
106
   * The time the test started, simulating a request time.
107
   *
108
   * @var int
109
   */
110
  protected $requestTime;
111
112
  /**
113
   * The site base URI.
114
   *
115
   * @var string
116
   */
117
  protected $uri;
118
119
  /**
120
   * Remove all Drupal markup placeholders.
121
   *
122
   * @param string $message
123
   *   The raw message.
124
   *
125
   * @return string
126
   *   The replacement message.
127
   */
128
  protected static function neuter(string $message): string {
129
    return str_replace(['{', '}', '@', '%', ':'], '', $message);
130
  }
131
132
  /**
133
   * {@inheritdoc}
134
   *
135
   * Configure settings and create users with specific permissions.
136
   *
137
   * @see \Drupal\Tests\mongodb_watchdog\Functional\ControllerTest::writeSettings()
138
   */
139
  public function setUp(): void {
140
    // $_ENV if it comes from phpunit.xml <env>
141
    // $_SERVER if it comes from the phpunit command line environment.
142
    $this->uri = $_ENV['MONGODB_URI']
143
      ?? $_SERVER['MONGODB_URI']
144
      ?? static::DEFAULT_URI;
145
146
    // This line customizes the parent site; ::writeSettings the child site.
147
    $this->settings = new Settings(
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
148
      [
149
        MongoDb::MODULE => $this->getSettingsArray(),
150
      ]
151
    );
152
153
    parent::setUp();
154
155
    // Create users.
156
    $this->adminUser = $this->drupalCreateUser([], 'test_admin', TRUE);
157
    $this->bigUser = $this->drupalCreateUser(
158
      [
159
        'administer site configuration',
160
        'access administration pages',
161
        'access site reports',
162
        'administer users',
163
      ],
164
      'test_honcho'
165
    );
166
    $this->anyUser = $this->drupalCreateUser(
167
      [
168
        'access content',
169
      ],
170
      'test_lambda'
171
    );
172
173
    $this->requestTime = $this->container
174
      ->get('datetime.time')
175
      ->getCurrentTime();
176
177
    try {
178
      $this->collection = $this->container
179
        ->get(MongoDb::SERVICE_DB_FACTORY)
180
        ->get(Logger::DB_LOGGER)
181
        ->selectCollection(Logger::TEMPLATE_COLLECTION);
182
    }
183
    catch (\Exception $e) {
184
      $this->collection = NULL;
185
    }
186
    $this->assertNotNull($this->collection, (string) $this->t('Access MongoDB watchdog collection'));
187
  }
188
189
  /**
190
   * {@inheritdoc}
191
   */
192
  public function tearDown(): void {
193
    // Get the database before container is torn down.
194
    $database = $this->container
195
      ->get(MongoDb::SERVICE_DB_FACTORY)
196
      ->get(Logger::DB_LOGGER);
197
198
    // Might trigger some more log insertions, so do not drop yet.
199
    parent::tearDown();
200
201
    $database->drop();
202
  }
203
204
  /**
205
   * Rewrites the settings.php file of the test site.
206
   *
207
   * @param array $settings
208
   *   An array of settings to write out, in the format expected by
209
   *   drupal_rewrite_settings().
210
   *
211
   * @throws \Exception
212
   *
213
   * @see \Drupal\Core\Test\FunctionalTestSetupTrait::writeSettings()
214
   */
215
  protected function writeSettings(array $settings) {
216
    // Taken from trait.
217
    include_once DRUPAL_ROOT . '/core/includes/install.inc';
0 ignored issues
show
Bug introduced by
The constant Drupal\Tests\mongodb_wat...\Functional\DRUPAL_ROOT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
218
    $filename = $this->siteDirectory . '/settings.php';
219
220
    // Customizations.
221
    $settings['settings'] += [
222
      MongoDb::MODULE => (object) [
223
        'value' => $this->getSettingsArray(),
224
        'required' => TRUE,
225
      ],
226
    ];
227
228
    // End of code taken from trait again.
229
    // system_requirements() removes write permissions from settings.php
230
    // whenever it is invoked.
231
    // Not using File API; a potential error must trigger a PHP warning.
232
    chmod($filename, 0666);
233
    drupal_rewrite_settings($settings, $filename);
0 ignored issues
show
Bug introduced by
The function drupal_rewrite_settings was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

233
    /** @scrutinizer ignore-call */ 
234
    drupal_rewrite_settings($settings, $filename);
Loading history...
234
  }
235
236
  /**
237
   * Prepare the Settings from a base set of MongoDB settings.
238
   *
239
   * @return array
240
   *   A settings array only containing MongoDB-related settings.
241
   */
242
  protected function getSettingsArray(): array {
243
    return [
244
      'clients' => [
245
        static::CLIENT_TEST_ALIAS => [
246
          'uri' => $this->uri,
247
          'uriOptions' => [],
248
          'driverOptions' => [],
249
        ],
250
      ],
251
      'databases' => [
252
        static::DB_DEFAULT_ALIAS => [
253
          static::CLIENT_TEST_ALIAS,
254
          $this->getDatabasePrefix(),
255
        ],
256
        Logger::DB_LOGGER => [
257
          static::CLIENT_TEST_ALIAS,
258
          $this->getDatabasePrefix(),
259
        ],
260
      ],
261
    ];
262
  }
263
264
  /**
265
   * Getter for the test database prefix.
266
   *
267
   * @return string
268
   *   The prefix.
269
   *
270
   * @see \Drupal\KernelTests\KernelTestBase::getDatabasePrefix()
271
   */
272
  protected function getDatabasePrefix(): string {
273
    return $this->databasePrefix ?? '';
274
  }
275
276
  /**
277
   * Get the log entry information form the page.
278
   *
279
   * @return array
280
   *   List of entries and their information.
281
   */
282
  protected function getLogEntries(): array {
283
    $entries = [];
284
    if ($table = $this->getLogsEntriesTable()) {
285
      /** @var \Behat\Mink\Element\NodeElement $row */
286
      foreach ($table as $row) {
287
        /** @var \Behat\Mink\Element\NodeElement[] $cells */
288
        $cells = $row->findAll('css', 'td');
289
        $entries[] = [
290
          'severity' => $this->getSeverityConstant($cells[2]->getAttribute('class')),
291
          'type' => $cells[3]->getText(),
292
          'message' => $cells[4]->getText(),
293
        ];
294
      }
295
    }
296
    return $entries;
297
  }
298
299
  /**
300
   * Gets the watchdog severity constant corresponding to the CSS class.
301
   *
302
   * @param string $class
303
   *   CSS class attribute.
304
   *
305
   * @return int|null
306
   *   The watchdog severity constant or NULL if not found.
307
   */
308
  protected function getSeverityConstant(string $class): int {
309
    // Class: "mongodb-watchdog__severity--(level)", prefix length = 28.
310
    $level = substr($class, 28);
311
    return static::LEVEL_TRANSLATION[$level];
312
  }
313
314
  /**
315
   * Find the Logs table in the DOM.
316
   *
317
   * @return \Behat\Mink\Element\NodeElement[]
318
   *   The return value of a xpath search.
319
   */
320
  protected function getLogsEntriesTable(): array {
321
    return $this->xpath('.//table/tbody/tr');
322
  }
323
324
  /**
325
   * Asserts that the counts for displayed entries match the expected counts.
326
   *
327
   * @param array $types
328
   *   The type information to compare against.
329
   */
330
  protected function assertTypeCount(array $types) {
331
    $entries = $this->getLogEntries();
332
    $reducer = function ($accu, $curr) {
333
      $accu[$curr['type'] . '-' . $curr['severity']] = [
334
        $curr['type'],
335
        $curr['severity'],
336
      ];
337
      return $accu;
338
    };
339
    $actual = array_reduce($entries, $reducer, []);
340
    $expected = array_reduce($types, $reducer, []);
341
    $this->assertEquals($expected, $actual, "Inserted events are found on page");
342
  }
343
344
  /**
345
   * Generate dblog entries.
346
   *
347
   * @param \Psr\Log\LoggerInterface $logger
348
   *   The mongodb.logger service.
349
   * @param int $count
350
   *   Number of log entries to generate.
351
   * @param string $type
352
   *   The type of watchdog entry.
353
   * @param int $severity
354
   *   The severity of the watchdog entry.
355
   */
356
  private function insertLogEntries(
357
    LoggerInterface $logger,
358
    int $count,
359
    string $type = 'custom',
360
    int $severity = RfcLogLevel::EMERGENCY
361
  ) {
362
    $ip = '::1';
363
    $context = [
364
      'channel' => $type,
365
      'link' => NULL,
366
      'user' => ['uid' => $this->bigUser->id()],
367
      'request_uri' => "http://[$ip]/",
368
      'referer' => $_SERVER['HTTP_REFERER'] ?? '',
369
      'ip' => $ip,
370
      'timestamp' => $this->requestTime,
371
    ];
372
    $message = $this->randomString();
373
    for ($i = 0; $i < $count; $i++) {
374
      $logger->log($severity, $message, $context);
375
    }
376
  }
377
378
  /**
379
   * Verify the logged-in user has the desired access to the log report.
380
   *
381
   * @param int $statusCode
382
   *   HTTP status code.
383
   *
384
   * @throws \Behat\Mink\Exception\ExpectationException
385
   * @throws \Behat\Mink\Exception\ResponseTextException
386
   *
387
   * The first of the assertions would really belong in a functional test for
388
   * the mongodb module. But until it gets a functional test, keeping it here
389
   * saves some test running time over having one more functional test in
390
   * mongodb module just for this.
391
   */
392
  private function verifyReports($statusCode = Response::HTTP_OK) {
393
    // View MongoDB help page.
394
    $this->drupalGet('/admin/help');
395
    $session = $this->assertSession();
396
    $session->statusCodeEquals($statusCode);
397
    if ($statusCode == Response::HTTP_OK) {
398
      $session->pageTextContains('MongoDB');
399
    }
400
401
    $this->drupalGet('/admin/help/mongodb');
402
    $session = $this->assertSession();
403
    $session->statusCodeEquals($statusCode);
404
    if ($statusCode == Response::HTTP_OK) {
405
      // DBLog help was displayed.
406
      $session->pageTextContains('implements a generic interface');
407
    }
408
409
    // View MongoDB watchdog overview report.
410
    $this->drupalGet(static::PATH_OVERVIEW);
411
    $session = $this->assertSession();
412
    $session->statusCodeEquals($statusCode);
413
    if ($statusCode == Response::HTTP_OK) {
414
      // MongoDB watchdog report was displayed.
415
      $expectedTexts = [
416
        'Recent log messages in MongoDB',
417
        'Filter log messages',
418
        'Type',
419
        'Severity',
420
        'Latest',
421
        'Severity',
422
        'Message',
423
        'Source',
424
      ];
425
      foreach ($expectedTexts as $expectedText) {
426
        $session->pageTextContains($expectedText);
427
      }
428
    }
429
430
    // View MongoDB watchdog page-not-found report.
431
    $this->drupalGet(self::PATH_NOT_FOUND);
432
    $session = $this->assertSession();
433
    $session->statusCodeEquals($statusCode);
434
    if ($statusCode == Response::HTTP_OK) {
435
      // MongoDB watchdog page-not-found report was displayed.
436
      $session->pageTextContains("Top 'page not found' errors in MongoDB");
437
    }
438
439
    // View MongoDB watchdog access-denied report.
440
    $this->drupalGet(static::PATH_DENIED);
441
    $session = $this->assertSession();
442
    $session->statusCodeEquals($statusCode);
443
    if ($statusCode == Response::HTTP_OK) {
444
      // MongoDB watchdog access-denied report was displayed.
445
      $session->pageTextContains("Top 'access denied' errors in MongoDB");
446
    }
447
448
    // Create an event to ensure an event page exists, using the standard PSR-3
449
    // service instead of the Drupal logger channel to ensure getting this
450
    // logger with its specific features.
451
    $expectedMessage = $this->randomString(32);
452
    /** @var \Drupal\mongodb_watchdog\Logger $logger */
453
    $logger = $this->container->get(Logger::SERVICE_LOGGER);
454
    $logger->info($expectedMessage, ['with' => 'context']);
455
456
    $selector = ['message' => $expectedMessage];
457
    $event = $logger->templateCollection()
458
      ->findOne($selector, MongoDb::ID_PROJECTION);
459
    $eventId = $event['_id'];
460
461
    // View MongoDB Watchdog event page.
462
    $this->drupalGet(static::PATH_EVENT_BASE . $eventId);
463
    $session = $this->assertSession();
464
    $session->statusCodeEquals($statusCode);
465
    // MongoDB watchdog event page was displayed.
466
    if ($statusCode == Response::HTTP_OK) {
467
      $expectedTexts = [
468
        'Event template',
469
        'ID',
470
        'Changed',
471
        'Count',
472
        'Type',
473
        'Message',
474
        'Severity',
475
        $eventId,
476
        'Event occurrences',
477
        $expectedMessage,
478
      ];
479
      foreach ($expectedTexts as $expectedText) {
480
        $session->pageTextContains($expectedText);
481
      }
482
    }
483
  }
484
485
  /**
486
   * The access and contents of the admin/reports/mongodb/watchdog[/*] pages.
487
   *
488
   * @todo verifyRowLimit(), verifyCron(), verifyEvents() as per DbLog.
489
   */
490
  public function testLoggerReportsAccess() {
491
    $expectations = [
492
      [$this->adminUser, Response::HTTP_OK],
493
      [$this->bigUser, Response::HTTP_OK],
494
      [$this->anyUser, Response::HTTP_FORBIDDEN],
495
    ];
496
    /** @var \Drupal\user\Entity\User $account */
497
    foreach ($expectations as $expectation) {
498
      [$account, $statusCode] = $expectation;
499
      $this->drupalLogin($account);
500
      $this->verifyReports($statusCode);
501
    }
502
  }
503
504
  /**
505
   * Test the UI clearing feature.
506
   */
507
  public function testLoggerAddAndUiClear() {
508
    // Drop the logger database to ensure no collections.
509
    $this->container->get(MongoDb::SERVICE_DB_FACTORY)
510
      ->get(Logger::DB_LOGGER)
511
      ->drop();
512
513
    /** @var \Drupal\Core\Logger\LoggerChannelInterface $loggerChannel */
514
    $loggerChannel = $this->container->get(Logger::SERVICE_CHANNEL);
515
    // Add a watchdog entry. Be sure not to include placeholder delimiters.
516
    $message = static::neuter($this->randomString(32));
517
    $loggerChannel->notice($message);
518
519
    // Make sure the collections were updated.
520
    /** @var \Drupal\mongodb_watchdog\Logger $logger */
521
    $logger = $this->container->get(Logger::SERVICE_LOGGER);
522
    $templates = $logger->templateCollection();
523
    $this->assertEquals(
524
      1,
525
      $templates->countDocuments(),
526
      'Logging created templates collection and added a template to it.'
527
    );
528
529
    $template = $templates->findOne(['message' => $message], MongoDb::ID_PROJECTION);
530
    $this->assertNotNull($template, "Logged message was found: [${message}]");
531
    $templateId = $template['_id'];
532
    $events = $logger->eventCollection($templateId);
533
    $this->assertEquals(
534
      1,
535
      $events->countDocuments(),
536
      'Logging created events collection and added a template to it.'
537
    );
538
539
    // Login the admin user.
540
    $this->drupalLogin($this->adminUser);
541
    // Now post to clear the db table.
542
    $this->drupalGet('admin/reports/mongodb/confirm');
543
    $this->submitForm([], 'Confirm');
544
545
    // Make the sure logs were dropped. After a UI clear, the templates
546
    // collection should exist, since it is recreated as a capped collection as
547
    // part of the clear, but be empty, and there should be no event collection.
548
    $count = $templates->countDocuments();
549
    $failMessage = 'Logger templates collection was cleared';
550
    if ($count > 0) {
551
      $options = ['projection' => ['_id' => 0, 'message' => 1]];
552
      $messages = iterator_to_array($templates->find([], $options));
553
      $failMessage = "Logger templates collection still contains messages: "
554
        . json_encode($messages);
555
    }
556
    $this->assertEquals(0, $count, $failMessage);
557
    $this->assertFalse(
558
      $logger->eventCollections()->valid(),
559
      "Event collections were dropped"
560
    );
561
  }
562
563
  /**
564
   * Test the dblog filter on admin/reports/dblog.
565
   */
566
  public function testFilter() {
567
    $this->drupalLogin($this->bigUser);
568
569
    // Clear log to ensure that only generated entries are found.
570
    $database = $this->container
571
      ->get(MongoDb::SERVICE_DB_FACTORY)
572
      ->get(Logger::DB_LOGGER);
573
    $database->drop();
574
575
    $logger = $this->container->get(Logger::SERVICE_LOGGER);
576
577
    // Generate watchdog entries.
578
    $typeNames = [];
579
    $types = [];
580
    for ($i = 0; $i < 3; $i++) {
581
      $typeNames[] = $typeName = $this->randomMachineName();
582
      $severity = RfcLogLevel::EMERGENCY;
583
      for ($j = 0; $j < 3; $j++) {
584
        $types[] = $type = [
585
          'count' => mt_rand(1, 5),
586
          'type' => $typeName,
587
          'severity' => $severity++,
588
        ];
589
        $this->insertLogEntries($logger, $type['count'], $type['type'], $type['severity']);
590
      }
591
    }
592
    // View the dblog.
593
    $this->drupalGet(self::PATH_OVERVIEW);
594
595
    // Confirm all the entries are displayed.
596
    $this->assertTypeCount($types);
597
598
    // Filter by each type and confirm that entries with various severities are
599
    // displayed.
600
    foreach ($typeNames as $typeName) {
601
      $edit = [
602
        'type[]' => [$typeName],
603
      ];
604
      $this->submitForm($edit, 'Filter');
605
606
      // Check whether the displayed event templates match our filter.
607
      $filteredTypes = array_filter(
608
        $types,
609
        function (array $type) use ($typeName) {
610
          return $type['type'] === $typeName;
611
        }
612
      );
613
      $this->assertTypeCount($filteredTypes);
614
    }
615
616
    // Set filter to match each of the combined filter sets and confirm the
617
    // entries displayed.
618
    foreach ($types as $type) {
619
      $edit = [
620
        'type[]' => $typeType = $type['type'],
621
        'severity[]' => $typeSeverity = $type['severity'],
622
      ];
623
      $this->submitForm($edit, 'Filter');
624
625
      $filteredTypes = array_filter(
626
        $types,
627
        function (array $type) use ($typeType, $typeSeverity) {
628
          return $type['type'] === $typeType && $type['severity'] == $typeSeverity;
629
        }
630
      );
631
632
      $this->assertTypeCount($filteredTypes);
633
    }
634
  }
635
636
}
637