statistics.test 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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', 'Testing an uncached page.');
  81. $log = db_query('SELECT * FROM {accesslog}')->fetchAll(PDO::FETCH_ASSOC);
  82. $this->assertTrue(is_array($log) && count($log) == 1, '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', 'Testing a cached page.');
  89. $log = db_query('SELECT * FROM {accesslog}')->fetchAll(PDO::FETCH_ASSOC);
  90. $this->assertTrue(is_array($log) && count($log) == 2, '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, '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, 'Page request was logged.');
  112. $this->assertEqual(array_intersect_key($log[6], $expected), $expected);
  113. // Create a path longer than 255 characters. Drupal's .htaccess file
  114. // instructs Apache to test paths against the file system before routing to
  115. // index.php. Many file systems restrict file names to 255 characters
  116. // (http://en.wikipedia.org/wiki/Comparison_of_file_systems#Limits), and
  117. // Apache returns a 403 when testing longer file names, but the total path
  118. // length is not restricted.
  119. $long_path = $this->randomName(127) . '/' . $this->randomName(128);
  120. // Test that the long path is properly truncated when logged.
  121. $this->drupalGet($long_path);
  122. $log = db_query('SELECT * FROM {accesslog}')->fetchAll(PDO::FETCH_ASSOC);
  123. $this->assertTrue(is_array($log) && count($log) == 8, 'Page request was logged for a path over 255 characters.');
  124. $this->assertEqual($log[7]['path'], truncate_utf8($long_path, 255));
  125. }
  126. }
  127. /**
  128. * Tests that report pages render properly, and that access logging works.
  129. */
  130. class StatisticsReportsTestCase extends StatisticsTestCase {
  131. public static function getInfo() {
  132. return array(
  133. 'name' => 'Statistics reports tests',
  134. 'description' => 'Tests display of statistics report pages and access logging.',
  135. 'group' => 'Statistics'
  136. );
  137. }
  138. /**
  139. * Verifies that 'Recent hits' renders properly and displays the added hit.
  140. */
  141. function testRecentHits() {
  142. $this->drupalGet('admin/reports/hits');
  143. $this->assertText('test', 'Hit title found.');
  144. $this->assertText('node/1', 'Hit URL found.');
  145. $this->assertText('Anonymous', 'Hit user found.');
  146. }
  147. /**
  148. * Verifies that 'Top pages' renders properly and displays the added hit.
  149. */
  150. function testTopPages() {
  151. $this->drupalGet('admin/reports/pages');
  152. $this->assertText('test', 'Hit title found.');
  153. $this->assertText('node/1', 'Hit URL found.');
  154. }
  155. /**
  156. * Verifies that 'Top referrers' renders properly and displays the added hit.
  157. */
  158. function testTopReferrers() {
  159. $this->drupalGet('admin/reports/referrers');
  160. $this->assertText('http://example.com', 'Hit referrer found.');
  161. }
  162. /**
  163. * Verifies that 'Details' page renders properly and displays the added hit.
  164. */
  165. function testDetails() {
  166. $this->drupalGet('admin/reports/access/1');
  167. $this->assertText('test', 'Hit title found.');
  168. $this->assertText('node/1', 'Hit URL found.');
  169. $this->assertText('Anonymous', 'Hit user found.');
  170. }
  171. /**
  172. * Verifies that access logging is working and is reported correctly.
  173. */
  174. function testAccessLogging() {
  175. $this->drupalGet('admin/reports/referrers');
  176. $this->drupalGet('admin/reports/hits');
  177. $this->assertText('Top referrers in the past 3 days', 'Hit title found.');
  178. $this->assertText('admin/reports/referrers', 'Hit URL found.');
  179. }
  180. /**
  181. * Tests the "popular content" block.
  182. */
  183. function testPopularContentBlock() {
  184. // Visit a node to have something show up in the block.
  185. $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->blocking_user->uid));
  186. $this->drupalGet('node/' . $node->nid);
  187. // Configure and save the block.
  188. $block = block_load('statistics', 'popular');
  189. $block->theme = variable_get('theme_default', 'bartik');
  190. $block->status = 1;
  191. $block->pages = '';
  192. $block->region = 'sidebar_first';
  193. $block->cache = -1;
  194. $block->visibility = 0;
  195. $edit = array('statistics_block_top_day_num' => 3, 'statistics_block_top_all_num' => 3, 'statistics_block_top_last_num' => 3);
  196. module_invoke('statistics', 'block_save', 'popular', $edit);
  197. drupal_write_record('block', $block);
  198. // Get some page and check if the block is displayed.
  199. $this->drupalGet('user');
  200. $this->assertText('Popular content', 'Found the popular content block.');
  201. $this->assertText("Today's", 'Found today\'s popular content.');
  202. $this->assertText('All time', 'Found the alll time popular content.');
  203. $this->assertText('Last viewed', 'Found the last viewed popular content.');
  204. $this->assertRaw(l($node->title, 'node/' . $node->nid), 'Found link to visited node.');
  205. }
  206. }
  207. /**
  208. * Tests that the visitor blocking functionality works.
  209. */
  210. class StatisticsBlockVisitorsTestCase extends StatisticsTestCase {
  211. public static function getInfo() {
  212. return array(
  213. 'name' => 'Top visitor blocking',
  214. 'description' => 'Tests blocking of IP addresses via the top visitors report.',
  215. 'group' => 'Statistics'
  216. );
  217. }
  218. /**
  219. * Blocks an IP address via the top visitors report and then unblocks it.
  220. */
  221. function testIPAddressBlocking() {
  222. // IP address for testing.
  223. $test_ip_address = '192.168.1.1';
  224. // Verify the IP address from accesslog appears on the top visitors page
  225. // and that a 'block IP address' link is displayed.
  226. $this->drupalLogin($this->blocking_user);
  227. $this->drupalGet('admin/reports/visitors');
  228. $this->assertText($test_ip_address, 'IP address found.');
  229. $this->assertText(t('block IP address'), 'Block IP link displayed');
  230. // Block the IP address.
  231. $this->clickLink('block IP address');
  232. $this->assertText(t('IP address blocking'), 'IP blocking page displayed.');
  233. $edit = array();
  234. $edit['ip'] = $test_ip_address;
  235. $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
  236. $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField();
  237. $this->assertNotEqual($ip, FALSE, 'IP address found in database');
  238. $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $edit['ip'])), 'IP address was blocked.');
  239. // Verify that the block/unblock link on the top visitors page has been
  240. // altered.
  241. $this->drupalGet('admin/reports/visitors');
  242. $this->assertText(t('unblock IP address'), 'Unblock IP address link displayed');
  243. // Unblock the IP address.
  244. $this->clickLink('unblock IP address');
  245. $this->assertRaw(t('Are you sure you want to delete %ip?', array('%ip' => $test_ip_address)), 'IP address deletion confirmation found.');
  246. $edit = array();
  247. $this->drupalPost('admin/config/people/ip-blocking/delete/1', NULL, t('Delete'));
  248. $this->assertRaw(t('The IP address %ip was deleted.', array('%ip' => $test_ip_address)), 'IP address deleted.');
  249. }
  250. }
  251. /**
  252. * Tests the statistics administration screen.
  253. */
  254. class StatisticsAdminTestCase extends DrupalWebTestCase {
  255. /**
  256. * A user that has permission to administer and access statistics.
  257. *
  258. * @var object|FALSE
  259. *
  260. * A fully loaded user object, or FALSE if user creation failed.
  261. */
  262. protected $privileged_user;
  263. /**
  264. * A page node for which to check access statistics.
  265. *
  266. * @var object
  267. */
  268. protected $test_node;
  269. public static function getInfo() {
  270. return array(
  271. 'name' => 'Test statistics admin.',
  272. 'description' => 'Tests the statistics admin.',
  273. 'group' => 'Statistics'
  274. );
  275. }
  276. function setUp() {
  277. parent::setUp('statistics');
  278. $this->privileged_user = $this->drupalCreateUser(array('access statistics', 'administer statistics', 'view post access counter', 'create page content'));
  279. $this->drupalLogin($this->privileged_user);
  280. $this->test_node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->privileged_user->uid));
  281. }
  282. /**
  283. * Verifies that the statistics settings page works.
  284. */
  285. function testStatisticsSettings() {
  286. $this->assertFalse(variable_get('statistics_enable_access_log', 0), 'Access log is disabled by default.');
  287. $this->assertFalse(variable_get('statistics_count_content_views', 0), 'Count content view log is disabled by default.');
  288. $this->drupalGet('admin/reports/pages');
  289. $this->assertRaw(t('No statistics available.'), 'Verifying text shown when no statistics is available.');
  290. // Enable access log and counter on content view.
  291. $edit['statistics_enable_access_log'] = 1;
  292. $edit['statistics_count_content_views'] = 1;
  293. $this->drupalPost('admin/config/system/statistics', $edit, t('Save configuration'));
  294. $this->assertTrue(variable_get('statistics_enable_access_log'), 'Access log is enabled.');
  295. $this->assertTrue(variable_get('statistics_count_content_views'), 'Count content view log is enabled.');
  296. // Hit the node.
  297. $this->drupalGet('node/' . $this->test_node->nid);
  298. $this->drupalGet('admin/reports/pages');
  299. $this->assertText('node/1', 'Test node found.');
  300. // Hit the node again (the counter is incremented after the hit, so
  301. // "1 read" will actually be shown when the node is hit the second time).
  302. $this->drupalGet('node/' . $this->test_node->nid);
  303. $this->assertText('1 read', 'Node is read once.');
  304. $this->drupalGet('node/' . $this->test_node->nid);
  305. $this->assertText('2 reads', 'Node is read 2 times.');
  306. }
  307. /**
  308. * Tests that when a node is deleted, the node counter is deleted too.
  309. */
  310. function testDeleteNode() {
  311. variable_set('statistics_count_content_views', 1);
  312. $this->drupalGet('node/' . $this->test_node->nid);
  313. $result = db_select('node_counter', 'n')
  314. ->fields('n', array('nid'))
  315. ->condition('n.nid', $this->test_node->nid)
  316. ->execute()
  317. ->fetchAssoc();
  318. $this->assertEqual($result['nid'], $this->test_node->nid, 'Verifying that the node counter is incremented.');
  319. node_delete($this->test_node->nid);
  320. $result = db_select('node_counter', 'n')
  321. ->fields('n', array('nid'))
  322. ->condition('n.nid', $this->test_node->nid)
  323. ->execute()
  324. ->fetchAssoc();
  325. $this->assertFalse($result, 'Verifying that the node counter is deleted.');
  326. }
  327. /**
  328. * Tests that accesslog reflects when a user is deleted.
  329. */
  330. function testDeleteUser() {
  331. variable_set('statistics_enable_access_log', 1);
  332. variable_set('user_cancel_method', 'user_cancel_delete');
  333. $this->drupalLogout($this->privileged_user);
  334. $account = $this->drupalCreateUser(array('access content', 'cancel account'));
  335. $this->drupalLogin($account);
  336. $this->drupalGet('node/' . $this->test_node->nid);
  337. $account = user_load($account->uid, TRUE);
  338. $this->drupalGet('user/' . $account->uid . '/edit');
  339. $this->drupalPost(NULL, NULL, t('Cancel account'));
  340. $timestamp = time();
  341. $this->drupalPost(NULL, NULL, t('Cancel account'));
  342. // Confirm account cancellation request.
  343. $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
  344. $this->assertFalse(user_load($account->uid, TRUE), 'User is not found in the database.');
  345. $this->drupalGet('admin/reports/visitors');
  346. $this->assertNoText($account->name, 'Did not find user in visitor statistics.');
  347. }
  348. /**
  349. * Tests that cron clears day counts and expired access logs.
  350. */
  351. function testExpiredLogs() {
  352. variable_set('statistics_enable_access_log', 1);
  353. variable_set('statistics_count_content_views', 1);
  354. variable_set('statistics_day_timestamp', 8640000);
  355. variable_set('statistics_flush_accesslog_timer', 1);
  356. $this->drupalGet('node/' . $this->test_node->nid);
  357. $this->drupalGet('node/' . $this->test_node->nid);
  358. $this->assertText('1 read', 'Node is read once.');
  359. $this->drupalGet('admin/reports/pages');
  360. $this->assertText('node/' . $this->test_node->nid, 'Hit URL found.');
  361. // statistics_cron will subtract the statistics_flush_accesslog_timer
  362. // variable from REQUEST_TIME in the delete query, so wait two secs here to
  363. // make sure the access log will be flushed for the node just hit.
  364. sleep(2);
  365. $this->cronRun();
  366. $this->drupalGet('admin/reports/pages');
  367. $this->assertNoText('node/' . $this->test_node->nid, 'No hit URL found.');
  368. $result = db_select('node_counter', 'nc')
  369. ->fields('nc', array('daycount'))
  370. ->condition('nid', $this->test_node->nid, '=')
  371. ->execute()
  372. ->fetchField();
  373. $this->assertFalse($result, 'Daycounter is zero.');
  374. }
  375. }
  376. /**
  377. * Tests statistics token replacement in strings.
  378. */
  379. class StatisticsTokenReplaceTestCase extends StatisticsTestCase {
  380. public static function getInfo() {
  381. return array(
  382. 'name' => 'Statistics token replacement',
  383. 'description' => 'Generates text using placeholders for dummy content to check statistics token replacement.',
  384. 'group' => 'Statistics',
  385. );
  386. }
  387. /**
  388. * Creates a node, then tests the statistics tokens generated from it.
  389. */
  390. function testStatisticsTokenReplacement() {
  391. global $language;
  392. // Create user and node.
  393. $user = $this->drupalCreateUser(array('create page content'));
  394. $this->drupalLogin($user);
  395. $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $user->uid));
  396. // Hit the node.
  397. $this->drupalGet('node/' . $node->nid);
  398. $statistics = statistics_get($node->nid);
  399. // Generate and test tokens.
  400. $tests = array();
  401. $tests['[node:total-count]'] = 1;
  402. $tests['[node:day-count]'] = 1;
  403. $tests['[node:last-view]'] = format_date($statistics['timestamp']);
  404. $tests['[node:last-view:short]'] = format_date($statistics['timestamp'], 'short');
  405. // Test to make sure that we generated something for each token.
  406. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  407. foreach ($tests as $input => $expected) {
  408. $output = token_replace($input, array('node' => $node), array('language' => $language));
  409. $this->assertEqual($output, $expected, format_string('Statistics token %token replaced.', array('%token' => $input)));
  410. }
  411. }
  412. }