statistics.test 19 KB

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