baidu_tongji-8.x-1.x-dev/baidu_analytics.test
baidu_analytics.test
<?php /** * @file * Test file for the Baidu Analytics module. */ /** * Basic tests for the Baidu Analytics module. */ class BaiduAnalyticsBasicTest extends BaiduAnalyticsTestCase { /** * Implements DrupalWebTestCase::getInfo(). */ public static function getInfo() { return array( 'name' => 'Baidu Analytics basic tests', 'description' => 'Test Page Visibility, 403/404 and DNT configuration settings.<br/>Test Baidu Analytics Tracker Code (BATC) generation and page inclusion.', 'group' => 'Baidu Analytics', ); } /** * Test Page Visibility, 403/404 and DNT configuration settings. */ public function testBaiduAnalyticsPageVisibility() { // Create and authenticate test user with enough permissions. $permissions = array('access administration pages'); $this->privilegedUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->privilegedUser); // Show tracking on "every page except the listed pages". \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_visibility_pages', 0)->save(); // Disable tracking one "admin*" pages only. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_pages', "admin\nadmin/*")->save(); // Enable tracking only for authenticated users only. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_roles', array(\Drupal\Core\Session\AccountInterface::AUTHENTICATED_RID => \Drupal\Core\Session\AccountInterface::AUTHENTICATED_RID))->save(); // Check tracking code visibility. $this->drupalGet(''); $this->assertRaw($this->baCode, '[testBaiduAnalyticsPageVisibility]: Tracking code is displayed for authenticated users.'); // Test whether tracking code is not included on pages to omit. $this->drupalGet('admin'); $this->assertNoRaw($this->baCode, '[testBaiduAnalyticsPageVisibility]: Tracking code is not displayed on admin page.'); $this->drupalGet('admin/config/system'); // Checking for tracking code URI here, as baCode is displayed in the form. $this->assertNoRaw(BAIDU_ANALYTICS_ASYNC_LIBRARY_URL . "?{$this->baCode}", '[testBaiduAnalyticsPageVisibility]: Tracking code is not displayed on admin subpage.'); // Test whether tracking code display is properly flipped. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_visibility_pages', 1)->save(); $this->drupalGet('admin'); $this->assertRaw($this->baCode, '[testBaiduAnalyticsPageVisibility]: Tracking code is displayed on admin page.'); $this->drupalGet('admin/config/system/baidu_analytics'); // Checking for tracking code URI here, as baCode is displayed in the form. $this->assertRaw(BAIDU_ANALYTICS_ASYNC_LIBRARY_URL . "?{$this->baCode}", '[testBaiduAnalyticsPageVisibility]: Tracking code is displayed on admin subpage.'); $this->drupalGet(''); $this->assertNoRaw($this->baCode, '[testBaiduAnalyticsPageVisibility]: Tracking code is NOT displayed on front page.'); // Test whether tracking code is not display for anonymous. $this->drupalLogout(); $this->drupalGet(''); $this->assertNoRaw($this->baCode, '[testBaiduAnalyticsPageVisibility]: Tracking code is NOT displayed for anonymous.'); // Switch back to every page except the listed pages. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_visibility_pages', 0)->save(); // Enable tracking code for all user roles. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_roles', array())->save(); // Test whether 403 forbidden tracking code is shown if user has no access. $this->drupalGet('admin'); $this->assertRaw('/403.html', '[testBaiduAnalyticsPageVisibility]: 403 Forbidden tracking code shown if user has no access.'); // Test whether 404 not found tracking code is shown on non-existent pages. $this->drupalGet($this->randomName(64)); $this->assertRaw('/404.html', '[testBaiduAnalyticsPageVisibility]: 404 Not Found tracking code shown on non-existent page.'); // DNT Tests: // Enable caching of pages for anonymous users. // @FIXME // // @FIXME // // This looks like another module's variable. You'll need to rewrite this call // // to ensure that it uses the correct configuration object. // variable_set('cache', TRUE); // Test whether DNT headers will fail to disable embedding of tracking code. $this->drupalGet('', array(), array('DNT: 1')); $this->assertRaw('_hmt.push(["_trackPageview"]);', '[testBaiduAnalyticsDNTVisibility]: DNT header send from client, but page caching is enabled and tracker cannot removed.'); // DNT works only with caching of pages for anonymous users disabled. // @FIXME // // @FIXME // // This looks like another module's variable. You'll need to rewrite this call // // to ensure that it uses the correct configuration object. // variable_set('cache', FALSE); $this->drupalGet(''); $this->assertRaw('_hmt.push(["_trackPageview"]);', '[testBaiduAnalyticsDNTVisibility]: Tracking is enabled without DNT header.'); // Test whether DNT header is able to remove the tracking code. $this->drupalGet('', array(), array('DNT: 1')); $this->assertNoRaw('_hmt.push(["_trackPageview"]);', '[testBaiduAnalyticsDNTVisibility]: DNT header received from client. Tracking has been disabled by browser.'); // Disable DNT feature and see if tracker is still embedded. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_privacy_donottrack', FALSE)->save(); $this->drupalGet('', array(), array('DNT: 1')); $this->assertRaw('_hmt.push(["_trackPageview"]);', '[testBaiduAnalyticsDNTVisibility]: DNT feature is disabled, DNT header from browser has been ignored.'); } /** * Test Baidu Analytics Tracker Code (BATC) generation and page inclusion. */ public function testBaiduAnalyticsTrackingCode() { // Show tracking code on every page except the listed pages. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_visibility_pages', 0)->save(); // Enable tracking code for all user roles. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_roles', array())->save(); /* Sample JS code as added to page: <script type="text/javascript" src= "/sites/all/modules/google_analytics/googleanalytics.js?w"></script> <script type="text/javascript"> var _hmt = _hmt || []; _hmt.push(['_setAccount', '0123456789abcdef0123456789abcdef']); _hmt.push(['_trackPageview']); // For the Asynchronous code type. (function() { var hm = document.createElement('script'); hm.src = '//hm.baidu.com/hm.js?0123456789abcdef0123456789abcdef'; hm.type = 'text/javascript'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(hm, s); })(); // For the Standard code type. document.write(unescape("%3Cscript src= 'http://hm.baidu.com/h.js?0123456789abcdef0123456789abcdef' type='text/javascript'%3E%3C/script%3E")); </script> */ // Test whether Asynchronous tracking code uses latest JS. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_cache', FALSE)->save(); $this->drupalGet(''); $this->assertRaw(BAIDU_ANALYTICS_ASYNC_LIBRARY_URL . "?{$this->baCode}", '[testBaiduAnalyticsTrackingCode]: Latest <em>Asynchronous</em> tracking code used.'); // Check default scope, should be in header. $this->assertTrue($this->xpath("//head/script[contains(.,'" . BAIDU_ANALYTICS_ASYNC_LIBRARY_URL . "?{$this->baCode}')]"), '[testBaiduAnalyticsTrackingCode]: Default scope for <em>Asynchronous</em> code is header.'); // Test whether Standard tracking code uses latest JS. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_code_type', 'standard')->save(); $this->drupalGet(''); $this->assertRaw(BAIDU_ANALYTICS_STANDARD_LIBRARY_URL . "?{$this->baCode}", '[testBaiduAnalyticsTrackingCode]: Latest <em>Standard</em> tracking code used.'); // Check default scope, should be the last HTML tag in footer. $this->assertTrue($this->xpath("//body/*[last()][self::script][contains(.,'" . BAIDU_ANALYTICS_STANDARD_LIBRARY_URL . "?{$this->baCode}')]"), '[testBaiduAnalyticsTrackingCode]: Default scope for <em>Standard</em> code is footer.'); // Change the scope to header and check again. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_js_scope', 'header')->save(); $this->drupalGet(''); $this->assertTrue($this->xpath("//head/script[contains(.,'" . BAIDU_ANALYTICS_STANDARD_LIBRARY_URL . "?{$this->baCode}')]"), '[testBaiduAnalyticsTrackingCode]: Overridden scope for <em>Standard</em> displays in header correctly.'); // Check for Asynchronous code in footer. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_js_scope', 'footer')->save(); \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_code_type', 'async')->save(); $this->drupalGet(''); $this->assertTrue($this->xpath("//body/*[last()][self::script][contains(.,'" . BAIDU_ANALYTICS_ASYNC_LIBRARY_URL . "?{$this->baCode}')]"), '[testBaiduAnalyticsTrackingCode]: Cached <em>Asynchronous</em> tracking code displays correctly in overridden footer scope.'); // Test whether the BEFORE and AFTER code is added to the tracker. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_codesnippet_before', '_setDetectFlash(false);')->save(); \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_codesnippet_after', '_hmt.push(["t2._setAccount", "0123456789abcdef0123456789abcde0"]);_hmt.push(["t2._trackPageview"]);')->save(); $this->drupalGet(''); $this->assertRaw('_setDetectFlash(false);', '[testBaiduAnalyticsTrackingCode]: Before codesnippet has been found with "Flash" detection disabled.'); $this->assertRaw('t2._setAccount', '[testBaiduAnalyticsTrackingCode]: After codesnippet with "t2" tracker has been found.'); } } /** * Test Baidu Analytics Custom Variables configuration. */ class BaiduAnalyticsCustomVariablesTest extends BaiduAnalyticsTestCase { /** * Implements DrupalWebTestCase::getInfo(). */ public static function getInfo() { return array( 'name' => 'Baidu Analytics Custom Variables tests', 'description' => 'Test Custom Variables configuration settings and ensure the expected Baidu Analytics JavaScript code is generated to allow tracking of <em>five</em> Custom Variables.<br/>Check variables do not display if they are wrongly configured.', 'group' => 'Baidu Analytics', 'dependencies' => array('token'), ); } /** * Enable modules and create user with specific permissions. */ public function setUp() { // Include the Token module for testing tokens replacements in variables. parent::setUp('token'); } /** * Ensure configured Custom Variables are included as expected in pages. */ public function testBaiduAnalyticsCustomVariables() { // Basic test if the feature works. $custom_vars = array( 'slots' => array( 1 => array( 'slot' => 1, 'name' => 'Foo 1', 'value' => 'Bar 1', 'scope' => 3, ), 2 => array( 'slot' => 2, 'name' => 'Foo 2', 'value' => 'Bar 2', 'scope' => 2, ), 3 => array( 'slot' => 3, 'name' => 'Foo 3', 'value' => 'Bar 3', 'scope' => 3, ), 4 => array( 'slot' => 4, 'name' => 'Foo 4', 'value' => 'Bar 4', 'scope' => 2, ), 5 => array( 'slot' => 5, 'name' => 'Foo 5', 'value' => 'Bar 5', 'scope' => 1, ), ), ); \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_custom_var', $custom_vars)->save(); $this->drupalGet(''); foreach ($custom_vars['slots'] as $slot) { $this->assertRaw("_hmt.push(['_setCustomVar', " . $slot['slot'] . ", \"" . $slot['name'] . "\", \"" . $slot['value'] . "\", " . $slot['scope'] . "]);", '[testBaiduAnalyticsCustomVariables]: _setCustomVar ' . $slot['slot'] . ' is shown.'); } // Test whether tokens are replaced in custom variable names. $site_slogan = $this->randomName(16); // @FIXME // // @FIXME // // This looks like another module's variable. You'll need to rewrite this call // // to ensure that it uses the correct configuration object. // variable_set('site_slogan', $site_slogan); $custom_vars = array( 'slots' => array( 1 => array( 'slot' => 1, 'name' => 'Name: [site:slogan]', 'value' => 'Value: [site:slogan]', 'scope' => 3, ), 2 => array( 'slot' => 2, 'name' => '', 'value' => $this->randomName(16), 'scope' => 1, ), 3 => array( 'slot' => 3, 'name' => $this->randomName(16), 'value' => '', 'scope' => 2, ), 4 => array( 'slot' => 4, 'name' => '', 'value' => '', 'scope' => 3, ), 5 => array( 'slot' => 5, 'name' => '', 'value' => '', 'scope' => 3, ), ), ); \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_custom_var', $custom_vars)->save(); $this->verbose('<pre>' . print_r($custom_vars, TRUE) . '</pre>'); $this->drupalGet(''); $this->assertRaw("_hmt.push(['_setCustomVar', 1, \"Name: $site_slogan\", \"Value: $site_slogan\", 3]", '[testBaiduAnalyticsCustomVariables]: Tokens have been replaced in custom variable.'); $this->assertNoRaw("_hmt.push(['_setCustomVar', 2,", '[testBaiduAnalyticsCustomVariables]: Value with empty name is not shown.'); $this->assertNoRaw("_hmt.push(['_setCustomVar', 3,", '[testBaiduAnalyticsCustomVariables]: Name with empty value is not shown.'); $this->assertNoRaw("_hmt.push(['_setCustomVar', 4,", '[testBaiduAnalyticsCustomVariables]: Empty name and value is not shown.'); $this->assertNoRaw("_hmt.push(['_setCustomVar', 5,", '[testBaiduAnalyticsCustomVariables]: Empty name and value is not shown.'); // Test Baidu Analytics Tokens replacements. $custom_vars['slots'][1]['name'] = 'User Roles: [current-user:baidu_analytics:role-names]'; $custom_vars['slots'][1]['value'] = 'Value: [current-user:baidu_analytics:role-names]'; $custom_vars['slots'][2]['name'] = 'User Role IDs: [current-user:baidu_analytics:role-ids]'; $custom_vars['slots'][2]['value'] = 'Value: [current-user:baidu_analytics:role-ids]'; $custom_vars['slots'][3]['name'] = 'Combined: [current-user:baidu_analytics:role-names]-[current-user:baidu_analytics:role-ids]'; $custom_vars['slots'][3]['value'] = 'Value: [current-user:baidu_analytics:role-names]-[current-user:baidu_analytics:role-ids]'; \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_custom_var', $custom_vars)->save(); $this->verbose('<pre>' . print_r($custom_vars, TRUE) . '</pre>'); // Create and authenticate test user with all permissions. $this->privilegedUser = $this->drupalCreateUser(); $this->drupalLogin($this->privilegedUser); // Get user's roles ids and names to be compare with replacements. $role_names = 'authenticated user'; $role_ids = 2; $this->drupalGet(''); $this->assertRaw("_hmt.push(['_setCustomVar', 1, \"User Roles: $role_names\", \"Value: $role_names\", 3]", format_string('[testBaiduAnalyticsCustomVariables]: Baidu Analytics <em>Role names</em> token has been replaced in custom variable: @role_names.', array('@role_names' => $role_names))); $this->assertRaw("_hmt.push(['_setCustomVar', 2, \"User Role IDs: $role_ids\", \"Value: $role_ids\", 1]", format_string('[testBaiduAnalyticsCustomVariables]: Baidu Analytics <em>Role IDs</em> token has been replaced in custom variable: @role_ids.', array('@role_ids' => $role_ids))); $this->assertRaw("_hmt.push(['_setCustomVar', 3, \"Combined: $role_names-$role_ids\", \"Value: $role_names-$role_ids\", 2]", format_string('[testBaiduAnalyticsCustomVariables]: Baidu Analytics <em>Role names</em> and <em>Role IDs</em> tokens have been replaced in custom variable: @combined.', array('@combined' => "$role_names-$role_ids"))); } } /** * Test Baidu Analytics tracking of status messages. */ class BaiduAnalyticsStatusMessagesTest extends BaiduAnalyticsTestCase { /** * Implements DrupalWebTestCase::getInfo(). */ public static function getInfo() { return array( 'name' => 'Baidu Analytics status messages tests', 'description' => 'Test status messages configuration settings and ensure the expected Baidu Analytics JavaScript code is generated to allow tracking of <em>status</em>, <em>warning</em> or <em>error</em> messages.', 'group' => 'Baidu Analytics', ); } /** * Enable modules and create user with specific permissions. */ public function setUp() { // Include the Baidu Analytics Test helper module to trigger messages. parent::setUp('baidu_analytics_test'); } /** * Ensure expected JavaScript code is generated for tracking status messages. */ public function testBaiduAnalyticsStatusMessages() { // Enable tracking of errors only. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_trackmessages', array('error' => 'error'))->save(); $status_heading = array( 'status' => t('Status message'), 'warning' => t('Warning message'), 'error' => t('Error message'), ); // Programmatically test all messages: status, error and warning. $this->drupalPost('user/login', array(), 'Log in'); // Check error messages from invalid form submission. $this->assertRaw('_hmt.push(["_trackEvent", "Messages", "Error message", ' . drupal_json_encode($status_heading['error'] . ': ' . t('Username field is required.')) . ']);', '[testBaiduAnalyticsStatusMessages]: _trackEvent "Username field is required." is shown.'); $this->assertRaw('_hmt.push(["_trackEvent", "Messages", "Error message", ' . drupal_json_encode($status_heading['error'] . ': ' . t('Password field is required.')) . ']);', '[testBaiduAnalyticsStatusMessages]: _trackEvent "Password field is required." is shown.'); // Check all the messages added by baidu_analytics_test. // Status/warning messages should not be found since they are not tracked. $this->assertNoRaw('_hmt.push(["_trackEvent", "Messages", "Status message", ' . drupal_json_encode(drupal_json_encode($status_heading['status']) . ': ' . t('Baidu Analytics Test status message.')) . ']);', '[testBaiduAnalyticsStatusMessages]: Baidu Analytics Test status message is <strong>not</strong> displayed because tracking of <em>status</em> messages is <strong>disabled</strong>.'); $this->assertNoRaw('_hmt.push(["_trackEvent", "Messages", "Warning message", ' . drupal_json_encode(drupal_json_encode($status_heading['warning']) . ': ' . t('Baidu Analytics Test warning message.')) . ']);', '[testBaiduAnalyticsStatusMessages]: Baidu Analytics Test warning message is <strong>not</strong> displayed because tracking of <em>warning</em> messages is <strong>disabled</strong>.'); // Check error messages should be tracked and the HTML stripped off. $this->assertRaw('_hmt.push(["_trackEvent", "Messages", "Error message", ' . drupal_json_encode($status_heading['error'] . ': ' . t('Baidu Analytics Test error message.')) . ']);', '[testBaiduAnalyticsStatusMessages]: Baidu Analytics Test error message is displayed.'); $this->assertRaw('_hmt.push(["_trackEvent", "Messages", "Error message", ' . drupal_json_encode($status_heading['error'] . ': ' . t('Baidu Analytics Test error message with html tags and link.')) . ']);', '[testBaiduAnalyticsStatusMessages]: HTML has been stripped off successfully from Baidu Analytics Test error message with html tags and link.'); // Enable all settings and test again for warning and status messages. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_trackmessages', array( 'error' => 'error', 'warning' => 'warning', 'status' => 'status', ))->save(); $this->drupalGet(''); $this->assertRaw('_hmt.push(["_trackEvent", "Messages", "Status message", ' . drupal_json_encode($status_heading['status'] . ': ' . t('Baidu Analytics Test status message.')) . ']);', '[testBaiduAnalyticsStatusMessages]: Baidu Analytics Test status message is displayed because tracking of <em>status</em> messages is <strong>enabled</strong>.'); $this->assertRaw('_hmt.push(["_trackEvent", "Messages", "Warning message", ' . drupal_json_encode($status_heading['warning'] . ': ' . t('Baidu Analytics Test warning message.')) . ']);', '[testBaiduAnalyticsStatusMessages]: Baidu Analytics Test warning message is displayed for tracking because tracking of <em>status</em> messages is <strong>enabled</strong>.'); } } /** * Test Baidu Analytics configuration for different Roles. */ class BaiduAnalyticsRolesTest extends BaiduAnalyticsTestCase { /** * Implements DrupalWebTestCase::getInfo(). */ public static function getInfo() { return array( 'name' => 'Baidu Analytics role tests', 'description' => 'Test roles functionality of Baidu Analytics module.', 'description' => 'Test roles configuration settings and ensure Baidu Analytics JavaScript code is displayed or hidden depending on user\'s roles.', 'group' => 'Baidu Analytics', ); } /** * Ensure JavaScript code is hidden depending on configured roles settings. */ public function testBaiduAnalyticsRolesTracking() { // Create and authenticate test user with all permissions. $permissions = array( 'access administration pages', 'administer baidu analytics', ); $this->privilegedUser = $this->drupalCreateUser($permissions); // Test if the default settings are working as expected. // Add to the selected roles only. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_visibility_roles', 0)->save(); // Enable tracking for all users. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_roles', array())->save(); // Check tracking code visibility. $this->drupalGet(''); $this->assertRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is displayed for anonymous users on frontpage with default settings.'); $this->drupalGet('admin'); $this->assertRaw('/403.html', '[testBaiduAnalyticsRoleVisibility]: 403 Forbidden tracking code is displayed for anonymous users in admin section with default settings.'); $this->drupalLogin($this->privilegedUser); $this->drupalGet(''); $this->assertRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is displayed for authenticated users on frontpage with default settings.'); $this->drupalGet('admin'); $this->assertNoRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is NOT displayed for authenticated users in admin section with default settings.'); // Test if the non-default settings are working as expected. // Enable tracking only for authenticated users. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_roles', array(\Drupal\Core\Session\AccountInterface::AUTHENTICATED_RID => \Drupal\Core\Session\AccountInterface::AUTHENTICATED_RID))->save(); $this->drupalGet(''); $this->assertRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is displayed for authenticated users only on frontpage.'); $this->drupalLogout(); $this->drupalGet(''); $this->assertNoRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is NOT displayed for anonymous users on frontpage.'); // Add to every role except the selected ones. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_visibility_roles', 1)->save(); // Enable tracking for all users. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_roles', array())->save(); // Check tracking code visibility. $this->drupalGet(''); $this->assertRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is added to every role and displayed for anonymous users.'); $this->drupalGet('admin'); $this->assertRaw('/403.html', '[testBaiduAnalyticsRoleVisibility]: 403 Forbidden tracking code is shown for anonymous users if every role except the selected ones is selected.'); $this->drupalLogin($this->privilegedUser); $this->drupalGet(''); $this->assertRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is added to every role and displayed on frontpage for authenticated users.'); $this->drupalGet('admin'); $this->assertNoRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is added to every role and NOT displayed in admin section for authenticated users.'); // Disable tracking for authenticated users. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_roles', array(\Drupal\Core\Session\AccountInterface::AUTHENTICATED_RID => \Drupal\Core\Session\AccountInterface::AUTHENTICATED_RID))->save(); $this->drupalGet(''); $this->assertNoRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is NOT displayed on frontpage for excluded authenticated users.'); $this->drupalGet('admin'); $this->assertNoRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is NOT displayed in admin section for excluded authenticated users.'); $this->drupalLogout(); $this->drupalGet(''); $this->assertRaw($this->baCode, '[testBaiduAnalyticsRoleVisibility]: Tracking code is displayed on frontpage for included anonymous users.'); } } /** * Test Baidu Analytics tracking of links: download, outbound or email links. */ class BaiduAnalyticsLinksTrackingTest extends BaiduAnalyticsTestCase { /** * Implements DrupalWebTestCase::getInfo(). */ public static function getInfo() { return array( 'name' => 'Baidu Analytics links tracking tests', 'description' => 'Test link tracking configuration settings and ensure the expected Baidu Analytics JavaScript code is generated to allow tracking for <em>download</em>, <em>outbound</em> or <em>email</em> links.', 'group' => 'Baidu Analytics', ); } /** * Ensure expected JavaScript code is generated for tracking links. */ public function testBaiduAnalyticsLinksTracking() { // Initially, all links tracking should be enabled. $this->drupalGet(''); // Ensure baidu_analytics.js is included. $this->assertTrue($this->xpath("//head/script[contains(@src,'baidu_analytics.js')]"), '[testBaiduAnalyticsLinksTracking]: Tracking of links is enabled: baidu_analytics.js is not included in the page.'); // Check download links tracking setting code is displayed correctly. $this->assertRaw('"trackDownload":true,"trackDownloadExtensions":"', '[testBaiduAnalyticsLinksTracking]: Download link tracking and files extensions settings code is correctly displayed.'); $this->assertRaw('"trackDownloadExtensions":"' . BAIDU_ANALYTICS_TRACKFILES_EXTENSIONS . '"', '[testBaiduAnalyticsLinksTracking]: Download extensions setting code is displayed correctly with <em>default list</em> of extensions.'); // Change the list of extensions to be tracked for download links. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_trackfiles_extensions', 'test1|test2')->save(); $this->drupalGet(''); $this->assertRaw('"trackDownloadExtensions":"test1|test2"', '[testBaiduAnalyticsLinksTracking]: Download extensions setting code is displayed correctly with <em>overridden list</em> of custom file extensions.'); // Disable tracking of download links. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_trackfiles', FALSE)->save(); $this->drupalGet(''); // Check download links tracking setting code is not displayed. $this->assertNoRaw('"trackDownload":true', '[testBaiduAnalyticsLinksTracking]: Download link tracking is disabled and settings code is not displayed.'); $this->assertNoRaw('"trackDownloadExtensions":', '[testBaiduAnalyticsLinksTracking]: Download extensions setting code is not displayed because tracking of downloads is disabled.'); // Check email links tracking setting code is displayed correctly. $this->assertRaw('"trackMailto":true', '[testBaiduAnalyticsLinksTracking]: Email links tracking setting code is correctly displayed.'); // Disable tracking of email links. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_trackmailto', FALSE)->save(); $this->drupalGet(''); // Check email links tracking setting code is not displayed. $this->assertNoRaw('"trackMailto":true', '[testBaiduAnalyticsLinksTracking]: Email links tracking setting code is not displayed because it is disabled.'); // Check outbound links tracking setting code is displayed correctly. $this->assertRaw('"trackOutbound":true', '[testBaiduAnalyticsLinksTracking]: Outbound links tracking setting code is correctly displayed.'); // Check download links tracking setting code is not displayed. $this->assertNoRaw('"trackDownloadExtensions":', '[testBaiduAnalyticsLinksTracking]: Download extensions setting code is not displayed because tracking of downloads is disabled.'); // Disable tracking of outbound links: Link tracking completely disabled. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_trackoutbound', FALSE)->save(); $this->drupalGet(''); // Check outbound links tracking setting code is not displayed. $this->assertNoRaw('"trackOutbound":true', '[testBaiduAnalyticsLinksTracking]: Outbound links tracking setting code is not displayed because outbound links tracking is disabled.'); // Check email links tracking setting code is displayed correctly. $this->assertNoRaw('"trackDownloadExtensions":', '[testBaiduAnalyticsLinksTracking]: Download extensions setting code is not displayed because tracking of downloads is disabled.'); // Ensure the baidu_analytics.js JavaScript file is not included. $this->drupalGet(''); $this->assertFalse($this->xpath("//head/script[contains(@src,'baidu_analytics.js')]"), '[testBaiduAnalyticsLinksTracking]: Tracking of links is disabled: baidu_analytics.js is not included in the page.'); } } /** * Test Baidu Analytics permissisons. */ class BaiduAnalyticsPermissionsTest extends BaiduAnalyticsTestCase { /** * Implements DrupalWebTestCase::getInfo(). */ public static function getInfo() { return array( 'name' => 'Baidu Analytics permissions tests', 'description' => 'Test the permissions added by the module: <em>administer baidu analytics</em>, <em>opt-in or out of tracking</em>, <em>use PHP for tracking visibility</em>.<br/>Test the <em>Web Property ID</em> field validation: required and validate exactly 32 lower case hexadecimal characters.<br/>Test <em>opt-in or out of tracking</em> setting for users in the edit account page.', 'group' => 'Baidu Analytics', ); } /** * Enable modules and create user with specific permissions. */ public function setUp() { // Include the PHP Filter module for this test case. parent::setUp('php'); // Create and authenticate test user with all permissions. $permissions = array( 'access administration pages', 'opt-in or out of tracking', 'administer baidu analytics', 'use PHP for tracking visibility', ); $this->privilegedUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->privilegedUser); } /** * Test Baidu Analytics permissions and settings form validation. */ public function testBaiduAnalyticsPemissions() { // Browse to the Baidu Analytics settings form page. $this->drupalGet('admin/config/system/baidu_analytics'); // Check if expected Web Property ID field is displayed. $this->assertFieldByName('baidu_analytics_account', '', '[testBaiduAnalyticsPemissions]: Settings page displayed and the <em>Web Property ID</em> field is displayed correctly.'); // Check if expected PHP Filter option is displayed. $this->assertRaw('Pages on which this PHP code returns <code>TRUE</code> (experts only)', '[testBaiduAnalyticsPemissions]: <em>PHP code visibility</em> setting is allowed and displayed correctly.'); // Check required Web Property ID field. $edit['baidu_analytics_account'] = ''; $this->drupalPost('admin/config/system/baidu_analytics', $edit, t('Save configuration')); $this->assertRaw(t('Web Property ID field is required.'), '[testBaiduAnalyticsPemissions]: <em>Web Property ID</em> field is required.'); // Check Web Property ID field validation. $edit['baidu_analytics_account'] = $this->randomName(2); $this->drupalPost('admin/config/system/baidu_analytics', $edit, t('Save configuration')); $this->assertRaw(t('A valid Baidu Analytics Web Property ID should have exactly 32 lower case hexadecimal characters (only allowed: 0 to 9 and a to f).'), format_string('[testBaiduAnalyticsPemissions]: Invalid <em>Web Property ID</em> field value, provided string is <strong>too short</strong>: @code.', array('@code' => $edit['baidu_analytics_account']))); // Test a string of 32 characters but with uppercase letters. $edit['baidu_analytics_account'] = 'F0123456789abcdef0123456789abcde'; $this->drupalPost('admin/config/system/baidu_analytics', $edit, t('Save configuration')); $this->assertRaw(t('A valid Baidu Analytics Web Property ID should have exactly 32 lower case hexadecimal characters (only allowed: 0 to 9 and a to f).'), format_string('[testBaiduAnalyticsPemissions]: Invalid <em>Web Property ID</em> containing <strong>uppercase</strong> characters: @code.', array('@code' => $edit['baidu_analytics_account']))); // Test: use PHP for tracking visibility. // Logout and login with another user with fewer permissions. $this->drupalLogout(); $permissions = array( 'access administration pages', 'opt-in or out of tracking', 'administer baidu analytics', ); $this->privilegedUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->privilegedUser); // Enough permissions to get to the settings form page. $this->drupalGet('admin/config/system/baidu_analytics'); // Check if expected Web Property ID field is displayed. $this->assertFieldByName('baidu_analytics_account', '', '[testBaiduAnalyticsPemissions]: Settings page displayed and theWeb Property ID field is displayed correctly.'); // No more permissions to use PHP code for page visibility settings. $this->assertNoRaw('Pages on which this PHP code returns <code>TRUE</code> (experts only)', '[testBaiduAnalyticsPemissions]: <em>PHP code visibility</em> setting is <strong>not</strong> allowed and <strong>not</strong> displayed. User does not have the permission: <em>use PHP for tracking visibility</em>.'); // Test: administer baidu analytics. // Logout and login with another user with fewer permissions. $this->drupalLogout(); $permissions = array( 'access administration pages', 'opt-in or out of tracking', ); $this->privilegedUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->privilegedUser); // Not enough permissions to get to the settings form page. $this->drupalGet('admin/config/system/baidu_analytics'); // Check if expected Web Property ID field is displayed. $this->assertNoFieldByName('baidu_analytics_account', '', '[testBaiduAnalyticsPemissions]: Settings page is <strong>not</strong> displayed and access to the page is denied. User does not have the permission: <em>administer baidu analytics</em>.'); $this->assertResponse(403, '[testBaiduAnalyticsPemissions]: Received a <strong>403</strong> response code for the Baidu Analytics settings form: <strong>Access denied</strong>.'); // Test: opt-in or out of tracking. // Tracking on by default, users with permission can opt out. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_custom', 1)->save(); $this->drupalGet("user/{$this->privilegedUser->uid}/edit"); $this->assertFieldByName('baidu_analytics[custom]', TRUE, '[testBaiduAnalyticsPemissions]: <em>Enable user tracking</em> (opt-in or out) setting is displayed correctly in user edit account page and <strong>enabled</strong> by default.'); // Check tracking off by default, users with permission can opt in. \Drupal::configFactory()->getEditable('baidu_analytics.settings')->set('baidu_analytics_custom', 2)->save(); $this->drupalGet("user/{$this->privilegedUser->uid}/edit"); $this->assertFieldByName('baidu_analytics[custom]', FALSE, '[testBaiduAnalyticsPemissions]: <em>Enable user tracking</em> (opt-in or out) setting is displayed correctly in user edit account page and <strong>disabled</strong> by default.'); // Logout and login with another user with fewer permissions. $this->drupalLogout(); $permissions = array( 'access administration pages', ); $this->privilegedUser = $this->drupalCreateUser($permissions); $this->drupalLogin($this->privilegedUser); // Not enough permissions to opt-in or out of tracking. $this->drupalGet("user/{$this->privilegedUser->uid}/edit"); $this->assertNoFieldByName('baidu_analytics[custom]', TRUE, '[testBaiduAnalyticsPemissions]: <em>Enable user tracking</em> (opt-in or out) setting is <strong>not</strong> displayed in user edit account page. User does not have the permission: <em>opt-in or out of tracking</em>.'); } }