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

LoggerTest::testLogClosure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Drupal\Tests\mongodb_watchdog\Kernel;
6
7
use Drupal\Core\Logger\RfcLogLevel;
8
use Drupal\Core\StringTranslation\StringTranslationTrait;
9
use Drupal\mongodb\MongoDb;
10
use Drupal\mongodb_watchdog\Logger;
11
use Drupal\Tests\mongodb\Kernel\MongoDbTestBase;
12
13
/**
14
 * Class LoggerTest tests the logging mechanism itself.
15
 *
16
 * @coversDefaultClass \Drupal\mongodb_watchdog\Logger
17
 *
18
 * @group MongoDB
19
 */
20
class LoggerTest extends MongoDbTestBase {
21
  use StringTranslationTrait;
22
23
  /**
24
   * The event templates collection.
25
   *
26
   * @var \MongoDB\Collection
27
   */
28
  protected $collection;
29
30
  /**
31
   * These modules need to be enabled.
32
   *
33
   * @var array
34
   */
35
  protected static $modules = [
36
    'system',
37
    MongoDb::MODULE,
38
    Logger::MODULE,
39
  ];
40
41
  /**
42
   * {@inheritdoc}
43
   */
44
  public function setUp(): void {
45
    parent::setUp();
46
    $this->installConfig(Logger::MODULE);
47
  }
48
49
  /**
50
   * {@inheritdoc}
51
   */
52
  protected function getSettingsArray(): array {
53
    $settings = parent::getSettingsArray();
54
    $settings['databases'][Logger::DB_LOGGER] = [
55
      static::CLIENT_TEST_ALIAS,
56
      $this->getDatabasePrefix(),
57
    ];
58
59
    return $settings;
60
  }
61
62
  /**
63
   * Assert that a given entry is present in the watchdog.
64
   *
65
   * @param string $message
66
   *   The message is present in the collection.
67
   */
68
  public function assertEntry($message) {
69
    $logged = $this->find($message);
70
    $this->assertNotNull($logged,
71
      (string) $this->t('Event %message is logged', ['%message' => $message]));
72
    $this->assertTrue(isset($logged['message']) && $logged['message'] == $message,
73
      (string) $this->t('Logged message is unchanged'));
74
  }
75
76
  /**
77
   * Assert that a given entry is not present in the watchdog.
78
   *
79
   * @param string $message
80
   *   The message which must not be present in the collection.
81
   */
82
  public function assertNoEntry($message) {
83
    $logged = $this->find($message);
84
    $this->assertNull($logged,
85
      (string) $this->t('Event %message is not logged', ['%message' => $message]));
86
  }
87
88
  /**
89
   * Replaces PSR-3 braces by angle brackets.
90
   *
91
   * Braces in log($l, $message, $c) will be interpreted as PSR-3 placeholders.
92
   * As such they need to be avoid when inserted randomly.
93
   *
94
   * @param string $message
95
   *   The raw message.
96
   *
97
   * @return string
98
   *   The replacement message.
99
   *
100
   * @see \Drupal\Core\Logger\LogMessageParserInterface::parseMessagePlaceholders()
101
   */
102
  public static function debrace(string $message): string {
103
    return str_replace(['{', '}'], ['<', '>'], $message);
104
  }
105
106
  /**
107
   * Simplified query to look for a logged message.
108
   *
109
   * @param string $message
110
   *   The message to look for.
111
   *
112
   * @return array|null
0 ignored issues
show
Documentation introduced by
Should the return type not be array|object|null? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
113
   *   The document containing the message, if any ; NULL otherwise.
114
   */
115
  protected function find($message) {
116
    $ret = $this->collection->findOne(['message' => $message]);
117
    return $ret;
118
  }
119
120
  /**
121
   * Ensure logging from a closure does not fail.
122
   *
123
   * @covers ::enhanceLogEntry
124
   *
125
   * @see https://www.drupal.org/project/mongodb/issues/3193195
126
   */
127
  public function testLogClosure() {
128
    $logger = $this->container->get(Logger::SERVICE_LOGGER);
129
    $closure = function () use ($logger) {
130
      $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.");
131
      return 1;
132
    };
133
    $this->assertEquals(1, $closure());
134
  }
135
136
  /**
137
   * Test the default and non-default mongodb_watchdog insertion behaviours.
138
   *
139
   * Make sure the module applies the watchdog_limit variable,
140
   *
141
   * @covers ::log
142
   */
143
  public function testWatchdogLimit() {
144
    $config = $this->config(Logger::CONFIG_NAME);
145
    $limit = $config->get(Logger::CONFIG_LIMIT);
146
    $this->assertEquals(RfcLogLevel::DEBUG, $limit,
147
      (string) $this->t('%name defaults to @level', [
148
        '%name' => Logger::CONFIG_LIMIT,
149
        '@level' => RfcLogLevel::DEBUG,
150
      ]));
151
152
    $logger = $this->container->get(Logger::SERVICE_LOGGER);
153
    $database = $this->container->get(MongoDb::SERVICE_DB_FACTORY)
154
      ->get(Logger::DB_LOGGER);
155
    $this->collection = $database->selectCollection(Logger::TEMPLATE_COLLECTION);
156
    $this->collection->drop();
157
158
    $message = static::debrace($this->randomString(32));
159
    $logger->log($limit, $message);
160
    $this->assertEntry($message);
161
162
    // Now request a higher level: unimportant events should be ignored. For
163
    // this to work, ensure limit is not the maximum level already.
164
    $logger->setLimit(RfcLogLevel::INFO);
165
    $this->collection->drop();
166
167
    $message = $this->randomMachineName(32);
168
    $logger->debug($message);
169
    $this->assertNoEntry($message);
170
171
    // ... but events at the limit or more important should be logged.
172
    $message = $this->randomMachineName(32);
173
    $logger->notice($message);
174
    $this->assertEntry($message);
175
176
    $message = $this->randomMachineName(32);
177
    $logger->error($message);
178
    $this->assertEntry($message);
179
  }
180
181
}
182