googleanalytics.test 40 KB

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