statistics.test 19 KB

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