/[drupal]/drupal/modules/dblog/dblog.test
ViewVC logotype

Contents of /drupal/modules/dblog/dblog.test

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


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

  ViewVC Help
Powered by ViewVC 1.1.2