statistics.test 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. <?php
  2. /**
  3. * @file
  4. * Tests for the Statistics module.
  5. */
  6. /**
  7. * Defines a base class for testing 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 all pages.
  43. *
  44. * We subclass DrupalWebTestCase rather than StatisticsTestCase, because we
  45. * want 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. * Tests the statistics administration screen.
  248. */
  249. class StatisticsAdminTestCase extends DrupalWebTestCase {
  250. /**
  251. * A user that has permission to administer and access statistics.
  252. *
  253. * @var object|FALSE
  254. *
  255. * A fully loaded user object, or FALSE if user creation failed.
  256. */
  257. protected $privileged_user;
  258. /**
  259. * A page node for which to check access statistics.
  260. *
  261. * @var object
  262. */
  263. protected $test_node;
  264. public static function getInfo() {
  265. return array(
  266. 'name' => 'Test statistics admin.',
  267. 'description' => 'Tests the statistics admin.',
  268. 'group' => 'Statistics'
  269. );
  270. }
  271. function setUp() {
  272. parent::setUp('statistics');
  273. $this->privileged_user = $this->drupalCreateUser(array('access statistics', 'administer statistics', 'view post access counter', 'create page content'));
  274. $this->drupalLogin($this->privileged_user);
  275. $this->test_node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->privileged_user->uid));
  276. }
  277. /**
  278. * Verifies that the statistics settings page works.
  279. */
  280. function testStatisticsSettings() {
  281. $this->assertFalse(variable_get('statistics_enable_access_log', 0), t('Access log is disabled by default.'));
  282. $this->assertFalse(variable_get('statistics_count_content_views', 0), t('Count content view log is disabled by default.'));
  283. $this->drupalGet('admin/reports/pages');
  284. $this->assertRaw(t('No statistics available.'), t('Verifying text shown when no statistics is available.'));
  285. // Enable access log and counter on content view.
  286. $edit['statistics_enable_access_log'] = 1;
  287. $edit['statistics_count_content_views'] = 1;
  288. $this->drupalPost('admin/config/system/statistics', $edit, t('Save configuration'));
  289. $this->assertTrue(variable_get('statistics_enable_access_log'), t('Access log is enabled.'));
  290. $this->assertTrue(variable_get('statistics_count_content_views'), t('Count content view log is enabled.'));
  291. // Hit the node.
  292. $this->drupalGet('node/' . $this->test_node->nid);
  293. $this->drupalGet('admin/reports/pages');
  294. $this->assertText('node/1', t('Test node found.'));
  295. // Hit the node again (the counter is incremented after the hit, so
  296. // "1 read" will actually be shown when the node is hit the second time).
  297. $this->drupalGet('node/' . $this->test_node->nid);
  298. $this->assertText('1 read', t('Node is read once.'));
  299. $this->drupalGet('node/' . $this->test_node->nid);
  300. $this->assertText('2 reads', t('Node is read 2 times.'));
  301. }
  302. /**
  303. * Tests that when a node is deleted, the node counter is deleted too.
  304. */
  305. function testDeleteNode() {
  306. variable_set('statistics_count_content_views', 1);
  307. $this->drupalGet('node/' . $this->test_node->nid);
  308. $result = db_select('node_counter', 'n')
  309. ->fields('n', array('nid'))
  310. ->condition('n.nid', $this->test_node->nid)
  311. ->execute()
  312. ->fetchAssoc();
  313. $this->assertEqual($result['nid'], $this->test_node->nid, 'Verifying that the node counter is incremented.');
  314. node_delete($this->test_node->nid);
  315. $result = db_select('node_counter', 'n')
  316. ->fields('n', array('nid'))
  317. ->condition('n.nid', $this->test_node->nid)
  318. ->execute()
  319. ->fetchAssoc();
  320. $this->assertFalse($result, 'Verifying that the node counter is deleted.');
  321. }
  322. /**
  323. * Tests that accesslog reflects when a user is deleted.
  324. */
  325. function testDeleteUser() {
  326. variable_set('statistics_enable_access_log', 1);
  327. variable_set('user_cancel_method', 'user_cancel_delete');
  328. $this->drupalLogout($this->privileged_user);
  329. $account = $this->drupalCreateUser(array('access content', 'cancel account'));
  330. $this->drupalLogin($account);
  331. $this->drupalGet('node/' . $this->test_node->nid);
  332. $account = user_load($account->uid, TRUE);
  333. $this->drupalGet('user/' . $account->uid . '/edit');
  334. $this->drupalPost(NULL, NULL, t('Cancel account'));
  335. $timestamp = time();
  336. $this->drupalPost(NULL, NULL, t('Cancel account'));
  337. // Confirm account cancellation request.
  338. $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
  339. $this->assertFalse(user_load($account->uid, TRUE), t('User is not found in the database.'));
  340. $this->drupalGet('admin/reports/visitors');
  341. $this->assertNoText($account->name, t('Did not find user in visitor statistics.'));
  342. }
  343. /**
  344. * Tests that cron clears day counts and expired access logs.
  345. */
  346. function testExpiredLogs() {
  347. variable_set('statistics_enable_access_log', 1);
  348. variable_set('statistics_count_content_views', 1);
  349. variable_set('statistics_day_timestamp', 8640000);
  350. variable_set('statistics_flush_accesslog_timer', 1);
  351. $this->drupalGet('node/' . $this->test_node->nid);
  352. $this->drupalGet('node/' . $this->test_node->nid);
  353. $this->assertText('1 read', t('Node is read once.'));
  354. $this->drupalGet('admin/reports/pages');
  355. $this->assertText('node/' . $this->test_node->nid, t('Hit URL found.'));
  356. // statistics_cron will subtract the statistics_flush_accesslog_timer
  357. // variable from REQUEST_TIME in the delete query, so wait two secs here to
  358. // make sure the access log will be flushed for the node just hit.
  359. sleep(2);
  360. $this->cronRun();
  361. $this->drupalGet('admin/reports/pages');
  362. $this->assertNoText('node/' . $this->test_node->nid, t('No hit URL found.'));
  363. $result = db_select('node_counter', 'nc')
  364. ->fields('nc', array('daycount'))
  365. ->condition('nid', $this->test_node->nid, '=')
  366. ->execute()
  367. ->fetchField();
  368. $this->assertFalse($result, t('Daycounter is zero.'));
  369. }
  370. }
  371. /**
  372. * Tests statistics token replacement in strings.
  373. */
  374. class StatisticsTokenReplaceTestCase extends StatisticsTestCase {
  375. public static function getInfo() {
  376. return array(
  377. 'name' => 'Statistics token replacement',
  378. 'description' => 'Generates text using placeholders for dummy content to check statistics token replacement.',
  379. 'group' => 'Statistics',
  380. );
  381. }
  382. /**
  383. * Creates a node, then tests the statistics tokens generated from it.
  384. */
  385. function testStatisticsTokenReplacement() {
  386. global $language;
  387. // Create user and node.
  388. $user = $this->drupalCreateUser(array('create page content'));
  389. $this->drupalLogin($user);
  390. $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $user->uid));
  391. // Hit the node.
  392. $this->drupalGet('node/' . $node->nid);
  393. $statistics = statistics_get($node->nid);
  394. // Generate and test tokens.
  395. $tests = array();
  396. $tests['[node:total-count]'] = 1;
  397. $tests['[node:day-count]'] = 1;
  398. $tests['[node:last-view]'] = format_date($statistics['timestamp']);
  399. $tests['[node:last-view:short]'] = format_date($statistics['timestamp'], 'short');
  400. // Test to make sure that we generated something for each token.
  401. $this->assertFalse(in_array(0, array_map('strlen', $tests)), t('No empty tokens generated.'));
  402. foreach ($tests as $input => $expected) {
  403. $output = token_replace($input, array('node' => $node), array('language' => $language));
  404. $this->assertEqual($output, $expected, t('Statistics token %token replaced.', array('%token' => $input)));
  405. }
  406. }
  407. }