annotate core/modules/dblog/tests/src/Functional/DbLogTest.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Tests\dblog\Functional;
Chris@0 4
Chris@0 5 use Drupal\Component\Utility\Html;
Chris@0 6 use Drupal\Component\Utility\Unicode;
Chris@18 7 use Drupal\Core\Database\Database;
Chris@0 8 use Drupal\Core\Logger\RfcLogLevel;
Chris@0 9 use Drupal\Core\Url;
Chris@0 10 use Drupal\dblog\Controller\DbLogController;
Chris@0 11 use Drupal\Tests\BrowserTestBase;
Chris@0 12
Chris@0 13 /**
Chris@0 14 * Generate events and verify dblog entries; verify user access to log reports
Chris@0 15 * based on permissions.
Chris@0 16 *
Chris@0 17 * @group dblog
Chris@0 18 */
Chris@0 19 class DbLogTest extends BrowserTestBase {
Chris@17 20 use FakeLogEntries;
Chris@0 21
Chris@0 22 /**
Chris@0 23 * Modules to enable.
Chris@0 24 *
Chris@0 25 * @var array
Chris@0 26 */
Chris@0 27 public static $modules = ['dblog', 'node', 'forum', 'help', 'block'];
Chris@0 28
Chris@0 29 /**
Chris@0 30 * A user with some relevant administrative permissions.
Chris@0 31 *
Chris@0 32 * @var \Drupal\user\UserInterface
Chris@0 33 */
Chris@0 34 protected $adminUser;
Chris@0 35
Chris@0 36 /**
Chris@0 37 * A user without any permissions.
Chris@0 38 *
Chris@0 39 * @var \Drupal\user\UserInterface
Chris@0 40 */
Chris@0 41 protected $webUser;
Chris@0 42
Chris@0 43 /**
Chris@0 44 * {@inheritdoc}
Chris@0 45 */
Chris@0 46 protected function setUp() {
Chris@0 47 parent::setUp();
Chris@0 48 $this->drupalPlaceBlock('system_breadcrumb_block');
Chris@0 49 $this->drupalPlaceBlock('page_title_block');
Chris@0 50
Chris@0 51 // Create users with specific permissions.
Chris@0 52 $this->adminUser = $this->drupalCreateUser(['administer site configuration', 'access administration pages', 'access site reports', 'administer users']);
Chris@0 53 $this->webUser = $this->drupalCreateUser([]);
Chris@0 54 }
Chris@0 55
Chris@0 56 /**
Chris@0 57 * Tests Database Logging module functionality through interfaces.
Chris@0 58 *
Chris@0 59 * First logs in users, then creates database log events, and finally tests
Chris@0 60 * Database Logging module functionality through both the admin and user
Chris@0 61 * interfaces.
Chris@0 62 */
Chris@0 63 public function testDbLog() {
Chris@0 64 // Log in the admin user.
Chris@0 65 $this->drupalLogin($this->adminUser);
Chris@0 66
Chris@0 67 $row_limit = 100;
Chris@0 68 $this->verifyRowLimit($row_limit);
Chris@0 69 $this->verifyEvents();
Chris@0 70 $this->verifyReports();
Chris@0 71 $this->verifyBreadcrumbs();
Chris@0 72 $this->verifyLinkEscaping();
Chris@0 73 // Verify the overview table sorting.
Chris@0 74 $orders = ['Date', 'Type', 'User'];
Chris@0 75 $sorts = ['asc', 'desc'];
Chris@0 76 foreach ($orders as $order) {
Chris@0 77 foreach ($sorts as $sort) {
Chris@0 78 $this->verifySort($sort, $order);
Chris@0 79 }
Chris@0 80 }
Chris@0 81
Chris@0 82 // Log in the regular user.
Chris@0 83 $this->drupalLogin($this->webUser);
Chris@0 84 $this->verifyReports(403);
Chris@0 85 }
Chris@0 86
Chris@0 87 /**
Chris@0 88 * Test individual log event page.
Chris@0 89 */
Chris@0 90 public function testLogEventPage() {
Chris@0 91 // Login the admin user.
Chris@0 92 $this->drupalLogin($this->adminUser);
Chris@0 93
Chris@0 94 // Since referrer and location links vary by how the tests are run, inject
Chris@0 95 // fake log data to test these.
Chris@0 96 $context = [
Chris@0 97 'request_uri' => 'http://example.com?dblog=1',
Chris@0 98 'referer' => 'http://example.org?dblog=2',
Chris@0 99 'uid' => 0,
Chris@0 100 'channel' => 'testing',
Chris@0 101 'link' => 'foo/bar',
Chris@0 102 'ip' => '0.0.1.0',
Chris@0 103 'timestamp' => REQUEST_TIME,
Chris@0 104 ];
Chris@0 105 \Drupal::service('logger.dblog')->log(RfcLogLevel::NOTICE, 'Test message', $context);
Chris@0 106 $wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
Chris@0 107
Chris@0 108 // Verify the links appear correctly.
Chris@0 109 $this->drupalGet('admin/reports/dblog/event/' . $wid);
Chris@0 110 $this->assertLinkByHref($context['request_uri']);
Chris@0 111 $this->assertLinkByHref($context['referer']);
Chris@0 112
Chris@0 113 // Verify hostname.
Chris@0 114 $this->assertRaw($context['ip'], 'Found hostname on the detail page.');
Chris@0 115
Chris@18 116 // Verify location.
Chris@18 117 $this->assertRaw($context['request_uri'], 'Found location on the detail page.');
Chris@18 118
Chris@0 119 // Verify severity.
Chris@0 120 $this->assertText('Notice', 'The severity was properly displayed on the detail page.');
Chris@0 121 }
Chris@0 122
Chris@0 123 /**
Chris@18 124 * Test individual log event page with missing log attributes.
Chris@18 125 *
Chris@18 126 * In some cases few log attributes are missing. For example:
Chris@18 127 * - Missing referer: When request is made to a specific url directly and
Chris@18 128 * error occurred. In this case there is no referer.
Chris@18 129 * - Incorrect location: When location attribute is incorrect uri which can
Chris@18 130 * not be used to generate a valid link.
Chris@18 131 */
Chris@18 132 public function testLogEventPageWithMissingInfo() {
Chris@18 133 $this->drupalLogin($this->adminUser);
Chris@18 134 $connection = Database::getConnection();
Chris@18 135
Chris@18 136 // Test log event page with missing referer.
Chris@18 137 $this->generateLogEntries(1, [
Chris@18 138 'referer' => NULL,
Chris@18 139 ]);
Chris@18 140 $wid = $connection->query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
Chris@18 141 $this->drupalGet('admin/reports/dblog/event/' . $wid);
Chris@18 142
Chris@18 143 // Verify table headers are present, even though the referrer is missing.
Chris@18 144 $this->assertText('Referrer', 'Referrer header is present on the detail page.');
Chris@18 145
Chris@18 146 // Verify severity.
Chris@18 147 $this->assertText('Notice', 'The severity is properly displayed on the detail page.');
Chris@18 148
Chris@18 149 // Test log event page with incorrect location.
Chris@18 150 $request_uri = '/some/incorrect/url';
Chris@18 151 $this->generateLogEntries(1, [
Chris@18 152 'request_uri' => $request_uri,
Chris@18 153 ]);
Chris@18 154 $wid = $connection->query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
Chris@18 155 $this->drupalGet('admin/reports/dblog/event/' . $wid);
Chris@18 156
Chris@18 157 // Verify table headers are present.
Chris@18 158 $this->assertText('Location', 'Location header is present on the detail page.');
Chris@18 159
Chris@18 160 // Verify severity.
Chris@18 161 $this->assertText('Notice', 'The severity is properly displayed on the detail page.');
Chris@18 162
Chris@18 163 // Verify location is available as plain text.
Chris@18 164 $this->assertEquals($request_uri, $this->cssSelect('table.dblog-event > tbody > tr:nth-child(4) > td')[0]->getHtml());
Chris@18 165 $this->assertNoLink($request_uri);
Chris@18 166 }
Chris@18 167
Chris@18 168 /**
Chris@0 169 * Verifies setting of the database log row limit.
Chris@0 170 *
Chris@0 171 * @param int $row_limit
Chris@0 172 * The row limit.
Chris@0 173 */
Chris@0 174 private function verifyRowLimit($row_limit) {
Chris@0 175 // Change the database log row limit.
Chris@0 176 $edit = [];
Chris@0 177 $edit['dblog_row_limit'] = $row_limit;
Chris@0 178 $this->drupalPostForm('admin/config/development/logging', $edit, t('Save configuration'));
Chris@0 179 $this->assertResponse(200);
Chris@0 180
Chris@0 181 // Check row limit variable.
Chris@0 182 $current_limit = $this->config('dblog.settings')->get('row_limit');
Chris@0 183 $this->assertTrue($current_limit == $row_limit, format_string('[Cache] Row limit variable of @count equals row limit of @limit', ['@count' => $current_limit, '@limit' => $row_limit]));
Chris@0 184 }
Chris@0 185
Chris@0 186 /**
Chris@0 187 * Clear the entry logs by clicking on 'Clear log messages' button.
Chris@0 188 */
Chris@0 189 protected function clearLogsEntries() {
Chris@0 190 $this->drupalGet(Url::fromRoute('dblog.confirm'));
Chris@0 191 }
Chris@0 192
Chris@0 193 /**
Chris@0 194 * Filters the logs according to the specific severity and log entry type.
Chris@0 195 *
Chris@0 196 * @param string $type
Chris@0 197 * (optional) The log entry type.
Chris@0 198 * @param string $severity
Chris@0 199 * (optional) The log entry severity.
Chris@0 200 */
Chris@0 201 protected function filterLogsEntries($type = NULL, $severity = NULL) {
Chris@0 202 $edit = [];
Chris@0 203 if (isset($type)) {
Chris@0 204 $edit['type[]'] = $type;
Chris@0 205 }
Chris@0 206 if (isset($severity)) {
Chris@0 207 $edit['severity[]'] = $severity;
Chris@0 208 }
Chris@0 209 $this->drupalPostForm(NULL, $edit, t('Filter'));
Chris@0 210 }
Chris@0 211
Chris@0 212 /**
Chris@0 213 * Confirms that database log reports are displayed at the correct paths.
Chris@0 214 *
Chris@0 215 * @param int $response
Chris@0 216 * (optional) HTTP response code. Defaults to 200.
Chris@0 217 */
Chris@0 218 private function verifyReports($response = 200) {
Chris@0 219 // View the database log help page.
Chris@0 220 $this->drupalGet('admin/help/dblog');
Chris@0 221 $this->assertResponse($response);
Chris@0 222 if ($response == 200) {
Chris@0 223 $this->assertText(t('Database Logging'), 'DBLog help was displayed');
Chris@0 224 }
Chris@0 225
Chris@0 226 // View the database log report page.
Chris@0 227 $this->drupalGet('admin/reports/dblog');
Chris@0 228 $this->assertResponse($response);
Chris@0 229 if ($response == 200) {
Chris@0 230 $this->assertText(t('Recent log messages'), 'DBLog report was displayed');
Chris@0 231 }
Chris@0 232
Chris@0 233 $this->drupalGet('admin/reports/dblog/confirm');
Chris@0 234 $this->assertResponse($response);
Chris@0 235 if ($response == 200) {
Chris@0 236 $this->assertText(t('Are you sure you want to delete the recent logs?'), 'DBLog clear logs form was displayed');
Chris@0 237 }
Chris@0 238
Chris@0 239 // View the database log page-not-found report page.
Chris@0 240 $this->drupalGet('admin/reports/page-not-found');
Chris@0 241 $this->assertResponse($response);
Chris@0 242 if ($response == 200) {
Chris@0 243 $this->assertText("Top 'page not found' errors", 'DBLog page-not-found report was displayed');
Chris@0 244 }
Chris@0 245
Chris@0 246 // View the database log access-denied report page.
Chris@0 247 $this->drupalGet('admin/reports/access-denied');
Chris@0 248 $this->assertResponse($response);
Chris@0 249 if ($response == 200) {
Chris@0 250 $this->assertText("Top 'access denied' errors", 'DBLog access-denied report was displayed');
Chris@0 251 }
Chris@0 252
Chris@0 253 // View the database log event page.
Chris@0 254 $wid = db_query('SELECT MIN(wid) FROM {watchdog}')->fetchField();
Chris@0 255 $this->drupalGet('admin/reports/dblog/event/' . $wid);
Chris@0 256 $this->assertResponse($response);
Chris@0 257 if ($response == 200) {
Chris@0 258 $this->assertText(t('Details'), 'DBLog event node was displayed');
Chris@0 259 }
Chris@0 260 }
Chris@0 261
Chris@0 262 /**
Chris@0 263 * Generates and then verifies breadcrumbs.
Chris@0 264 */
Chris@0 265 private function verifyBreadcrumbs() {
Chris@0 266 // View the database log event page.
Chris@0 267 $wid = db_query('SELECT MIN(wid) FROM {watchdog}')->fetchField();
Chris@0 268 $this->drupalGet('admin/reports/dblog/event/' . $wid);
Chris@0 269 $xpath = '//nav[@class="breadcrumb"]/ol/li[last()]/a';
Chris@0 270 $this->assertEqual(current($this->xpath($xpath))->getText(), 'Recent log messages', 'DBLogs link displayed at breadcrumb in event page.');
Chris@0 271 }
Chris@0 272
Chris@0 273 /**
Chris@0 274 * Generates and then verifies various types of events.
Chris@0 275 */
Chris@0 276 private function verifyEvents() {
Chris@0 277 // Invoke events.
Chris@0 278 $this->doUser();
Chris@0 279 $this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]);
Chris@0 280 $this->drupalCreateContentType(['type' => 'page', 'name' => t('Basic page')]);
Chris@0 281 $this->doNode('article');
Chris@0 282 $this->doNode('page');
Chris@0 283 $this->doNode('forum');
Chris@0 284
Chris@0 285 // When a user account is canceled, any content they created remains but the
Chris@0 286 // uid = 0. Records in the watchdog table related to that user have the uid
Chris@0 287 // set to zero.
Chris@0 288 }
Chris@0 289
Chris@0 290 /**
Chris@0 291 * Verifies the sorting functionality of the database logging reports table.
Chris@0 292 *
Chris@0 293 * @param string $sort
Chris@0 294 * The sort direction.
Chris@0 295 * @param string $order
Chris@0 296 * The order by which the table should be sorted.
Chris@0 297 */
Chris@0 298 public function verifySort($sort = 'asc', $order = 'Date') {
Chris@0 299 $this->drupalGet('admin/reports/dblog', ['query' => ['sort' => $sort, 'order' => $order]]);
Chris@0 300 $this->assertResponse(200);
Chris@0 301 $this->assertText(t('Recent log messages'), 'DBLog report was displayed correctly and sorting went fine.');
Chris@0 302 }
Chris@0 303
Chris@0 304 /**
Chris@0 305 * Tests the escaping of links in the operation row of a database log detail
Chris@0 306 * page.
Chris@0 307 */
Chris@0 308 private function verifyLinkEscaping() {
Chris@0 309 $link = \Drupal::l('View', Url::fromRoute('entity.node.canonical', ['node' => 1]));
Chris@0 310 $message = 'Log entry added to do the verifyLinkEscaping test.';
Chris@0 311 $this->generateLogEntries(1, [
Chris@0 312 'message' => $message,
Chris@0 313 'link' => $link,
Chris@0 314 ]);
Chris@0 315
Chris@18 316 $result = Database::getConnection()->queryRange('SELECT wid FROM {watchdog} ORDER BY wid DESC', 0, 1);
Chris@0 317 $this->drupalGet('admin/reports/dblog/event/' . $result->fetchField());
Chris@0 318
Chris@0 319 // Check if the link exists (unescaped).
Chris@0 320 $this->assertRaw($link);
Chris@0 321 }
Chris@0 322
Chris@0 323 /**
Chris@0 324 * Generates and then verifies some user events.
Chris@0 325 */
Chris@0 326 private function doUser() {
Chris@0 327 // Set user variables.
Chris@0 328 $name = $this->randomMachineName();
Chris@0 329 $pass = user_password();
Chris@0 330 // Add a user using the form to generate an add user event (which is not
Chris@0 331 // triggered by drupalCreateUser).
Chris@0 332 $edit = [];
Chris@0 333 $edit['name'] = $name;
Chris@0 334 $edit['mail'] = $name . '@example.com';
Chris@0 335 $edit['pass[pass1]'] = $pass;
Chris@0 336 $edit['pass[pass2]'] = $pass;
Chris@0 337 $edit['status'] = 1;
Chris@0 338 $this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
Chris@0 339 $this->assertResponse(200);
Chris@0 340 // Retrieve the user object.
Chris@0 341 $user = user_load_by_name($name);
Chris@0 342 $this->assertTrue($user != NULL, format_string('User @name was loaded', ['@name' => $name]));
Chris@0 343 // pass_raw property is needed by drupalLogin.
Chris@0 344 $user->passRaw = $pass;
Chris@0 345 // Log in user.
Chris@0 346 $this->drupalLogin($user);
Chris@0 347 // Log out user.
Chris@0 348 $this->drupalLogout();
Chris@0 349 // Fetch the row IDs in watchdog that relate to the user.
Chris@0 350 $result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', [':uid' => $user->id()]);
Chris@0 351 foreach ($result as $row) {
Chris@0 352 $ids[] = $row->wid;
Chris@0 353 }
Chris@0 354 $count_before = (isset($ids)) ? count($ids) : 0;
Chris@18 355 $this->assertTrue($count_before > 0, format_string('DBLog contains @count records for @name', ['@count' => $count_before, '@name' => $user->getAccountName()]));
Chris@0 356
Chris@0 357 // Log in the admin user.
Chris@0 358 $this->drupalLogin($this->adminUser);
Chris@0 359 // Delete the user created at the start of this test.
Chris@0 360 // We need to POST here to invoke batch_process() in the internal browser.
Chris@0 361 $this->drupalPostForm('user/' . $user->id() . '/cancel', ['user_cancel_method' => 'user_cancel_reassign'], t('Cancel account'));
Chris@0 362
Chris@0 363 // View the database log report.
Chris@0 364 $this->drupalGet('admin/reports/dblog');
Chris@0 365 $this->assertResponse(200);
Chris@0 366
Chris@0 367 // Verify that the expected events were recorded.
Chris@0 368 // Add user.
Chris@0 369 // Default display includes name and email address; if too long, the email
Chris@0 370 // address is replaced by three periods.
Chris@0 371 $this->assertLogMessage(t('New user: %name %email.', ['%name' => $name, '%email' => '<' . $user->getEmail() . '>']), 'DBLog event was recorded: [add user]');
Chris@0 372 // Log in user.
Chris@0 373 $this->assertLogMessage(t('Session opened for %name.', ['%name' => $name]), 'DBLog event was recorded: [login user]');
Chris@0 374 // Log out user.
Chris@0 375 $this->assertLogMessage(t('Session closed for %name.', ['%name' => $name]), 'DBLog event was recorded: [logout user]');
Chris@0 376 // Delete user.
Chris@0 377 $message = t('Deleted user: %name %email.', ['%name' => $name, '%email' => '<' . $user->getEmail() . '>']);
Chris@0 378 $message_text = Unicode::truncate(Html::decodeEntities(strip_tags($message)), 56, TRUE, TRUE);
Chris@0 379 // Verify that the full message displays on the details page.
Chris@0 380 $link = FALSE;
Chris@0 381 if ($links = $this->xpath('//a[text()="' . $message_text . '"]')) {
Chris@0 382 // Found link with the message text.
Chris@0 383 $links = array_shift($links);
Chris@0 384 $value = $links->getAttribute('href');
Chris@0 385
Chris@0 386 // Extract link to details page.
Chris@17 387 $link = mb_substr($value, strpos($value, 'admin/reports/dblog/event/'));
Chris@0 388 $this->drupalGet($link);
Chris@0 389 // Check for full message text on the details page.
Chris@0 390 $this->assertRaw($message, 'DBLog event details was found: [delete user]');
Chris@0 391 }
Chris@0 392 $this->assertTrue($link, 'DBLog event was recorded: [delete user]');
Chris@0 393 // Visit random URL (to generate page not found event).
Chris@0 394 $not_found_url = $this->randomMachineName(60);
Chris@0 395 $this->drupalGet($not_found_url);
Chris@0 396 $this->assertResponse(404);
Chris@0 397 // View the database log page-not-found report page.
Chris@0 398 $this->drupalGet('admin/reports/page-not-found');
Chris@0 399 $this->assertResponse(200);
Chris@0 400 // Check that full-length URL displayed.
Chris@0 401 $this->assertText($not_found_url, 'DBLog event was recorded: [page not found]');
Chris@0 402 }
Chris@0 403
Chris@0 404 /**
Chris@0 405 * Generates and then verifies some node events.
Chris@0 406 *
Chris@0 407 * @param string $type
Chris@0 408 * A node type (e.g., 'article', 'page' or 'forum').
Chris@0 409 */
Chris@0 410 private function doNode($type) {
Chris@0 411 // Create user.
Chris@0 412 $perm = ['create ' . $type . ' content', 'edit own ' . $type . ' content', 'delete own ' . $type . ' content'];
Chris@0 413 $user = $this->drupalCreateUser($perm);
Chris@0 414 // Log in user.
Chris@0 415 $this->drupalLogin($user);
Chris@0 416
Chris@0 417 // Create a node using the form in order to generate an add content event
Chris@0 418 // (which is not triggered by drupalCreateNode).
Chris@0 419 $edit = $this->getContent($type);
Chris@0 420 $title = $edit['title[0][value]'];
Chris@0 421 $this->drupalPostForm('node/add/' . $type, $edit, t('Save'));
Chris@0 422 $this->assertResponse(200);
Chris@0 423 // Retrieve the node object.
Chris@0 424 $node = $this->drupalGetNodeByTitle($title);
Chris@0 425 $this->assertTrue($node != NULL, format_string('Node @title was loaded', ['@title' => $title]));
Chris@0 426 // Edit the node.
Chris@0 427 $edit = $this->getContentUpdate($type);
Chris@0 428 $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save'));
Chris@0 429 $this->assertResponse(200);
Chris@0 430 // Delete the node.
Chris@0 431 $this->drupalPostForm('node/' . $node->id() . '/delete', [], t('Delete'));
Chris@0 432 $this->assertResponse(200);
Chris@0 433 // View the node (to generate page not found event).
Chris@0 434 $this->drupalGet('node/' . $node->id());
Chris@0 435 $this->assertResponse(404);
Chris@0 436 // View the database log report (to generate access denied event).
Chris@0 437 $this->drupalGet('admin/reports/dblog');
Chris@0 438 $this->assertResponse(403);
Chris@0 439
Chris@0 440 // Log in the admin user.
Chris@0 441 $this->drupalLogin($this->adminUser);
Chris@0 442 // View the database log report.
Chris@0 443 $this->drupalGet('admin/reports/dblog');
Chris@0 444 $this->assertResponse(200);
Chris@0 445
Chris@0 446 // Verify that node events were recorded.
Chris@0 447 // Was node content added?
Chris@0 448 $this->assertLogMessage(t('@type: added %title.', ['@type' => $type, '%title' => $title]), 'DBLog event was recorded: [content added]');
Chris@0 449 // Was node content updated?
Chris@0 450 $this->assertLogMessage(t('@type: updated %title.', ['@type' => $type, '%title' => $title]), 'DBLog event was recorded: [content updated]');
Chris@0 451 // Was node content deleted?
Chris@0 452 $this->assertLogMessage(t('@type: deleted %title.', ['@type' => $type, '%title' => $title]), 'DBLog event was recorded: [content deleted]');
Chris@0 453
Chris@0 454 // View the database log access-denied report page.
Chris@0 455 $this->drupalGet('admin/reports/access-denied');
Chris@0 456 $this->assertResponse(200);
Chris@0 457 // Verify that the 'access denied' event was recorded.
Chris@0 458 $this->assertText('admin/reports/dblog', 'DBLog event was recorded: [access denied]');
Chris@0 459
Chris@0 460 // View the database log page-not-found report page.
Chris@0 461 $this->drupalGet('admin/reports/page-not-found');
Chris@0 462 $this->assertResponse(200);
Chris@0 463 // Verify that the 'page not found' event was recorded.
Chris@0 464 $this->assertText('node/' . $node->id(), 'DBLog event was recorded: [page not found]');
Chris@0 465 }
Chris@0 466
Chris@0 467 /**
Chris@0 468 * Creates random content based on node content type.
Chris@0 469 *
Chris@0 470 * @param string $type
Chris@0 471 * Node content type (e.g., 'article').
Chris@0 472 *
Chris@0 473 * @return array
Chris@0 474 * Random content needed by various node types.
Chris@0 475 */
Chris@0 476 private function getContent($type) {
Chris@0 477 switch ($type) {
Chris@0 478 case 'forum':
Chris@0 479 $content = [
Chris@0 480 'title[0][value]' => $this->randomMachineName(8),
Chris@0 481 'taxonomy_forums' => 1,
Chris@0 482 'body[0][value]' => $this->randomMachineName(32),
Chris@0 483 ];
Chris@0 484 break;
Chris@0 485
Chris@0 486 default:
Chris@0 487 $content = [
Chris@0 488 'title[0][value]' => $this->randomMachineName(8),
Chris@0 489 'body[0][value]' => $this->randomMachineName(32),
Chris@0 490 ];
Chris@0 491 break;
Chris@0 492 }
Chris@0 493 return $content;
Chris@0 494 }
Chris@0 495
Chris@0 496 /**
Chris@0 497 * Creates random content as an update based on node content type.
Chris@0 498 *
Chris@0 499 * @param string $type
Chris@0 500 * Node content type (e.g., 'article').
Chris@0 501 *
Chris@0 502 * @return array
Chris@0 503 * Random content needed by various node types.
Chris@0 504 */
Chris@0 505 private function getContentUpdate($type) {
Chris@0 506 $content = [
Chris@0 507 'body[0][value]' => $this->randomMachineName(32),
Chris@0 508 ];
Chris@0 509 return $content;
Chris@0 510 }
Chris@0 511
Chris@0 512 /**
Chris@0 513 * Tests the addition and clearing of log events through the admin interface.
Chris@0 514 *
Chris@0 515 * Logs in the admin user, creates a database log event, and tests the
Chris@0 516 * functionality of clearing the database log through the admin interface.
Chris@0 517 */
Chris@0 518 public function testDBLogAddAndClear() {
Chris@0 519 global $base_root;
Chris@0 520 // Get a count of how many watchdog entries already exist.
Chris@0 521 $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
Chris@0 522 $log = [
Chris@0 523 'channel' => 'system',
Chris@0 524 'message' => 'Log entry added to test the doClearTest clear down.',
Chris@0 525 'variables' => [],
Chris@0 526 'severity' => RfcLogLevel::NOTICE,
Chris@0 527 'link' => NULL,
Chris@0 528 'uid' => $this->adminUser->id(),
Chris@0 529 'request_uri' => $base_root . \Drupal::request()->getRequestUri(),
Chris@0 530 'referer' => \Drupal::request()->server->get('HTTP_REFERER'),
Chris@0 531 'ip' => '127.0.0.1',
Chris@0 532 'timestamp' => REQUEST_TIME,
Chris@0 533 ];
Chris@0 534 // Add a watchdog entry.
Chris@0 535 $this->container->get('logger.dblog')->log($log['severity'], $log['message'], $log);
Chris@0 536 // Make sure the table count has actually been incremented.
Chris@0 537 $this->assertEqual($count + 1, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), format_string('\Drupal\dblog\Logger\DbLog->log() added an entry to the dblog :count', [':count' => $count]));
Chris@0 538 // Log in the admin user.
Chris@0 539 $this->drupalLogin($this->adminUser);
Chris@0 540 // Post in order to clear the database table.
Chris@0 541 $this->clearLogsEntries();
Chris@0 542 // Confirm that the logs should be cleared.
Chris@0 543 $this->drupalPostForm(NULL, [], 'Confirm');
Chris@0 544 // Count the rows in watchdog that previously related to the deleted user.
Chris@0 545 $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
Chris@0 546 $this->assertEqual($count, 0, format_string('DBLog contains :count records after a clear.', [':count' => $count]));
Chris@0 547 }
Chris@0 548
Chris@0 549 /**
Chris@0 550 * Tests the database log filter functionality at admin/reports/dblog.
Chris@0 551 */
Chris@0 552 public function testFilter() {
Chris@0 553 $this->drupalLogin($this->adminUser);
Chris@0 554
Chris@0 555 // Clear the log to ensure that only generated entries will be found.
Chris@18 556 Database::getConnection()->delete('watchdog')->execute();
Chris@0 557
Chris@0 558 // Generate 9 random watchdog entries.
Chris@0 559 $type_names = [];
Chris@0 560 $types = [];
Chris@0 561 for ($i = 0; $i < 3; $i++) {
Chris@0 562 $type_names[] = $type_name = $this->randomMachineName();
Chris@0 563 $severity = RfcLogLevel::EMERGENCY;
Chris@0 564 for ($j = 0; $j < 3; $j++) {
Chris@0 565 $types[] = $type = [
Chris@0 566 'count' => $j + 1,
Chris@0 567 'type' => $type_name,
Chris@0 568 'severity' => $severity++,
Chris@0 569 ];
Chris@0 570 $this->generateLogEntries($type['count'], [
Chris@0 571 'channel' => $type['type'],
Chris@0 572 'severity' => $type['severity'],
Chris@0 573 ]);
Chris@0 574 }
Chris@0 575 }
Chris@0 576
Chris@0 577 // View the database log page.
Chris@0 578 $this->drupalGet('admin/reports/dblog');
Chris@0 579
Chris@0 580 // Confirm that all the entries are displayed.
Chris@0 581 $count = $this->getTypeCount($types);
Chris@0 582 foreach ($types as $key => $type) {
Chris@0 583 $this->assertEqual($count[$key], $type['count'], 'Count matched');
Chris@0 584 }
Chris@0 585
Chris@0 586 // Filter by each type and confirm that entries with various severities are
Chris@0 587 // displayed.
Chris@0 588 foreach ($type_names as $type_name) {
Chris@0 589 $this->filterLogsEntries($type_name);
Chris@0 590
Chris@0 591 // Count the number of entries of this type.
Chris@0 592 $type_count = 0;
Chris@0 593 foreach ($types as $type) {
Chris@0 594 if ($type['type'] == $type_name) {
Chris@0 595 $type_count += $type['count'];
Chris@0 596 }
Chris@0 597 }
Chris@0 598
Chris@0 599 $count = $this->getTypeCount($types);
Chris@0 600 $this->assertEqual(array_sum($count), $type_count, 'Count matched');
Chris@0 601 }
Chris@0 602
Chris@0 603 // Set the filter to match each of the two filter-type attributes and
Chris@0 604 // confirm the correct number of entries are displayed.
Chris@0 605 foreach ($types as $type) {
Chris@0 606 $this->filterLogsEntries($type['type'], $type['severity']);
Chris@0 607
Chris@0 608 $count = $this->getTypeCount($types);
Chris@0 609 $this->assertEqual(array_sum($count), $type['count'], 'Count matched');
Chris@0 610 }
Chris@0 611
Chris@0 612 $this->drupalGet('admin/reports/dblog', ['query' => ['order' => 'Type']]);
Chris@0 613 $this->assertResponse(200);
Chris@0 614 $this->assertText(t('Operations'), 'Operations text found');
Chris@0 615
Chris@0 616 // Clear all logs and make sure the confirmation message is found.
Chris@0 617 $this->clearLogsEntries();
Chris@0 618 // Confirm that the logs should be cleared.
Chris@0 619 $this->drupalPostForm(NULL, [], 'Confirm');
Chris@0 620 $this->assertText(t('Database log cleared.'), 'Confirmation message found');
Chris@0 621 }
Chris@0 622
Chris@0 623 /**
Chris@0 624 * Gets the database log event information from the browser page.
Chris@0 625 *
Chris@0 626 * @return array
Chris@0 627 * List of log events where each event is an array with following keys:
Chris@0 628 * - severity: (int) A database log severity constant.
Chris@0 629 * - type: (string) The type of database log event.
Chris@0 630 * - message: (string) The message for this database log event.
Chris@0 631 * - user: (string) The user associated with this database log event.
Chris@0 632 */
Chris@0 633 protected function getLogEntries() {
Chris@0 634 $entries = [];
Chris@0 635 if ($table = $this->getLogsEntriesTable()) {
Chris@0 636 foreach ($table as $row) {
Chris@0 637 $cells = $row->findAll('css', 'td');
Chris@0 638 $entries[] = [
Chris@0 639 'severity' => $this->getSeverityConstant($row->getAttribute('class')),
Chris@0 640 'type' => $cells[1]->getText(),
Chris@0 641 'message' => $cells[3]->getText(),
Chris@0 642 'user' => $cells[4]->getText(),
Chris@0 643 ];
Chris@0 644 }
Chris@0 645 }
Chris@0 646 return $entries;
Chris@0 647 }
Chris@0 648
Chris@0 649 /**
Chris@0 650 * Find the Logs table in the DOM.
Chris@0 651 *
Chris@0 652 * @return \SimpleXMLElement[]
Chris@0 653 * The return value of a xpath search.
Chris@0 654 */
Chris@0 655 protected function getLogsEntriesTable() {
Chris@0 656 return $this->xpath('.//table[@id="admin-dblog"]/tbody/tr');
Chris@0 657 }
Chris@0 658
Chris@0 659 /**
Chris@0 660 * Gets the count of database log entries by database log event type.
Chris@0 661 *
Chris@0 662 * @param array $types
Chris@0 663 * The type information to compare against.
Chris@0 664 *
Chris@0 665 * @return array
Chris@0 666 * The count of each type keyed by the key of the $types array.
Chris@0 667 */
Chris@0 668 protected function getTypeCount(array $types) {
Chris@0 669 $entries = $this->getLogEntries();
Chris@0 670 $count = array_fill(0, count($types), 0);
Chris@0 671 foreach ($entries as $entry) {
Chris@0 672 foreach ($types as $key => $type) {
Chris@0 673 if ($entry['type'] == $type['type'] && $entry['severity'] == $type['severity']) {
Chris@0 674 $count[$key]++;
Chris@0 675 break;
Chris@0 676 }
Chris@0 677 }
Chris@0 678 }
Chris@0 679 return $count;
Chris@0 680 }
Chris@0 681
Chris@0 682 /**
Chris@0 683 * Gets the watchdog severity constant corresponding to the CSS class.
Chris@0 684 *
Chris@0 685 * @param string $class
Chris@0 686 * CSS class attribute.
Chris@0 687 *
Chris@0 688 * @return int|null
Chris@0 689 * The watchdog severity constant or NULL if not found.
Chris@0 690 */
Chris@0 691 protected function getSeverityConstant($class) {
Chris@0 692 $map = array_flip(DbLogController::getLogLevelClassMap());
Chris@0 693
Chris@0 694 // Find the class that contains the severity.
Chris@0 695 $classes = explode(' ', $class);
Chris@0 696 foreach ($classes as $class) {
Chris@0 697 if (isset($map[$class])) {
Chris@0 698 return $map[$class];
Chris@0 699 }
Chris@0 700 }
Chris@0 701 return NULL;
Chris@0 702 }
Chris@0 703
Chris@0 704 /**
Chris@0 705 * Confirms that a log message appears on the database log overview screen.
Chris@0 706 *
Chris@0 707 * This function should only be used for the admin/reports/dblog page, because
Chris@0 708 * it checks for the message link text truncated to 56 characters. Other log
Chris@0 709 * pages have no detail links so they contain the full message text.
Chris@0 710 *
Chris@0 711 * @param string $log_message
Chris@0 712 * The database log message to check.
Chris@0 713 * @param string $message
Chris@0 714 * The message to pass to simpletest.
Chris@0 715 */
Chris@0 716 protected function assertLogMessage($log_message, $message) {
Chris@0 717 $message_text = Unicode::truncate(Html::decodeEntities(strip_tags($log_message)), 56, TRUE, TRUE);
Chris@0 718 $this->assertLink($message_text, 0, $message);
Chris@0 719 }
Chris@0 720
Chris@0 721 /**
Chris@0 722 * Tests that the details page displays correctly for a temporary user.
Chris@0 723 */
Chris@0 724 public function testTemporaryUser() {
Chris@0 725 // Create a temporary user.
Chris@0 726 $tempuser = $this->drupalCreateUser();
Chris@0 727 $tempuser_uid = $tempuser->id();
Chris@0 728
Chris@0 729 // Log in as the admin user.
Chris@0 730 $this->drupalLogin($this->adminUser);
Chris@0 731
Chris@0 732 // Generate a single watchdog entry.
Chris@0 733 $this->generateLogEntries(1, ['user' => $tempuser, 'uid' => $tempuser_uid]);
Chris@0 734 $wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
Chris@0 735
Chris@0 736 // Check if the full message displays on the details page.
Chris@0 737 $this->drupalGet('admin/reports/dblog/event/' . $wid);
Chris@0 738 $this->assertText('Dblog test log message');
Chris@0 739
Chris@0 740 // Delete the user.
Chris@0 741 user_delete($tempuser->id());
Chris@0 742 $this->drupalGet('user/' . $tempuser_uid);
Chris@0 743 $this->assertResponse(404);
Chris@0 744
Chris@0 745 // Check if the full message displays on the details page.
Chris@0 746 $this->drupalGet('admin/reports/dblog/event/' . $wid);
Chris@0 747 $this->assertText('Dblog test log message');
Chris@0 748 }
Chris@0 749
Chris@0 750 /**
Chris@0 751 * Make sure HTML tags are filtered out in the log overview links.
Chris@0 752 */
Chris@0 753 public function testOverviewLinks() {
Chris@0 754 $this->drupalLogin($this->adminUser);
Chris@0 755 $this->generateLogEntries(1, ['message' => "&lt;script&gt;alert('foo');&lt;/script&gt;<strong>Lorem</strong> ipsum dolor sit amet, consectetur adipiscing & elit."]);
Chris@0 756 $this->drupalGet('admin/reports/dblog');
Chris@0 757 $this->assertResponse(200);
Chris@0 758 // Make sure HTML tags are filtered out.
Chris@0 759 $this->assertRaw('title="alert(&#039;foo&#039;);Lorem');
Chris@0 760 $this->assertNoRaw("<script>alert('foo');</script>");
Chris@0 761
Chris@0 762 // Make sure HTML tags are filtered out in admin/reports/dblog/event/ too.
Chris@0 763 $this->generateLogEntries(1, ['message' => "<script>alert('foo');</script> <strong>Lorem ipsum</strong>"]);
Chris@0 764 $wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
Chris@0 765 $this->drupalGet('admin/reports/dblog/event/' . $wid);
Chris@0 766 $this->assertNoRaw("<script>alert('foo');</script>");
Chris@0 767 $this->assertRaw("alert('foo'); <strong>Lorem ipsum</strong>");
Chris@0 768 }
Chris@0 769
Chris@0 770 /**
Chris@0 771 * Test sorting for entries with the same timestamp.
Chris@0 772 */
Chris@0 773 public function testSameTimestampEntries() {
Chris@0 774 $this->drupalLogin($this->adminUser);
Chris@0 775
Chris@0 776 $this->generateLogEntries(1, ['timestamp' => 1498062000, 'type' => 'same_time', 'message' => 'First']);
Chris@0 777 $this->generateLogEntries(1, ['timestamp' => 1498062000, 'type' => 'same_time', 'message' => 'Second']);
Chris@0 778 $this->generateLogEntries(1, ['timestamp' => 1498062000, 'type' => 'same_time', 'message' => 'Third']);
Chris@0 779
Chris@0 780 $this->drupalGet('admin/reports/dblog');
Chris@0 781
Chris@0 782 $entries = $this->getLogEntries();
Chris@0 783 $this->assertEquals($entries[0]['message'], 'Third Entry #0');
Chris@0 784 $this->assertEquals($entries[1]['message'], 'Second Entry #0');
Chris@0 785 $this->assertEquals($entries[2]['message'], 'First Entry #0');
Chris@0 786 }
Chris@0 787
Chris@0 788 }