Passed
Push — 8.x-2.x ( 9af07d...3011f1 )
by Frédéric G.
05:35
created

ControllerTest::verifyReports()   B

Complexity

Conditions 9
Paths 96

Size

Total Lines 90
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 9
eloc 60
c 2
b 0
f 0
nc 96
nop 1
dl 0
loc 90
rs 7.3171

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
    $this->assertNotNull($event);
460
    $eventId = $event['_id'];
461
462
    // View MongoDB Watchdog event page.
463
    $this->drupalGet(static::PATH_EVENT_BASE . $eventId);
464
    $session = $this->assertSession();
465
    $session->statusCodeEquals($statusCode);
466
    // MongoDB watchdog event page was displayed.
467
    if ($statusCode == Response::HTTP_OK) {
468
      $expectedTexts = [
469
        'Event template',
470
        'ID',
471
        'Changed',
472
        'Count',
473
        'Type',
474
        'Message',
475
        'Severity',
476
        $eventId,
477
        'Event occurrences',
478
        $expectedMessage,
479
      ];
480
      foreach ($expectedTexts as $expectedText) {
481
        $session->pageTextContains($expectedText);
482
      }
483
    }
484
  }
485
486
  /**
487
   * The access and contents of the admin/reports/mongodb/watchdog[/*] pages.
488
   *
489
   * @todo verifyRowLimit(), verifyCron(), verifyEvents() as per DbLog.
490
   */
491
  public function testLoggerReportsAccess() {
492
    $expectations = [
493
      [$this->adminUser, Response::HTTP_OK],
494
      [$this->bigUser, Response::HTTP_OK],
495
      [$this->anyUser, Response::HTTP_FORBIDDEN],
496
    ];
497
    /** @var \Drupal\user\Entity\User $account */
498
    foreach ($expectations as $expectation) {
499
      [$account, $statusCode] = $expectation;
500
      $this->drupalLogin($account);
501
      $this->verifyReports($statusCode);
502
    }
503
  }
504
505
  /**
506
   * Test the UI clearing feature.
507
   */
508
  public function testLoggerAddAndUiClear() {
509
    // Drop the logger database to ensure no collections.
510
    $this->container->get(MongoDb::SERVICE_DB_FACTORY)
511
      ->get(Logger::DB_LOGGER)
512
      ->drop();
513
514
    /** @var \Drupal\Core\Logger\LoggerChannelInterface $loggerChannel */
515
    $loggerChannel = $this->container->get(Logger::SERVICE_CHANNEL);
516
    // Add a watchdog entry. Be sure not to include placeholder delimiters.
517
    $message = static::neuter($this->randomString(32));
518
    $loggerChannel->notice($message);
519
520
    // Make sure the collections were updated.
521
    /** @var \Drupal\mongodb_watchdog\Logger $logger */
522
    $logger = $this->container->get(Logger::SERVICE_LOGGER);
523
    $templates = $logger->templateCollection();
524
    $this->assertEquals(
525
      1,
526
      $templates->countDocuments(),
527
      'Logging created templates collection and added a template to it.'
528
    );
529
530
    $template = $templates->findOne(['message' => $message], MongoDb::ID_PROJECTION);
531
    $this->assertNotNull($template, "Logged message was found: [${message}]");
532
    $templateId = $template['_id'];
533
    $events = $logger->eventCollection($templateId);
534
    $this->assertEquals(
535
      1,
536
      $events->countDocuments(),
537
      'Logging created events collection and added a template to it.'
538
    );
539
540
    // Login the admin user.
541
    $this->drupalLogin($this->adminUser);
542
    // Now post to clear the db table.
543
    $this->drupalGet('admin/reports/mongodb/confirm');
544
    $this->submitForm([], 'Confirm');
545
546
    // Make the sure logs were dropped. After a UI clear, the templates
547
    // collection should exist, since it is recreated as a capped collection as
548
    // part of the clear, but be empty, and there should be no event collection.
549
    $count = $templates->countDocuments();
550
    $failMessage = 'Logger templates collection was cleared';
551
    if ($count > 0) {
552
      $options = ['projection' => ['_id' => 0, 'message' => 1]];
553
      $messages = iterator_to_array($templates->find([], $options));
554
      $failMessage = "Logger templates collection still contains messages: "
555
        . json_encode($messages);
556
    }
557
    $this->assertEquals(0, $count, $failMessage);
558
    $this->assertFalse(
559
      $logger->eventCollections()->valid(),
560
      "Event collections were dropped"
561
    );
562
  }
563
564
  /**
565
   * Test the dblog filter on admin/reports/dblog.
566
   */
567
  public function testFilter() {
568
    $this->drupalLogin($this->bigUser);
569
570
    // Clear log to ensure that only generated entries are found.
571
    $database = $this->container
572
      ->get(MongoDb::SERVICE_DB_FACTORY)
573
      ->get(Logger::DB_LOGGER);
574
    $database->drop();
575
576
    $logger = $this->container->get(Logger::SERVICE_LOGGER);
577
578
    // Generate watchdog entries.
579
    $typeNames = [];
580
    $types = [];
581
    for ($i = 0; $i < 3; $i++) {
582
      $typeNames[] = $typeName = $this->randomMachineName();
583
      $severity = RfcLogLevel::EMERGENCY;
584
      for ($j = 0; $j < 3; $j++) {
585
        $types[] = $type = [
586
          'count' => mt_rand(1, 5),
587
          'type' => $typeName,
588
          'severity' => $severity++,
589
        ];
590
        $this->insertLogEntries($logger, $type['count'], $type['type'], $type['severity']);
591
      }
592
    }
593
    // View the dblog.
594
    $this->drupalGet(self::PATH_OVERVIEW);
595
596
    // Confirm all the entries are displayed.
597
    $this->assertTypeCount($types);
598
599
    // Filter by each type and confirm that entries with various severities are
600
    // displayed.
601
    foreach ($typeNames as $typeName) {
602
      $edit = [
603
        'type[]' => [$typeName],
604
      ];
605
      $this->submitForm($edit, 'Filter');
606
607
      // Check whether the displayed event templates match our filter.
608
      $filteredTypes = array_filter(
609
        $types,
610
        function (array $type) use ($typeName) {
611
          return $type['type'] === $typeName;
612
        }
613
      );
614
      $this->assertTypeCount($filteredTypes);
615
    }
616
617
    // Set filter to match each of the combined filter sets and confirm the
618
    // entries displayed.
619
    foreach ($types as $type) {
620
      $edit = [
621
        'type[]' => $typeType = $type['type'],
622
        'severity[]' => $typeSeverity = $type['severity'],
623
      ];
624
      $this->submitForm($edit, 'Filter');
625
626
      $filteredTypes = array_filter(
627
        $types,
628
        function (array $type) use ($typeType, $typeSeverity) {
629
          return $type['type'] === $typeType && $type['severity'] == $typeSeverity;
630
        }
631
      );
632
633
      $this->assertTypeCount($filteredTypes);
634
    }
635
  }
636
637
}
638