statistics.test

  1. drupal
    1. 7 modules/statistics/statistics.test
    2. 8 core/modules/statistics/statistics.test

Tests for statistics.module.

Classes

NameDescription
StatisticsAdminTestCaseTest statistics administration screen.
StatisticsBlockVisitorsTestCaseTests that the visitor blocking functionality works.
StatisticsLoggingTestCaseTests that logging via statistics_exit() works for cached and uncached pages.
StatisticsReportsTestCaseTests that report pages render properly, and that access logging works.
StatisticsTestCaseSets up a base class for the Statistics module.
StatisticsTokenReplaceTestCaseTest statistics token replacement in strings.

File

modules/statistics/statistics.test
View source
  1. <?php
  2. /**
  3. * @file
  4. * Tests for statistics.module.
  5. */
  6. /**
  7. * Sets up a base class for the Statistics module.
  8. */
  9. class StatisticsTestCase extends DrupalWebTestCase {
  10. function setUp() {
  11. parent::setUp('statistics');
  12. // Create user.
  13. $this->blocking_user = $this->drupalCreateUser(array(
  14. 'access administration pages',
  15. 'access site reports',
  16. 'access statistics',
  17. 'block IP addresses',
  18. 'administer blocks',
  19. 'administer statistics',
  20. 'administer users',
  21. ));
  22. $this->drupalLogin($this->blocking_user);
  23. // Enable access logging.
  24. variable_set('statistics_enable_access_log', 1);
  25. variable_set('statistics_count_content_views', 1);
  26. // Insert dummy access by anonymous user into access log.
  27. db_insert('accesslog')
  28. ->fields(array(
  29. 'title' => 'test',
  30. 'path' => 'node/1',
  31. 'url' => 'http://example.com',
  32. 'hostname' => '192.168.1.1',
  33. 'uid' => 0,
  34. 'sid' => 10,
  35. 'timer' => 10,
  36. 'timestamp' => REQUEST_TIME,
  37. ))
  38. ->execute();
  39. }
  40. }
  41. /**
  42. * Tests that logging via statistics_exit() works for cached and uncached pages.
  43. *
  44. * Subclass DrupalWebTestCase rather than StatisticsTestCase, because we want
  45. * to test requests from an anonymous user.
  46. */
  47. class StatisticsLoggingTestCase extends DrupalWebTestCase {
  48. public static function getInfo() {
  49. return array(
  50. 'name' => 'Statistics logging tests',
  51. 'description' => 'Tests request logging for cached and uncached pages.',
  52. 'group' => 'Statistics'
  53. );
  54. }
  55. function setUp() {
  56. parent::setUp('statistics');
  57. $this->auth_user = $this->drupalCreateUser(array('access content', 'create page content', 'edit own page content'));
  58. // Ensure we have a node page to access.
  59. $this->node = $this->drupalCreateNode(array('title' => $this->randomName(255), 'uid' => $this->auth_user->uid));
  60. // Enable page caching.
  61. variable_set('cache', TRUE);
  62. // Enable access logging.
  63. variable_set('statistics_enable_access_log', 1);
  64. variable_set('statistics_count_content_views', 1);
  65. // Clear the logs.
  66. db_truncate('accesslog');
  67. db_truncate('node_counter');
  68. }
  69. /**
  70. * Verifies request logging for cached and uncached pages.
  71. */
  72. function testLogging() {
  73. $path = 'node/' . $this->node->nid;
  74. $expected = array(
  75. 'title' => $this->node->title,
  76. 'path' => $path,
  77. );
  78. // Verify logging of an uncached page.
  79. $this->drupalGet($path);
  80. $this->assertIdentical($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', t('Testing an uncached page.'));
  81. $log = db_query('SELECT * FROM {accesslog}')->fetchAll(PDO::FETCH_ASSOC);
  82. $this->assertTrue(is_array($log) && count($log) == 1, t('Page request was logged.'));
  83. $this->assertEqual(array_intersect_key($log[0], $expected), $expected);
  84. $node_counter = statistics_get($this->node->nid);
  85. $this->assertIdentical($node_counter['totalcount'], '1');
  86. // Verify logging of a cached page.
  87. $this->drupalGet($path);
  88. $this->assertIdentical($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', t('Testing a cached page.'));
  89. $log = db_query('SELECT * FROM {accesslog}')->fetchAll(PDO::FETCH_ASSOC);
  90. $this->assertTrue(is_array($log) && count($log) == 2, t('Page request was logged.'));
  91. $this->assertEqual(array_intersect_key($log[1], $expected), $expected);
  92. $node_counter = statistics_get($this->node->nid);
  93. $this->assertIdentical($node_counter['totalcount'], '2');
  94. // Test logging from authenticated users
  95. $this->drupalLogin($this->auth_user);
  96. $this->drupalGet($path);
  97. $log = db_query('SELECT * FROM {accesslog}')->fetchAll(PDO::FETCH_ASSOC);
  98. // Check the 6th item since login and account pages are also logged
  99. $this->assertTrue(is_array($log) && count($log) == 6, t('Page request was logged.'));
  100. $this->assertEqual(array_intersect_key($log[5], $expected), $expected);
  101. $node_counter = statistics_get($this->node->nid);
  102. $this->assertIdentical($node_counter['totalcount'], '3');
  103. // Visit edit page to generate a title greater than 255.
  104. $path = 'node/' . $this->node->nid . '/edit';
  105. $expected = array(
  106. 'title' => truncate_utf8(t('Edit Basic page') . ' ' . $this->node->title, 255),
  107. 'path' => $path,
  108. );
  109. $this->drupalGet($path);
  110. $log = db_query('SELECT * FROM {accesslog}')->fetchAll(PDO::FETCH_ASSOC);
  111. $this->assertTrue(is_array($log) && count($log) == 7, t('Page request was logged.'));
  112. $this->assertEqual(array_intersect_key($log[6], $expected), $expected);
  113. // Create a path longer than 255 characters.
  114. $long_path = $this->randomName(256);
  115. // Test that the long path is properly truncated when logged.
  116. $this->drupalGet($long_path);
  117. $log = db_query('SELECT * FROM {accesslog}')->fetchAll(PDO::FETCH_ASSOC);
  118. $this->assertTrue(is_array($log) && count($log) == 8, 'Page request was logged for a path over 255 characters.');
  119. $this->assertEqual($log[7]['path'], truncate_utf8($long_path, 255));
  120. }
  121. }
  122. /**
  123. * Tests that report pages render properly, and that access logging works.
  124. */
  125. class StatisticsReportsTestCase extends StatisticsTestCase {
  126. public static function getInfo() {
  127. return array(
  128. 'name' => 'Statistics reports tests',
  129. 'description' => 'Tests display of statistics report pages and access logging.',
  130. 'group' => 'Statistics'
  131. );
  132. }
  133. /**
  134. * Verifies that 'Recent hits' renders properly and displays the added hit.
  135. */
  136. function testRecentHits() {
  137. $this->drupalGet('admin/reports/hits');
  138. $this->assertText('test', t('Hit title found.'));
  139. $this->assertText('node/1', t('Hit URL found.'));
  140. $this->assertText('Anonymous', t('Hit user found.'));
  141. }
  142. /**
  143. * Verifies that 'Top pages' renders properly and displays the added hit.
  144. */
  145. function testTopPages() {
  146. $this->drupalGet('admin/reports/pages');
  147. $this->assertText('test', t('Hit title found.'));
  148. $this->assertText('node/1', t('Hit URL found.'));
  149. }
  150. /**
  151. * Verifies that 'Top referrers' renders properly and displays the added hit.
  152. */
  153. function testTopReferrers() {
  154. $this->drupalGet('admin/reports/referrers');
  155. $this->assertText('http://example.com', t('Hit referrer found.'));
  156. }
  157. /**
  158. * Verifies that 'Details' page renders properly and displays the added hit.
  159. */
  160. function testDetails() {
  161. $this->drupalGet('admin/reports/access/1');
  162. $this->assertText('test', t('Hit title found.'));
  163. $this->assertText('node/1', t('Hit URL found.'));
  164. $this->assertText('Anonymous', t('Hit user found.'));
  165. }
  166. /**
  167. * Verifies that access logging is working and is reported correctly.
  168. */
  169. function testAccessLogging() {
  170. $this->drupalGet('admin/reports/referrers');
  171. $this->drupalGet('admin/reports/hits');
  172. $this->assertText('Top referrers in the past 3 days', t('Hit title found.'));
  173. $this->assertText('admin/reports/referrers', t('Hit URL found.'));
  174. }
  175. /**
  176. * Tests the "popular content" block.
  177. */
  178. function testPopularContentBlock() {
  179. // Visit a node to have something show up in the block.
  180. $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->blocking_user->uid));
  181. $this->drupalGet('node/' . $node->nid);
  182. // Configure and save the block.
  183. $block = block_load('statistics', 'popular');
  184. $block->theme = variable_get('theme_default', 'bartik');
  185. $block->status = 1;
  186. $block->pages = '';
  187. $block->region = 'sidebar_first';
  188. $block->cache = -1;
  189. $block->visibility = 0;
  190. $edit = array('statistics_block_top_day_num' => 3, 'statistics_block_top_all_num' => 3, 'statistics_block_top_last_num' => 3);
  191. module_invoke('statistics', 'block_save', 'popular', $edit);
  192. drupal_write_record('block', $block);
  193. // Get some page and check if the block is displayed.
  194. $this->drupalGet('user');
  195. $this->assertText('Popular content', t('Found the popular content block.'));
  196. $this->assertText("Today's", t('Found today\'s popular content.'));
  197. $this->assertText('All time', t('Found the alll time popular content.'));
  198. $this->assertText('Last viewed', t('Found the last viewed popular content.'));
  199. $this->assertRaw(l($node->title, 'node/' . $node->nid), t('Found link to visited node.'));
  200. }
  201. }
  202. /**
  203. * Tests that the visitor blocking functionality works.
  204. */
  205. class StatisticsBlockVisitorsTestCase extends StatisticsTestCase {
  206. public static function getInfo() {
  207. return array(
  208. 'name' => 'Top visitor blocking',
  209. 'description' => 'Tests blocking of IP addresses via the top visitors report.',
  210. 'group' => 'Statistics'
  211. );
  212. }
  213. /**
  214. * Blocks an IP address via the top visitors report and then unblocks it.
  215. */
  216. function testIPAddressBlocking() {
  217. // IP address for testing.
  218. $test_ip_address = '192.168.1.1';
  219. // Verify the IP address from accesslog appears on the top visitors page
  220. // and that a 'block IP address' link is displayed.
  221. $this->drupalLogin($this->blocking_user);
  222. $this->drupalGet('admin/reports/visitors');
  223. $this->assertText($test_ip_address, t('IP address found.'));
  224. $this->assertText(t('block IP address'), t('Block IP link displayed'));
  225. // Block the IP address.
  226. $this->clickLink('block IP address');
  227. $this->assertText(t('IP address blocking'), t('IP blocking page displayed.'));
  228. $edit = array();
  229. $edit['ip'] = $test_ip_address;
  230. $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
  231. $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField();
  232. $this->assertNotEqual($ip, FALSE, t('IP address found in database'));
  233. $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $edit['ip'])), t('IP address was blocked.'));
  234. // Verify that the block/unblock link on the top visitors page has been
  235. // altered.
  236. $this->drupalGet('admin/reports/visitors');
  237. $this->assertText(t('unblock IP address'), t('Unblock IP address link displayed'));
  238. // Unblock the IP address.
  239. $this->clickLink('unblock IP address');
  240. $this->assertRaw(t('Are you sure you want to delete %ip?', array('%ip' => $test_ip_address)), t('IP address deletion confirmation found.'));
  241. $edit = array();
  242. $this->drupalPost('admin/config/people/ip-blocking/delete/1', NULL, t('Delete'));
  243. $this->assertRaw(t('The IP address %ip was deleted.', array('%ip' => $test_ip_address)), t('IP address deleted.'));
  244. }
  245. }
  246. /**
  247. * Test statistics administration screen.
  248. */
  249. class StatisticsAdminTestCase extends DrupalWebTestCase {
  250. protected $privileged_user;
  251. protected $test_node;
  252. public static function getInfo() {
  253. return array(
  254. 'name' => 'Test statistics admin.',
  255. 'description' => 'Tests the statistics admin.',
  256. 'group' => 'Statistics'
  257. );
  258. }
  259. function setUp() {
  260. parent::setUp('statistics');
  261. $this->privileged_user = $this->drupalCreateUser(array('access statistics', 'administer statistics', 'view post access counter', 'create page content'));
  262. $this->drupalLogin($this->privileged_user);
  263. $this->test_node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->privileged_user->uid));
  264. }
  265. /**
  266. * Verifies that the statistics settings page works.
  267. */
  268. function testStatisticsSettings() {
  269. $this->assertFalse(variable_get('statistics_enable_access_log', 0), t('Access log is disabled by default.'));
  270. $this->assertFalse(variable_get('statistics_count_content_views', 0), t('Count content view log is disabled by default.'));
  271. $this->drupalGet('admin/reports/pages');
  272. $this->assertRaw(t('No statistics available.'), t('Verifying text shown when no statistics is available.'));
  273. // Enable access log and counter on content view.
  274. $edit['statistics_enable_access_log'] = 1;
  275. $edit['statistics_count_content_views'] = 1;
  276. $this->drupalPost('admin/config/system/statistics', $edit, t('Save configuration'));
  277. $this->assertTrue(variable_get('statistics_enable_access_log'), t('Access log is enabled.'));
  278. $this->assertTrue(variable_get('statistics_count_content_views'), t('Count content view log is enabled.'));
  279. // Hit the node.
  280. $this->drupalGet('node/' . $this->test_node->nid);
  281. $this->drupalGet('admin/reports/pages');
  282. $this->assertText('node/1', t('Test node found.'));
  283. // Hit the node again (the counter is incremented after the hit, so
  284. // "1 read" will actually be shown when the node is hit the second time).
  285. $this->drupalGet('node/' . $this->test_node->nid);
  286. $this->assertText('1 read', t('Node is read once.'));
  287. $this->drupalGet('node/' . $this->test_node->nid);
  288. $this->assertText('2 reads', t('Node is read 2 times.'));
  289. }
  290. /**
  291. * Tests that when a node is deleted, the node counter is deleted too.
  292. */
  293. function testDeleteNode() {
  294. variable_set('statistics_count_content_views', 1);
  295. $this->drupalGet('node/' . $this->test_node->nid);
  296. $result = db_select('node_counter', 'n')
  297. ->fields('n', array('nid'))
  298. ->condition('n.nid', $this->test_node->nid)
  299. ->execute()
  300. ->fetchAssoc();
  301. $this->assertEqual($result['nid'], $this->test_node->nid, 'Verifying that the node counter is incremented.');
  302. node_delete($this->test_node->nid);
  303. $result = db_select('node_counter', 'n')
  304. ->fields('n', array('nid'))
  305. ->condition('n.nid', $this->test_node->nid)
  306. ->execute()
  307. ->fetchAssoc();
  308. $this->assertFalse($result, 'Verifying that the node counter is deleted.');
  309. }
  310. /**
  311. * Tests that accesslog reflects when a user is deleted.
  312. */
  313. function testDeleteUser() {
  314. variable_set('statistics_enable_access_log', 1);
  315. variable_set('user_cancel_method', 'user_cancel_delete');
  316. $this->drupalLogout($this->privileged_user);
  317. $account = $this->drupalCreateUser(array('access content', 'cancel account'));
  318. $this->drupalLogin($account);
  319. $this->drupalGet('node/' . $this->test_node->nid);
  320. $account = user_load($account->uid, TRUE);
  321. $this->drupalGet('user/' . $account->uid . '/edit');
  322. $this->drupalPost(NULL, NULL, t('Cancel account'));
  323. $timestamp = time();
  324. $this->drupalPost(NULL, NULL, t('Cancel account'));
  325. // Confirm account cancellation request.
  326. $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
  327. $this->assertFalse(user_load($account->uid, TRUE), t('User is not found in the database.'));
  328. $this->drupalGet('admin/reports/visitors');
  329. $this->assertNoText($account->name, t('Did not find user in visitor statistics.'));
  330. }
  331. /**
  332. * Tests that cron clears day counts and expired access logs.
  333. */
  334. function testExpiredLogs() {
  335. variable_set('statistics_enable_access_log', 1);
  336. variable_set('statistics_count_content_views', 1);
  337. variable_set('statistics_day_timestamp', 8640000);
  338. variable_set('statistics_flush_accesslog_timer', 1);
  339. $this->drupalGet('node/' . $this->test_node->nid);
  340. $this->drupalGet('node/' . $this->test_node->nid);
  341. $this->assertText('1 read', t('Node is read once.'));
  342. $this->drupalGet('admin/reports/pages');
  343. $this->assertText('node/' . $this->test_node->nid, t('Hit URL found.'));
  344. // statistics_cron will subtract the statistics_flush_accesslog_timer
  345. // variable from REQUEST_TIME in the delete query, so wait two secs here to
  346. // make sure the access log will be flushed for the node just hit.
  347. sleep(2);
  348. $this->cronRun();
  349. $this->drupalGet('admin/reports/pages');
  350. $this->assertNoText('node/' . $this->test_node->nid, t('No hit URL found.'));
  351. $result = db_select('node_counter', 'nc')
  352. ->fields('nc', array('daycount'))
  353. ->condition('nid', $this->test_node->nid, '=')
  354. ->execute()
  355. ->fetchField();
  356. $this->assertFalse($result, t('Daycounter is zero.'));
  357. }
  358. }
  359. /**
  360. * Test statistics token replacement in strings.
  361. */
  362. class StatisticsTokenReplaceTestCase extends StatisticsTestCase {
  363. public static function getInfo() {
  364. return array(
  365. 'name' => 'Statistics token replacement',
  366. 'description' => 'Generates text using placeholders for dummy content to check statistics token replacement.',
  367. 'group' => 'Statistics',
  368. );
  369. }
  370. /**
  371. * Creates a node, then tests the statistics tokens generated from it.
  372. */
  373. function testStatisticsTokenReplacement() {
  374. global $language;
  375. // Create user and node.
  376. $user = $this->drupalCreateUser(array('create page content'));
  377. $this->drupalLogin($user);
  378. $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $user->uid));
  379. // Hit the node.
  380. $this->drupalGet('node/' . $node->nid);
  381. $statistics = statistics_get($node->nid);
  382. // Generate and test tokens.
  383. $tests = array();
  384. $tests['[node:total-count]'] = 1;
  385. $tests['[node:day-count]'] = 1;
  386. $tests['[node:last-view]'] = format_date($statistics['timestamp']);
  387. $tests['[node:last-view:short]'] = format_date($statistics['timestamp'], 'short');
  388. // Test to make sure that we generated something for each token.
  389. $this->assertFalse(in_array(0, array_map('strlen', $tests)), t('No empty tokens generated.'));
  390. foreach ($tests as $input => $expected) {
  391. $output = token_replace($input, array('node' => $node), array('language' => $language));
  392. $this->assertEqual($output, $expected, t('Statistics token %token replaced.', array('%token' => $input)));
  393. }
  394. }
  395. }
Login or register to post comments