dblog.test

Tests for dblog.module.

File

drupal-7.x/modules/dblog/dblog.test
View source
  1. <?php
  2. /**
  3. * @file
  4. * Tests for dblog.module.
  5. */
  6. /**
  7. * Tests logging messages to the database.
  8. */
  9. class DBLogTestCase extends DrupalWebTestCase {
  10. /**
  11. * A user with some relevant administrative permissions.
  12. *
  13. * @var object
  14. */
  15. protected $big_user;
  16. /**
  17. * A user without any permissions.
  18. *
  19. * @var object
  20. */
  21. protected $any_user;
  22. public static function getInfo() {
  23. return array(
  24. 'name' => 'DBLog functionality',
  25. 'description' => 'Generate events and verify dblog entries; verify user access to log reports based on persmissions.',
  26. 'group' => 'DBLog',
  27. );
  28. }
  29. /**
  30. * Enable modules and create users with specific permissions.
  31. */
  32. function setUp() {
  33. parent::setUp('dblog', 'blog', 'poll');
  34. // Create users.
  35. $this->big_user = $this->drupalCreateUser(array('administer site configuration', 'access administration pages', 'access site reports', 'administer users'));
  36. $this->any_user = $this->drupalCreateUser(array());
  37. }
  38. /**
  39. * Tests Database Logging module functionality through interfaces.
  40. *
  41. * First logs in users, then creates database log events, and finally tests
  42. * Database Logging module functionality through both the admin and user
  43. * interfaces.
  44. */
  45. function testDBLog() {
  46. // Login the admin user.
  47. $this->drupalLogin($this->big_user);
  48. $row_limit = 100;
  49. $this->verifyRowLimit($row_limit);
  50. $this->verifyCron($row_limit);
  51. $this->verifyEvents();
  52. $this->verifyReports();
  53. // Login the regular user.
  54. $this->drupalLogin($this->any_user);
  55. $this->verifyReports(403);
  56. }
  57. /**
  58. * Verifies setting of the database log row limit.
  59. *
  60. * @param int $row_limit
  61. * The row limit.
  62. */
  63. private function verifyRowLimit($row_limit) {
  64. // Change the database log row limit.
  65. $edit = array();
  66. $edit['dblog_row_limit'] = $row_limit;
  67. $this->drupalPost('admin/config/development/logging', $edit, t('Save configuration'));
  68. $this->assertResponse(200);
  69. // Check row limit variable.
  70. $current_limit = variable_get('dblog_row_limit', 1000);
  71. $this->assertTrue($current_limit == $row_limit, format_string('[Cache] Row limit variable of @count equals row limit of @limit', array('@count' => $current_limit, '@limit' => $row_limit)));
  72. // Verify dblog row limit equals specified row limit.
  73. $current_limit = unserialize(db_query("SELECT value FROM {variable} WHERE name = :dblog_limit", array(':dblog_limit' => 'dblog_row_limit'))->fetchField());
  74. $this->assertTrue($current_limit == $row_limit, format_string('[Variable table] Row limit variable of @count equals row limit of @limit', array('@count' => $current_limit, '@limit' => $row_limit)));
  75. }
  76. /**
  77. * Verifies that cron correctly applies the database log row limit.
  78. *
  79. * @param int $row_limit
  80. * The row limit.
  81. */
  82. private function verifyCron($row_limit) {
  83. // Generate additional log entries.
  84. $this->generateLogEntries($row_limit + 10);
  85. // Verify that the database log row count exceeds the row limit.
  86. $count = db_query('SELECT COUNT(wid) FROM {watchdog}')->fetchField();
  87. $this->assertTrue($count > $row_limit, format_string('Dblog row count of @count exceeds row limit of @limit', array('@count' => $count, '@limit' => $row_limit)));
  88. // Run a cron job.
  89. $this->cronRun();
  90. // Verify that the database log row count equals the row limit plus one
  91. // because cron adds a record after it runs.
  92. $count = db_query('SELECT COUNT(wid) FROM {watchdog}')->fetchField();
  93. $this->assertTrue($count == $row_limit + 1, format_string('Dblog row count of @count equals row limit of @limit plus one', array('@count' => $count, '@limit' => $row_limit)));
  94. }
  95. /**
  96. * Generates a number of random database log events.
  97. *
  98. * @param int $count
  99. * Number of watchdog entries to generate.
  100. * @param string $type
  101. * (optional) The type of watchdog entry. Defaults to 'custom'.
  102. * @param int $severity
  103. * (optional) The severity of the watchdog entry. Defaults to WATCHDOG_NOTICE.
  104. */
  105. private function generateLogEntries($count, $type = 'custom', $severity = WATCHDOG_NOTICE) {
  106. global $base_root;
  107. // Prepare the fields to be logged
  108. $log = array(
  109. 'type' => $type,
  110. 'message' => 'Log entry added to test the dblog row limit.',
  111. 'variables' => array(),
  112. 'severity' => $severity,
  113. 'link' => NULL,
  114. 'user' => $this->big_user,
  115. 'uid' => isset($this->big_user->uid) ? $this->big_user->uid : 0,
  116. 'request_uri' => $base_root . request_uri(),
  117. 'referer' => $_SERVER['HTTP_REFERER'],
  118. 'ip' => ip_address(),
  119. 'timestamp' => REQUEST_TIME,
  120. );
  121. $message = 'Log entry added to test the dblog row limit. Entry #';
  122. for ($i = 0; $i < $count; $i++) {
  123. $log['message'] = $message . $i;
  124. dblog_watchdog($log);
  125. }
  126. }
  127. /**
  128. * Confirms that database log reports are displayed at the correct paths.
  129. *
  130. * @param int $response
  131. * (optional) HTTP response code. Defaults to 200.
  132. */
  133. private function verifyReports($response = 200) {
  134. $quote = '&#039;';
  135. // View the database log help page.
  136. $this->drupalGet('admin/help/dblog');
  137. $this->assertResponse($response);
  138. if ($response == 200) {
  139. $this->assertText(t('Database logging'), 'DBLog help was displayed');
  140. }
  141. // View the database log report page.
  142. $this->drupalGet('admin/reports/dblog');
  143. $this->assertResponse($response);
  144. if ($response == 200) {
  145. $this->assertText(t('Recent log messages'), 'DBLog report was displayed');
  146. }
  147. // View the database log page-not-found report page.
  148. $this->drupalGet('admin/reports/page-not-found');
  149. $this->assertResponse($response);
  150. if ($response == 200) {
  151. $this->assertText(t('Top ' . $quote . 'page not found' . $quote . ' errors'), 'DBLog page-not-found report was displayed');
  152. }
  153. // View the database log access-denied report page.
  154. $this->drupalGet('admin/reports/access-denied');
  155. $this->assertResponse($response);
  156. if ($response == 200) {
  157. $this->assertText(t('Top ' . $quote . 'access denied' . $quote . ' errors'), 'DBLog access-denied report was displayed');
  158. }
  159. // View the database log event page.
  160. $this->drupalGet('admin/reports/event/1');
  161. $this->assertResponse($response);
  162. if ($response == 200) {
  163. $this->assertText(t('Details'), 'DBLog event node was displayed');
  164. }
  165. }
  166. /**
  167. * Generates and then verifies various types of events.
  168. */
  169. private function verifyEvents() {
  170. // Invoke events.
  171. $this->doUser();
  172. $this->doNode('article');
  173. $this->doNode('blog');
  174. $this->doNode('page');
  175. $this->doNode('poll');
  176. // When a user account is canceled, any content they created remains but the
  177. // uid = 0. Their blog entry shows as "'s blog" on the home page. Records
  178. // in the watchdog table related to that user have the uid set to zero.
  179. }
  180. /**
  181. * Generates and then verifies some user events.
  182. */
  183. private function doUser() {
  184. // Set user variables.
  185. $name = $this->randomName();
  186. $pass = user_password();
  187. // Add a user using the form to generate an add user event (which is not
  188. // triggered by drupalCreateUser).
  189. $edit = array();
  190. $edit['name'] = $name;
  191. $edit['mail'] = $name . '@example.com';
  192. $edit['pass[pass1]'] = $pass;
  193. $edit['pass[pass2]'] = $pass;
  194. $edit['status'] = 1;
  195. $this->drupalPost('admin/people/create', $edit, t('Create new account'));
  196. $this->assertResponse(200);
  197. // Retrieve the user object.
  198. $user = user_load_by_name($name);
  199. $this->assertTrue($user != NULL, format_string('User @name was loaded', array('@name' => $name)));
  200. // pass_raw property is needed by drupalLogin.
  201. $user->pass_raw = $pass;
  202. // Login user.
  203. $this->drupalLogin($user);
  204. // Logout user.
  205. $this->drupalLogout();
  206. // Fetch the row IDs in watchdog that relate to the user.
  207. $result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', array(':uid' => $user->uid));
  208. foreach ($result as $row) {
  209. $ids[] = $row->wid;
  210. }
  211. $count_before = (isset($ids)) ? count($ids) : 0;
  212. $this->assertTrue($count_before > 0, format_string('DBLog contains @count records for @name', array('@count' => $count_before, '@name' => $user->name)));
  213. // Login the admin user.
  214. $this->drupalLogin($this->big_user);
  215. // Delete the user created at the start of this test.
  216. // We need to POST here to invoke batch_process() in the internal browser.
  217. $this->drupalPost('user/' . $user->uid . '/cancel', array('user_cancel_method' => 'user_cancel_reassign'), t('Cancel account'));
  218. // View the database log report.
  219. $this->drupalGet('admin/reports/dblog');
  220. $this->assertResponse(200);
  221. // Verify that the expected events were recorded.
  222. // Add user.
  223. // Default display includes name and email address; if too long, the email
  224. // address is replaced by three periods.
  225. $this->assertLogMessage(t('New user: %name (%email).', array('%name' => $name, '%email' => $user->mail)), 'DBLog event was recorded: [add user]');
  226. // Login user.
  227. $this->assertLogMessage(t('Session opened for %name.', array('%name' => $name)), 'DBLog event was recorded: [login user]');
  228. // Logout user.
  229. $this->assertLogMessage(t('Session closed for %name.', array('%name' => $name)), 'DBLog event was recorded: [logout user]');
  230. // Delete user.
  231. $message = t('Deleted user: %name %email.', array('%name' => $name, '%email' => '<' . $user->mail . '>'));
  232. $message_text = truncate_utf8(filter_xss($message, array()), 56, TRUE, TRUE);
  233. // Verify that the full message displays on the details page.
  234. $link = FALSE;
  235. if ($links = $this->xpath('//a[text()="' . html_entity_decode($message_text) . '"]')) {
  236. // Found link with the message text.
  237. $links = array_shift($links);
  238. foreach ($links->attributes() as $attr => $value) {
  239. if ($attr == 'href') {
  240. // Extract link to details page.
  241. $link = drupal_substr($value, strpos($value, 'admin/reports/event/'));
  242. $this->drupalGet($link);
  243. // Check for full message text on the details page.
  244. $this->assertRaw($message, 'DBLog event details was found: [delete user]');
  245. break;
  246. }
  247. }
  248. }
  249. $this->assertTrue($link, 'DBLog event was recorded: [delete user]');
  250. // Visit random URL (to generate page not found event).
  251. $not_found_url = $this->randomName(60);
  252. $this->drupalGet($not_found_url);
  253. $this->assertResponse(404);
  254. // View the database log page-not-found report page.
  255. $this->drupalGet('admin/reports/page-not-found');
  256. $this->assertResponse(200);
  257. // Check that full-length URL displayed.
  258. $this->assertText($not_found_url, 'DBLog event was recorded: [page not found]');
  259. }
  260. /**
  261. * Generates and then verifies some node events.
  262. *
  263. * @param string $type
  264. * A node type (e.g., 'article', 'page' or 'poll').
  265. */
  266. private function doNode($type) {
  267. // Create user.
  268. $perm = array('create ' . $type . ' content', 'edit own ' . $type . ' content', 'delete own ' . $type . ' content');
  269. $user = $this->drupalCreateUser($perm);
  270. // Login user.
  271. $this->drupalLogin($user);
  272. // Create a node using the form in order to generate an add content event
  273. // (which is not triggered by drupalCreateNode).
  274. $edit = $this->getContent($type);
  275. $langcode = LANGUAGE_NONE;
  276. $title = $edit["title"];
  277. $this->drupalPost('node/add/' . $type, $edit, t('Save'));
  278. $this->assertResponse(200);
  279. // Retrieve the node object.
  280. $node = $this->drupalGetNodeByTitle($title);
  281. $this->assertTrue($node != NULL, format_string('Node @title was loaded', array('@title' => $title)));
  282. // Edit the node.
  283. $edit = $this->getContentUpdate($type);
  284. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  285. $this->assertResponse(200);
  286. // Delete the node.
  287. $this->drupalPost('node/' . $node->nid . '/delete', array(), t('Delete'));
  288. $this->assertResponse(200);
  289. // View the node (to generate page not found event).
  290. $this->drupalGet('node/' . $node->nid);
  291. $this->assertResponse(404);
  292. // View the database log report (to generate access denied event).
  293. $this->drupalGet('admin/reports/dblog');
  294. $this->assertResponse(403);
  295. // Login the admin user.
  296. $this->drupalLogin($this->big_user);
  297. // View the database log report.
  298. $this->drupalGet('admin/reports/dblog');
  299. $this->assertResponse(200);
  300. // Verify that node events were recorded.
  301. // Was node content added?
  302. $this->assertLogMessage(t('@type: added %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content added]');
  303. // Was node content updated?
  304. $this->assertLogMessage(t('@type: updated %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content updated]');
  305. // Was node content deleted?
  306. $this->assertLogMessage(t('@type: deleted %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content deleted]');
  307. // View the database log access-denied report page.
  308. $this->drupalGet('admin/reports/access-denied');
  309. $this->assertResponse(200);
  310. // Verify that the 'access denied' event was recorded.
  311. $this->assertText(t('admin/reports/dblog'), 'DBLog event was recorded: [access denied]');
  312. // View the database log page-not-found report page.
  313. $this->drupalGet('admin/reports/page-not-found');
  314. $this->assertResponse(200);
  315. // Verify that the 'page not found' event was recorded.
  316. $this->assertText(t('node/@nid', array('@nid' => $node->nid)), 'DBLog event was recorded: [page not found]');
  317. }
  318. /**
  319. * Creates random content based on node content type.
  320. *
  321. * @param string $type
  322. * Node content type (e.g., 'article').
  323. *
  324. * @return array
  325. * Random content needed by various node types.
  326. */
  327. private function getContent($type) {
  328. $langcode = LANGUAGE_NONE;
  329. switch ($type) {
  330. case 'poll':
  331. $content = array(
  332. "title" => $this->randomName(8),
  333. 'choice[new:0][chtext]' => $this->randomName(32),
  334. 'choice[new:1][chtext]' => $this->randomName(32),
  335. );
  336. break;
  337. default:
  338. $content = array(
  339. "title" => $this->randomName(8),
  340. "body[$langcode][0][value]" => $this->randomName(32),
  341. );
  342. break;
  343. }
  344. return $content;
  345. }
  346. /**
  347. * Creates random content as an update based on node content type.
  348. *
  349. * @param string $type
  350. * Node content type (e.g., 'article').
  351. *
  352. * @return array
  353. * Random content needed by various node types.
  354. */
  355. private function getContentUpdate($type) {
  356. switch ($type) {
  357. case 'poll':
  358. $content = array(
  359. 'choice[chid:1][chtext]' => $this->randomName(32),
  360. 'choice[chid:2][chtext]' => $this->randomName(32),
  361. );
  362. break;
  363. default:
  364. $langcode = LANGUAGE_NONE;
  365. $content = array(
  366. "body[$langcode][0][value]" => $this->randomName(32),
  367. );
  368. break;
  369. }
  370. return $content;
  371. }
  372. /**
  373. * Tests the addition and clearing of log events through the admin interface.
  374. *
  375. * Logs in the admin user, creates a database log event, and tests the
  376. * functionality of clearing the database log through the admin interface.
  377. */
  378. protected function testDBLogAddAndClear() {
  379. global $base_root;
  380. // Get a count of how many watchdog entries already exist.
  381. $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
  382. $log = array(
  383. 'type' => 'custom',
  384. 'message' => 'Log entry added to test the doClearTest clear down.',
  385. 'variables' => array(),
  386. 'severity' => WATCHDOG_NOTICE,
  387. 'link' => NULL,
  388. 'user' => $this->big_user,
  389. 'uid' => isset($this->big_user->uid) ? $this->big_user->uid : 0,
  390. 'request_uri' => $base_root . request_uri(),
  391. 'referer' => $_SERVER['HTTP_REFERER'],
  392. 'ip' => ip_address(),
  393. 'timestamp' => REQUEST_TIME,
  394. );
  395. // Add a watchdog entry.
  396. dblog_watchdog($log);
  397. // Make sure the table count has actually been incremented.
  398. $this->assertEqual($count + 1, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), format_string('dblog_watchdog() added an entry to the dblog :count', array(':count' => $count)));
  399. // Login the admin user.
  400. $this->drupalLogin($this->big_user);
  401. // Post in order to clear the database table.
  402. $this->drupalPost('admin/reports/dblog', array(), t('Clear log messages'));
  403. // Count the rows in watchdog that previously related to the deleted user.
  404. $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
  405. $this->assertEqual($count, 0, format_string('DBLog contains :count records after a clear.', array(':count' => $count)));
  406. }
  407. /**
  408. * Tests the database log filter functionality at admin/reports/dblog.
  409. */
  410. protected function testFilter() {
  411. $this->drupalLogin($this->big_user);
  412. // Clear the log to ensure that only generated entries will be found.
  413. db_delete('watchdog')->execute();
  414. // Generate 9 random watchdog entries.
  415. $type_names = array();
  416. $types = array();
  417. for ($i = 0; $i < 3; $i++) {
  418. $type_names[] = $type_name = $this->randomName();
  419. $severity = WATCHDOG_EMERGENCY;
  420. for ($j = 0; $j < 3; $j++) {
  421. $types[] = $type = array(
  422. 'count' => $j + 1,
  423. 'type' => $type_name,
  424. 'severity' => $severity++,
  425. );
  426. $this->generateLogEntries($type['count'], $type['type'], $type['severity']);
  427. }
  428. }
  429. // View the database log page.
  430. $this->drupalGet('admin/reports/dblog');
  431. // Confirm that all the entries are displayed.
  432. $count = $this->getTypeCount($types);
  433. foreach ($types as $key => $type) {
  434. $this->assertEqual($count[$key], $type['count'], 'Count matched');
  435. }
  436. // Filter by each type and confirm that entries with various severities are
  437. // displayed.
  438. foreach ($type_names as $type_name) {
  439. $edit = array(
  440. 'type[]' => array($type_name),
  441. );
  442. $this->drupalPost(NULL, $edit, t('Filter'));
  443. // Count the number of entries of this type.
  444. $type_count = 0;
  445. foreach ($types as $type) {
  446. if ($type['type'] == $type_name) {
  447. $type_count += $type['count'];
  448. }
  449. }
  450. $count = $this->getTypeCount($types);
  451. $this->assertEqual(array_sum($count), $type_count, 'Count matched');
  452. }
  453. // Set the filter to match each of the two filter-type attributes and
  454. // confirm the correct number of entries are displayed.
  455. foreach ($types as $key => $type) {
  456. $edit = array(
  457. 'type[]' => array($type['type']),
  458. 'severity[]' => array($type['severity']),
  459. );
  460. $this->drupalPost(NULL, $edit, t('Filter'));
  461. $count = $this->getTypeCount($types);
  462. $this->assertEqual(array_sum($count), $type['count'], 'Count matched');
  463. }
  464. // Clear all logs and make sure the confirmation message is found.
  465. $this->drupalPost('admin/reports/dblog', array(), t('Clear log messages'));
  466. $this->assertText(t('Database log cleared.'), 'Confirmation message found');
  467. }
  468. /**
  469. * Gets the database log event information from the browser page.
  470. *
  471. * @return array
  472. * List of log events where each event is an array with following keys:
  473. * - severity: (int) A database log severity constant.
  474. * - type: (string) The type of database log event.
  475. * - message: (string) The message for this database log event.
  476. * - user: (string) The user associated with this database log event.
  477. */
  478. protected function getLogEntries() {
  479. $entries = array();
  480. if ($table = $this->xpath('.//table[@id="admin-dblog"]')) {
  481. $table = array_shift($table);
  482. foreach ($table->tbody->tr as $row) {
  483. $entries[] = array(
  484. 'severity' => $this->getSeverityConstant($row['class']),
  485. 'type' => $this->asText($row->td[1]),
  486. 'message' => $this->asText($row->td[3]),
  487. 'user' => $this->asText($row->td[4]),
  488. );
  489. }
  490. }
  491. return $entries;
  492. }
  493. /**
  494. * Gets the count of database log entries by database log event type.
  495. *
  496. * @param array $types
  497. * The type information to compare against.
  498. *
  499. * @return array
  500. * The count of each type keyed by the key of the $types array.
  501. */
  502. protected function getTypeCount(array $types) {
  503. $entries = $this->getLogEntries();
  504. $count = array_fill(0, count($types), 0);
  505. foreach ($entries as $entry) {
  506. foreach ($types as $key => $type) {
  507. if ($entry['type'] == $type['type'] && $entry['severity'] == $type['severity']) {
  508. $count[$key]++;
  509. break;
  510. }
  511. }
  512. }
  513. return $count;
  514. }
  515. /**
  516. * Gets the watchdog severity constant corresponding to the CSS class.
  517. *
  518. * @param string $class
  519. * CSS class attribute.
  520. *
  521. * @return int|null
  522. * The watchdog severity constant or NULL if not found.
  523. *
  524. * @ingroup logging_severity_levels
  525. */
  526. protected function getSeverityConstant($class) {
  527. // Reversed array from dblog_overview().
  528. $map = array(
  529. 'dblog-debug' => WATCHDOG_DEBUG,
  530. 'dblog-info' => WATCHDOG_INFO,
  531. 'dblog-notice' => WATCHDOG_NOTICE,
  532. 'dblog-warning' => WATCHDOG_WARNING,
  533. 'dblog-error' => WATCHDOG_ERROR,
  534. 'dblog-critical' => WATCHDOG_CRITICAL,
  535. 'dblog-alert' => WATCHDOG_ALERT,
  536. 'dblog-emerg' => WATCHDOG_EMERGENCY,
  537. );
  538. // Find the class that contains the severity.
  539. $classes = explode(' ', $class);
  540. foreach ($classes as $class) {
  541. if (isset($map[$class])) {
  542. return $map[$class];
  543. }
  544. }
  545. return NULL;
  546. }
  547. /**
  548. * Extracts the text contained by the XHTML element.
  549. *
  550. * @param SimpleXMLElement $element
  551. * Element to extract text from.
  552. *
  553. * @return string
  554. * Extracted text.
  555. */
  556. protected function asText(SimpleXMLElement $element) {
  557. if (!is_object($element)) {
  558. return $this->fail('The element is not an element.');
  559. }
  560. return trim(html_entity_decode(strip_tags($element->asXML())));
  561. }
  562. /**
  563. * Confirms that a log message appears on the database log overview screen.
  564. *
  565. * This function should only be used for the admin/reports/dblog page, because
  566. * it checks for the message link text truncated to 56 characters. Other log
  567. * pages have no detail links so they contain the full message text.
  568. *
  569. * @param string $log_message
  570. * The database log message to check.
  571. * @param string $message
  572. * The message to pass to simpletest.
  573. */
  574. protected function assertLogMessage($log_message, $message) {
  575. $message_text = truncate_utf8(filter_xss($log_message, array()), 56, TRUE, TRUE);
  576. // After filter_xss(), HTML entities should be converted to their character
  577. // equivalents because assertLink() uses this string in xpath() to query the
  578. // Document Object Model (DOM).
  579. $this->assertLink(html_entity_decode($message_text), 0, $message);
  580. }
  581. }