googleanalytics.test 39 KB

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