annotate core/modules/dblog/tests/src/Functional/DbLogTest.php @ 0:c75dbcec494b

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