googleanalytics.test 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. <?php
  2. /**
  3. * @file
  4. * Test file for Google Analytics module.
  5. */
  6. class GoogleAnalyticsBasicTest extends DrupalWebTestCase {
  7. public static function getInfo() {
  8. return array(
  9. 'name' => 'Google Analytics basic tests',
  10. 'description' => 'Test basic functionality of Google Analytics module.',
  11. 'group' => 'Google Analytics',
  12. );
  13. }
  14. function setUp() {
  15. parent::setUp('googleanalytics');
  16. $permissions = array(
  17. 'access administration pages',
  18. 'administer google analytics',
  19. 'administer modules',
  20. 'administer site configuration',
  21. );
  22. // User to set up google_analytics.
  23. $this->admin_user = $this->drupalCreateUser($permissions);
  24. $this->drupalLogin($this->admin_user);
  25. }
  26. function testGoogleAnalyticsConfiguration() {
  27. // Check if Configure link is available on 'Modules' page.
  28. // Requires 'administer modules' permission.
  29. $this->drupalGet('admin/modules');
  30. $this->assertRaw('admin/config/system/googleanalytics', '[testGoogleAnalyticsConfiguration]: Configure link from Modules page to Google Analytics Settings page exists.');
  31. // Check if Configure link is available on 'Status Reports' page. NOTE: Link is only shown without UA code configured.
  32. // Requires 'administer site configuration' permission.
  33. $this->drupalGet('admin/reports/status');
  34. $this->assertRaw('admin/config/system/googleanalytics', '[testGoogleAnalyticsConfiguration]: Configure link from Status Reports page to Google Analytics Settings page exists.');
  35. // Check for setting page's presence.
  36. $this->drupalGet('admin/config/system/googleanalytics');
  37. $this->assertRaw(t('Web Property ID'), '[testGoogleAnalyticsConfiguration]: Settings page displayed.');
  38. // Check for account code validation.
  39. $edit['googleanalytics_account'] = $this->randomName(2);
  40. $this->drupalPost('admin/config/system/googleanalytics', $edit, t('Save configuration'));
  41. $this->assertRaw(t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.'), '[testGoogleAnalyticsConfiguration]: Invalid Web Property ID number validated.');
  42. }
  43. function testGoogleAnalyticsPageVisibility() {
  44. // Verify that no tracking code is embedded into the webpage; if there is
  45. // only the module installed, but UA code not configured. See #2246991.
  46. $this->drupalGet('');
  47. $this->assertNoRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPageVisibility]: Tracking code is not displayed without UA code configured.');
  48. $ua_code = 'UA-123456-1';
  49. variable_set('googleanalytics_account', $ua_code);
  50. // Show tracking on "every page except the listed pages".
  51. variable_set('googleanalytics_visibility_pages', 0);
  52. // Disable tracking on "admin*" pages only.
  53. variable_set('googleanalytics_pages', "admin\nadmin/*");
  54. // Enable tracking only for authenticated users only.
  55. variable_set('googleanalytics_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
  56. // Check tracking code visibility.
  57. $this->drupalGet('');
  58. $this->assertRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is displayed for authenticated users.');
  59. // Test whether tracking code is not included on pages to omit.
  60. $this->drupalGet('admin');
  61. $this->assertNoRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is not displayed on admin page.');
  62. $this->drupalGet('admin/config/system/googleanalytics');
  63. // Checking for tracking code URI here, as $ua_code is displayed in the form.
  64. $this->assertNoRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPageVisibility]: Tracking code is not displayed on admin subpage.');
  65. // Test whether tracking code display is properly flipped.
  66. variable_set('googleanalytics_visibility_pages', 1);
  67. $this->drupalGet('admin');
  68. $this->assertRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is displayed on admin page.');
  69. $this->drupalGet('admin/config/system/googleanalytics');
  70. // Checking for tracking code URI here, as $ua_code is displayed in the form.
  71. $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPageVisibility]: Tracking code is displayed on admin subpage.');
  72. $this->drupalGet('');
  73. $this->assertNoRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is NOT displayed on front page.');
  74. // Test whether tracking code is not display for anonymous.
  75. $this->drupalLogout();
  76. $this->drupalGet('');
  77. $this->assertNoRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is NOT displayed for anonymous.');
  78. // Switch back to every page except the listed pages.
  79. variable_set('googleanalytics_visibility_pages', 0);
  80. // Enable tracking code for all user roles.
  81. variable_set('googleanalytics_roles', array());
  82. // Test whether 403 forbidden tracking code is shown if user has no access.
  83. $this->drupalGet('admin');
  84. $this->assertRaw('/403.html', '[testGoogleAnalyticsPageVisibility]: 403 Forbidden tracking code shown if user has no access.');
  85. // Test whether 404 not found tracking code is shown on non-existent pages.
  86. $this->drupalGet($this->randomName(64));
  87. $this->assertRaw('/404.html', '[testGoogleAnalyticsPageVisibility]: 404 Not Found tracking code shown on non-existent page.');
  88. // DNT Tests:
  89. // Enable system internal page cache for anonymous users.
  90. variable_set('cache', 1);
  91. // Test whether DNT headers will fail to disable embedding of tracking code.
  92. $this->drupalGet('', array(), array('DNT: 1'));
  93. $this->assertRaw('ga("send", "pageview");', '[testGoogleAnalyticsDNTVisibility]: DNT header send from client, but page caching is enabled and tracker cannot removed.');
  94. // DNT works only with system internal page cache for anonymous users disabled.
  95. variable_set('cache', 0);
  96. $this->drupalGet('');
  97. $this->assertRaw('ga("send", "pageview");', '[testGoogleAnalyticsDNTVisibility]: Tracking is enabled without DNT header.');
  98. // Test whether DNT header is able to remove the tracking code.
  99. $this->drupalGet('', array(), array('DNT: 1'));
  100. $this->assertNoRaw('ga("send", "pageview");', '[testGoogleAnalyticsDNTVisibility]: DNT header received from client. Tracking has been disabled by browser.');
  101. // Disable DNT feature and see if tracker is still embedded.
  102. variable_set('googleanalytics_privacy_donottrack', 0);
  103. $this->drupalGet('', array(), array('DNT: 1'));
  104. $this->assertRaw('ga("send", "pageview");', '[testGoogleAnalyticsDNTVisibility]: DNT feature is disabled, DNT header from browser has been ignored.');
  105. }
  106. function testGoogleAnalyticsTrackingCode() {
  107. $ua_code = 'UA-123456-2';
  108. variable_set('googleanalytics_account', $ua_code);
  109. // Show tracking code on every page except the listed pages.
  110. variable_set('googleanalytics_visibility_pages', 0);
  111. // Enable tracking code for all user roles.
  112. variable_set('googleanalytics_roles', array());
  113. /* Sample JS code as added to page:
  114. <script type="text/javascript" src="/sites/all/modules/google_analytics/googleanalytics.js?w"></script>
  115. <script>
  116. (function(q,u,i,c,k){window['GoogleAnalyticsObject']=q;
  117. window[q]=window[q]||function(){(window[q].q=window[q].q||[]).push(arguments)},
  118. window[q].l=1*new Date();c=i.createElement(u),k=i.getElementsByTagName(u)[0];
  119. c.async=true;c.src='//www.google-analytics.com/analytics.js';
  120. k.parentNode.insertBefore(c,k)})('ga','script',document);
  121. ga('create', 'UA-123456-7');
  122. ga('send', 'pageview');
  123. </script>
  124. <!-- End Google Analytics -->
  125. */
  126. // Test whether tracking code uses latest JS.
  127. variable_set('googleanalytics_cache', 0);
  128. $this->drupalGet('');
  129. $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsTrackingCode]: Latest tracking code used.');
  130. // Test whether anonymize visitors IP address feature has been enabled.
  131. variable_set('googleanalytics_tracker_anonymizeip', 0);
  132. $this->drupalGet('');
  133. $this->assertNoRaw('ga("set", "anonymizeIp", true);', '[testGoogleAnalyticsTrackingCode]: Anonymize visitors IP address not found on frontpage.');
  134. // Enable anonymizing of IP addresses.
  135. variable_set('googleanalytics_tracker_anonymizeip', 1);
  136. $this->drupalGet('');
  137. $this->assertRaw('ga("set", "anonymizeIp", true);', '[testGoogleAnalyticsTrackingCode]: Anonymize visitors IP address found on frontpage.');
  138. // Test if track Enhanced Link Attribution is enabled.
  139. variable_set('googleanalytics_tracklinkid', 1);
  140. $this->drupalGet('');
  141. $this->assertRaw('ga("require", "linkid", "linkid.js");', '[testGoogleAnalyticsTrackingCode]: Tracking code for Enhanced Link Attribution is enabled.');
  142. // Test if track Enhanced Link Attribution is disabled.
  143. variable_set('googleanalytics_tracklinkid', 0);
  144. $this->drupalGet('');
  145. $this->assertNoRaw('ga("require", "linkid", "linkid.js");', '[testGoogleAnalyticsTrackingCode]: Tracking code for Enhanced Link Attribution is not enabled.');
  146. // Test if tracking of User ID is enabled.
  147. variable_set('googleanalytics_trackuserid', 1);
  148. $this->drupalGet('');
  149. $this->assertRaw(', {"cookieDomain":"auto","userId":"', '[testGoogleAnalyticsTrackingCode]: Tracking code for User ID is enabled.');
  150. // Test if tracking of User ID is disabled.
  151. variable_set('googleanalytics_trackuserid', 0);
  152. $this->drupalGet('');
  153. $this->assertNoRaw(', {"cookieDomain":"auto","userId":"', '[testGoogleAnalyticsTrackingCode]: Tracking code for User ID is disabled.');
  154. // Test if tracking of url fragments is enabled.
  155. variable_set('googleanalytics_trackurlfragments', 1);
  156. $this->drupalGet('');
  157. $this->assertRaw('ga("set", "page", location.pathname + location.search + location.hash);', '[testGoogleAnalyticsTrackingCode]: Tracking code for url fragments is enabled.');
  158. // Test if tracking of url fragments is disabled.
  159. variable_set('googleanalytics_trackurlfragments', 0);
  160. $this->drupalGet('');
  161. $this->assertNoRaw('ga("set", "page", location.pathname + location.search + location.hash);', '[testGoogleAnalyticsTrackingCode]: Tracking code for url fragments is not enabled.');
  162. // Test if track display features is enabled.
  163. variable_set('googleanalytics_trackdoubleclick', 1);
  164. $this->drupalGet('');
  165. $this->assertRaw('ga("require", "displayfeatures");', '[testGoogleAnalyticsTrackingCode]: Tracking code for display features is enabled.');
  166. // Test if track display features is disabled.
  167. variable_set('googleanalytics_trackdoubleclick', 0);
  168. $this->drupalGet('');
  169. $this->assertNoRaw('ga("require", "displayfeatures");', '[testGoogleAnalyticsTrackingCode]: Tracking code for display features is not enabled.');
  170. // Test whether single domain tracking is active.
  171. $this->drupalGet('');
  172. $this->assertRaw('{"cookieDomain":"auto"}', '[testGoogleAnalyticsTrackingCode]: Single domain tracking is active.');
  173. // Enable "One domain with multiple subdomains".
  174. variable_set('googleanalytics_domain_mode', 1);
  175. $this->drupalGet('');
  176. // Test may run on localhost, an ipaddress or real domain name.
  177. // TODO: Workaround to run tests successfully. This feature cannot tested reliable.
  178. global $cookie_domain;
  179. if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
  180. $this->assertRaw('{"cookieDomain":"' . $cookie_domain . '"}', '[testGoogleAnalyticsTrackingCode]: One domain with multiple subdomains is active on real host.');
  181. }
  182. else {
  183. // Special cases, Localhost and IP addresses don't show '_setDomainName'.
  184. $this->assertNoRaw('{"cookieDomain":"' . $cookie_domain . '"}', '[testGoogleAnalyticsTrackingCode]: One domain with multiple subdomains may be active on localhost (test result is not reliable).');
  185. }
  186. // Enable "Multiple top-level domains" tracking.
  187. variable_set('googleanalytics_domain_mode', 2);
  188. variable_set('googleanalytics_cross_domains', "www.example.com\nwww.example.net");
  189. $this->drupalGet('');
  190. $this->assertRaw('ga("create", "' . $ua_code . '", {"cookieDomain":"auto","allowLinker":true', '[testGoogleAnalyticsTrackingCode]: "allowLinker" has been found. Cross domain tracking is active.');
  191. $this->assertRaw('ga("require", "linker");', '[testGoogleAnalyticsTrackingCode]: Require linker has been found. Cross domain tracking is active.');
  192. $this->assertRaw('ga("linker:autoLink", ["www.example.com","www.example.net"]);', '[testGoogleAnalyticsTrackingCode]: "linker:autoLink" has been found. Cross domain tracking is active.');
  193. $this->assertRaw('"trackCrossDomains":["www.example.com","www.example.net"]', '[testGoogleAnalyticsTrackingCode]: Cross domain tracking with www.example.com and www.example.net is active.');
  194. variable_set('googleanalytics_domain_mode', 0);
  195. // Test whether debugging script has been enabled.
  196. variable_set('googleanalytics_debug', 1);
  197. $this->drupalGet('');
  198. $this->assertRaw('//www.google-analytics.com/analytics_debug.js', '[testGoogleAnalyticsTrackingCode]: Google debugging script has been enabled.');
  199. // Check if text and link is shown on 'Status Reports' page.
  200. // Requires 'administer site configuration' permission.
  201. $this->drupalGet('admin/reports/status');
  202. $this->assertRaw(t('Google Analytics module has debugging enabled. Please disable debugging setting in production sites from the <a href="@url">Google Analytics settings page</a>.', array('@url' => url('admin/config/system/googleanalytics'))), '[testGoogleAnalyticsConfiguration]: Debugging enabled is shown on Status Reports page.');
  203. // Test whether debugging script has been disabled.
  204. variable_set('googleanalytics_debug', 0);
  205. $this->drupalGet('');
  206. $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsTrackingCode]: Google debugging script has been disabled.');
  207. // Test whether the CREATE and BEFORE and AFTER code is added to the tracker.
  208. $codesnippet_create = array(
  209. 'cookieDomain' => 'foo.example.com',
  210. 'cookieName' => 'myNewName',
  211. 'cookieExpires' => 20000,
  212. 'allowAnchor' => TRUE,
  213. 'sampleRate' => 4.3,
  214. );
  215. variable_set('googleanalytics_codesnippet_create', $codesnippet_create);
  216. variable_set('googleanalytics_codesnippet_before', 'ga("set", "forceSSL", true);');
  217. variable_set('googleanalytics_codesnippet_after', 'ga("create", "UA-123456-3", {"name": "newTracker"});ga("newTracker.send", "pageview");');
  218. $this->drupalGet('');
  219. $this->assertRaw('ga("create", "' . $ua_code . '", {"cookieDomain":"foo.example.com","cookieName":"myNewName","cookieExpires":20000,"allowAnchor":true,"sampleRate":4.3});', '[testGoogleAnalyticsTrackingCode]: Create only fields have been found.');
  220. $this->assertRaw('ga("set", "forceSSL", true);', '[testGoogleAnalyticsTrackingCode]: Before codesnippet will force http pages to also send all beacons using https.');
  221. $this->assertRaw('ga("create", "UA-123456-3", {"name": "newTracker"});', '[testGoogleAnalyticsTrackingCode]: After codesnippet with "newTracker" tracker has been found.');
  222. }
  223. }
  224. class GoogleAnalyticsCustomDimensionsAndMetricsTest extends DrupalWebTestCase {
  225. public static function getInfo() {
  226. return array(
  227. 'name' => 'Google Analytics custom dimensions and metrics tests',
  228. 'description' => 'Test custom dimensions and metrics functionality of Google Analytics module.',
  229. 'group' => 'Google Analytics',
  230. 'dependencies' => array('token'),
  231. );
  232. }
  233. function setUp() {
  234. parent::setUp('googleanalytics', 'token');
  235. $permissions = array(
  236. 'access administration pages',
  237. 'administer google analytics',
  238. );
  239. // User to set up google_analytics.
  240. $this->admin_user = $this->drupalCreateUser($permissions);
  241. }
  242. function testGoogleAnalyticsCustomDimensions() {
  243. $ua_code = 'UA-123456-3';
  244. variable_set('googleanalytics_account', $ua_code);
  245. // Basic test if the feature works.
  246. $googleanalytics_custom_dimension = array(
  247. 1 => array(
  248. 'index' => 1,
  249. 'value' => 'Bar 1',
  250. ),
  251. 2 => array(
  252. 'index' => 2,
  253. 'value' => 'Bar 2',
  254. ),
  255. 3 => array(
  256. 'index' => 3,
  257. 'value' => 'Bar 3',
  258. ),
  259. 4 => array(
  260. 'index' => 4,
  261. 'value' => 'Bar 4',
  262. ),
  263. 5 => array(
  264. 'index' => 5,
  265. 'value' => 'Bar 5',
  266. ),
  267. );
  268. variable_set('googleanalytics_custom_dimension', $googleanalytics_custom_dimension);
  269. $this->drupalGet('');
  270. foreach ($googleanalytics_custom_dimension as $dimension) {
  271. $this->assertRaw('ga("set", ' . drupal_json_encode('dimension' . $dimension['index']) . ', ' . drupal_json_encode($dimension['value']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Dimension #' . $dimension['index'] . ' is shown.');
  272. }
  273. // Test whether tokens are replaced in custom dimension values.
  274. $site_slogan = $this->randomName(16);
  275. variable_set('site_slogan', $site_slogan);
  276. $googleanalytics_custom_dimension = array(
  277. 1 => array(
  278. 'index' => 1,
  279. 'value' => 'Value: [site:slogan]',
  280. ),
  281. 2 => array(
  282. 'index' => 2,
  283. 'value' => $this->randomName(16),
  284. ),
  285. 3 => array(
  286. 'index' => 3,
  287. 'value' => '',
  288. ),
  289. // #2300701: Custom dimensions and custom metrics not outputed on zero value.
  290. 4 => array(
  291. 'index' => 4,
  292. 'value' => '0',
  293. ),
  294. );
  295. variable_set('googleanalytics_custom_dimension', $googleanalytics_custom_dimension);
  296. $this->verbose('<pre>' . print_r($googleanalytics_custom_dimension, TRUE) . '</pre>');
  297. $this->drupalGet('');
  298. $this->assertRaw('ga("set", ' . drupal_json_encode('dimension1') . ', ' . drupal_json_encode("Value: $site_slogan") . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Tokens have been replaced in dimension value.');
  299. $this->assertRaw('ga("set", ' . drupal_json_encode('dimension2') . ', ' . drupal_json_encode($googleanalytics_custom_dimension['2']['value']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Random value is shown.');
  300. $this->assertNoRaw('ga("set", ' . drupal_json_encode('dimension3') . ', ' . drupal_json_encode('') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Empty value is not shown.');
  301. $this->assertRaw('ga("set", ' . drupal_json_encode('dimension4') . ', ' . drupal_json_encode('0') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Value 0 is shown.');
  302. }
  303. function testGoogleAnalyticsCustomMetrics() {
  304. $ua_code = 'UA-123456-3';
  305. variable_set('googleanalytics_account', $ua_code);
  306. // Basic test if the feature works.
  307. $googleanalytics_custom_metric = array(
  308. 1 => array(
  309. 'index' => 1,
  310. 'value' => '6',
  311. 'value_expected' => 6,
  312. ),
  313. 2 => array(
  314. 'index' => 2,
  315. 'value' => '8000',
  316. 'value_expected' => 8000,
  317. ),
  318. 3 => array(
  319. 'index' => 3,
  320. 'value' => '7.8654',
  321. 'value_expected' => 7.8654,
  322. ),
  323. 4 => array(
  324. 'index' => 4,
  325. 'value' => '1123.4',
  326. 'value_expected' => 1123.4,
  327. ),
  328. 5 => array(
  329. 'index' => 5,
  330. 'value' => '5,67',
  331. 'value_expected' => 5,
  332. ),
  333. );
  334. variable_set('googleanalytics_custom_metric', $googleanalytics_custom_metric);
  335. $this->drupalGet('');
  336. foreach ($googleanalytics_custom_metric as $metric) {
  337. $this->assertRaw('ga("set", ' . drupal_json_encode('metric' . $metric['index']) . ', ' . drupal_json_encode($metric['value_expected']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Metric #' . $metric['index'] . ' is shown.');
  338. }
  339. // Test whether tokens are replaced in custom metric values.
  340. $googleanalytics_custom_metric = array(
  341. 1 => array(
  342. 'index' => 1,
  343. 'value' => '[current-user:roles:count]',
  344. ),
  345. 2 => array(
  346. 'index' => 2,
  347. 'value' => mt_rand(),
  348. ),
  349. 3 => array(
  350. 'index' => 3,
  351. 'value' => '',
  352. ),
  353. // #2300701: Custom dimensions and custom metrics not outputed on zero value.
  354. 4 => array(
  355. 'index' => 4,
  356. 'value' => '0',
  357. ),
  358. );
  359. variable_set('googleanalytics_custom_metric', $googleanalytics_custom_metric);
  360. $this->verbose('<pre>' . print_r($googleanalytics_custom_metric, TRUE) . '</pre>');
  361. $this->drupalGet('');
  362. $this->assertRaw('ga("set", ' . drupal_json_encode('metric1') . ', ', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Tokens have been replaced in metric value.');
  363. $this->assertRaw('ga("set", ' . drupal_json_encode('metric2') . ', ' . drupal_json_encode($googleanalytics_custom_metric['2']['value']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Random value is shown.');
  364. $this->assertNoRaw('ga("set", ' . drupal_json_encode('metric3') . ', ' . drupal_json_encode('') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Empty value is not shown.');
  365. $this->assertRaw('ga("set", ' . drupal_json_encode('metric4') . ', ' . drupal_json_encode(0) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Value 0 is shown.');
  366. }
  367. }
  368. class GoogleAnalyticsStatusMessagesTest extends DrupalWebTestCase {
  369. public static function getInfo() {
  370. return array(
  371. 'name' => 'Google Analytics status messages tests',
  372. 'description' => 'Test status messages functionality of Google Analytics module.',
  373. 'group' => 'Google Analytics',
  374. );
  375. }
  376. function setUp() {
  377. parent::setUp('googleanalytics');
  378. $permissions = array(
  379. 'access administration pages',
  380. 'administer google analytics',
  381. );
  382. // User to set up google_analytics.
  383. $this->admin_user = $this->drupalCreateUser($permissions);
  384. }
  385. function testGoogleAnalyticsStatusMessages() {
  386. $ua_code = 'UA-123456-4';
  387. variable_set('googleanalytics_account', $ua_code);
  388. // Enable logging of errors only.
  389. variable_set('googleanalytics_trackmessages', array('error' => 'error'));
  390. $this->drupalPost('user/login', array(), t('Log in'));
  391. $this->assertRaw('ga("send", "event", "Messages", "Error message", "Username field is required.");', '[testGoogleAnalyticsStatusMessages]: Event message "Username field is required." is shown.');
  392. $this->assertRaw('ga("send", "event", "Messages", "Error message", "Password field is required.");', '[testGoogleAnalyticsStatusMessages]: Event message "Password field is required." is shown.');
  393. // @todo: investigate why drupal_set_message() fails.
  394. //drupal_set_message('Example status message.', 'status');
  395. //drupal_set_message('Example warning message.', 'warning');
  396. //drupal_set_message('Example error message.', 'error');
  397. //drupal_set_message('Example error <em>message</em> with html tags and <a href="http://example.com/">link</a>.', 'error');
  398. //$this->drupalGet('');
  399. //$this->assertNoRaw('ga("send", "event", "Messages", "Status message", "Example status message.");', '[testGoogleAnalyticsStatusMessages]: Example status message is not enabled for tracking.');
  400. //$this->assertNoRaw('ga("send", "event", "Messages", "Warning message", "Example warning message.");', '[testGoogleAnalyticsStatusMessages]: Example warning message is not enabled for tracking.');
  401. //$this->assertRaw('ga("send", "event", "Messages", "Error message", "Example error message.");', '[testGoogleAnalyticsStatusMessages]: Example error message is shown.');
  402. //$this->assertRaw('ga("send", "event", "Messages", "Error message", "Example error message with html tags and link.");', '[testGoogleAnalyticsStatusMessages]: HTML has been stripped successful from Example error message with html tags and link.');
  403. }
  404. }
  405. class GoogleAnalyticsRolesTest extends DrupalWebTestCase {
  406. public static function getInfo() {
  407. return array(
  408. 'name' => 'Google Analytics role tests',
  409. 'description' => 'Test roles functionality of Google Analytics module.',
  410. 'group' => 'Google Analytics',
  411. );
  412. }
  413. function setUp() {
  414. parent::setUp('googleanalytics');
  415. $permissions = array(
  416. 'access administration pages',
  417. 'administer google analytics',
  418. );
  419. // User to set up google_analytics.
  420. $this->admin_user = $this->drupalCreateUser($permissions);
  421. }
  422. function testGoogleAnalyticsRolesTracking() {
  423. $ua_code = 'UA-123456-4';
  424. variable_set('googleanalytics_account', $ua_code);
  425. // Test if the default settings are working as expected.
  426. // Add to the selected roles only.
  427. variable_set('googleanalytics_visibility_roles', 0);
  428. // Enable tracking for all users.
  429. variable_set('googleanalytics_roles', array());
  430. // Check tracking code visibility.
  431. $this->drupalGet('');
  432. $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed for anonymous users on frontpage with default settings.');
  433. $this->drupalGet('admin');
  434. $this->assertRaw('/403.html', '[testGoogleAnalyticsRoleVisibility]: 403 Forbidden tracking code is displayed for anonymous users in admin section with default settings.');
  435. $this->drupalLogin($this->admin_user);
  436. $this->drupalGet('');
  437. $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed for authenticated users on frontpage with default settings.');
  438. $this->drupalGet('admin');
  439. $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed for authenticated users in admin section with default settings.');
  440. // Test if the non-default settings are working as expected.
  441. // Enable tracking only for authenticated users.
  442. variable_set('googleanalytics_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
  443. $this->drupalGet('');
  444. $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed for authenticated users only on frontpage.');
  445. $this->drupalLogout();
  446. $this->drupalGet('');
  447. $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed for anonymous users on frontpage.');
  448. // Add to every role except the selected ones.
  449. variable_set('googleanalytics_visibility_roles', 1);
  450. // Enable tracking for all users.
  451. variable_set('googleanalytics_roles', array());
  452. // Check tracking code visibility.
  453. $this->drupalGet('');
  454. $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is added to every role and displayed for anonymous users.');
  455. $this->drupalGet('admin');
  456. $this->assertRaw('/403.html', '[testGoogleAnalyticsRoleVisibility]: 403 Forbidden tracking code is shown for anonymous users if every role except the selected ones is selected.');
  457. $this->drupalLogin($this->admin_user);
  458. $this->drupalGet('');
  459. $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is added to every role and displayed on frontpage for authenticated users.');
  460. $this->drupalGet('admin');
  461. $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is added to every role and NOT displayed in admin section for authenticated users.');
  462. // Disable tracking for authenticated users.
  463. variable_set('googleanalytics_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
  464. $this->drupalGet('');
  465. $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed on frontpage for excluded authenticated users.');
  466. $this->drupalGet('admin');
  467. $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed in admin section for excluded authenticated users.');
  468. $this->drupalLogout();
  469. $this->drupalGet('');
  470. $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed on frontpage for included anonymous users.');
  471. }
  472. }
  473. class GoogleAnalyticsSearchTest extends DrupalWebTestCase {
  474. public static function getInfo() {
  475. return array(
  476. 'name' => 'Google Analytics search tests',
  477. 'description' => 'Test search functionality of Google Analytics module.',
  478. 'group' => 'Google Analytics',
  479. );
  480. }
  481. function setUp() {
  482. parent::setUp('googleanalytics', 'search', 'node');
  483. $permissions = array(
  484. 'access administration pages',
  485. 'administer google analytics',
  486. 'search content',
  487. 'create page content',
  488. 'edit own page content',
  489. );
  490. // User to set up google_analytics.
  491. $this->admin_user = $this->drupalCreateUser($permissions);
  492. $this->drupalLogin($this->admin_user);
  493. }
  494. function testGoogleAnalyticsSearchTracking() {
  495. $ua_code = 'UA-123456-1';
  496. variable_set('googleanalytics_account', $ua_code);
  497. // Check tracking code visibility.
  498. $this->drupalGet('');
  499. $this->assertRaw($ua_code, '[testGoogleAnalyticsSearch]: Tracking code is displayed for authenticated users.');
  500. $this->drupalGet('search/node');
  501. $this->assertNoRaw('ga("set", "page",', '[testGoogleAnalyticsSearch]: Custom url not set.');
  502. // Enable site search support.
  503. variable_set('googleanalytics_site_search', 1);
  504. // Search for random string.
  505. $search = array();
  506. $search['keys'] = $this->randomName(8);
  507. // Create a node to search for.
  508. $langcode = LANGUAGE_NONE;
  509. $edit = array();
  510. $edit['title'] = 'This is a test title';
  511. $edit["body[$langcode][0][value]"] = 'This test content contains ' . $search['keys'] . ' string.';
  512. // Fire a search, it's expected to get 0 results.
  513. $this->drupalPost('search/node', $search, t('Search'));
  514. $this->assertRaw('ga("set", "page", (window.googleanalytics_search_results) ?', '[testGoogleAnalyticsSearch]: Search results tracker is displayed.');
  515. $this->assertRaw('window.googleanalytics_search_results = 0;', '[testGoogleAnalyticsSearch]: Search yielded no results.');
  516. // Save the node.
  517. $this->drupalPost('node/add/page', $edit, t('Save'));
  518. $this->assertText(t('@type @title has been created.', array('@type' => 'Basic page', '@title' => $edit['title'])), 'Node was created.');
  519. // Index the node or it cannot found.
  520. $this->cronRun();
  521. $this->drupalPost('search/node', $search, t('Search'));
  522. $this->assertRaw('ga("set", "page", (window.googleanalytics_search_results) ?', '[testGoogleAnalyticsSearch]: Search results tracker is displayed.');
  523. $this->assertRaw('window.googleanalytics_search_results = 1;', '[testGoogleAnalyticsSearch]: One search result found.');
  524. $this->drupalPost('node/add/page', $edit, t('Save'));
  525. $this->assertText(t('@type @title has been created.', array('@type' => 'Basic page', '@title' => $edit['title'])), 'Node was created.');
  526. // Index the node or it cannot found.
  527. $this->cronRun();
  528. $this->drupalPost('search/node', $search, t('Search'));
  529. $this->assertRaw('ga("set", "page", (window.googleanalytics_search_results) ?', '[testGoogleAnalyticsSearch]: Search results tracker is displayed.');
  530. $this->assertRaw('window.googleanalytics_search_results = 2;', '[testGoogleAnalyticsSearch]: Two search results found.');
  531. }
  532. }
  533. class GoogleAnalyticsPhpFilterTest extends DrupalWebTestCase {
  534. public static function getInfo() {
  535. return array(
  536. 'name' => 'Google Analytics php filter tests',
  537. 'description' => 'Test php filter functionality of Google Analytics module.',
  538. 'group' => 'Google Analytics',
  539. );
  540. }
  541. function setUp() {
  542. parent::setUp('googleanalytics', 'php');
  543. // Administrator with all permissions.
  544. $permissions_admin_user = array(
  545. 'access administration pages',
  546. 'administer google analytics',
  547. 'use PHP for tracking visibility',
  548. );
  549. $this->admin_user = $this->drupalCreateUser($permissions_admin_user);
  550. // Administrator who cannot configure tracking visibility with PHP.
  551. $permissions_delegated_admin_user = array(
  552. 'access administration pages',
  553. 'administer google analytics',
  554. );
  555. $this->delegated_admin_user = $this->drupalCreateUser($permissions_delegated_admin_user);
  556. }
  557. function testGoogleAnalyticsPhpFilter() {
  558. $ua_code = 'UA-123456-1';
  559. $this->drupalLogin($this->admin_user);
  560. $edit = array();
  561. $edit['googleanalytics_account'] = $ua_code;
  562. $edit['googleanalytics_visibility_pages'] = 2;
  563. $edit['googleanalytics_pages'] = '<?php return 0; ?>';
  564. $this->drupalPost('admin/config/system/googleanalytics', $edit, t('Save configuration'));
  565. // Compare saved setting with posted setting.
  566. $googleanalytics_pages = variable_get('googleanalytics_pages', $this->randomName(8));
  567. $this->assertEqual('<?php return 0; ?>', $googleanalytics_pages, '[testGoogleAnalyticsPhpFilter]: PHP code snippet is intact.');
  568. // Check tracking code visibility.
  569. variable_set('googleanalytics_pages', '<?php return TRUE; ?>');
  570. $this->drupalGet('');
  571. $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPhpFilter]: Tracking is displayed on frontpage page.');
  572. $this->drupalGet('admin');
  573. $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPhpFilter]: Tracking is displayed on admin page.');
  574. variable_set('googleanalytics_pages', '<?php return FALSE; ?>');
  575. $this->drupalGet('');
  576. $this->assertNoRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPhpFilter]: Tracking is not displayed on frontpage page.');
  577. // Test administration form.
  578. variable_set('googleanalytics_pages', '<?php return TRUE; ?>');
  579. $this->drupalGet('admin/config/system/googleanalytics');
  580. $this->assertRaw(t('Pages on which this PHP code returns <code>TRUE</code> (experts only)'), '[testGoogleAnalyticsPhpFilter]: Permission to administer PHP for tracking visibility.');
  581. $this->assertRaw(check_plain('<?php return TRUE; ?>'), '[testGoogleAnalyticsPhpFilter]: PHP code snippted is displayed.');
  582. // Login the delegated user and check if fields are visible.
  583. $this->drupalLogin($this->delegated_admin_user);
  584. $this->drupalGet('admin/config/system/googleanalytics');
  585. $this->assertNoRaw(t('Pages on which this PHP code returns <code>TRUE</code> (experts only)'), '[testGoogleAnalyticsPhpFilter]: No permission to administer PHP for tracking visibility.');
  586. $this->assertNoRaw(check_plain('<?php return TRUE; ?>'), '[testGoogleAnalyticsPhpFilter]: No permission to view PHP code snippted.');
  587. // Set a different value and verify that this is still the same after the post.
  588. variable_set('googleanalytics_pages', '<?php return 0; ?>');
  589. $edit = array();
  590. $edit['googleanalytics_account'] = $ua_code;
  591. $this->drupalPost('admin/config/system/googleanalytics', $edit, t('Save configuration'));
  592. // Compare saved setting with posted setting.
  593. $googleanalytics_visibility_pages = variable_get('googleanalytics_visibility_pages', 0);
  594. $googleanalytics_pages = variable_get('googleanalytics_pages', $this->randomName(8));
  595. $this->assertEqual(2, $googleanalytics_visibility_pages, '[testGoogleAnalyticsPhpFilter]: Pages on which this PHP code returns TRUE is selected.');
  596. $this->assertEqual('<?php return 0; ?>', $googleanalytics_pages, '[testGoogleAnalyticsPhpFilter]: PHP code snippet is intact.');
  597. }
  598. }