diff options
author | diosmosis <benaka.moorthi@gmail.com> | 2013-03-11 04:58:21 +0400 |
---|---|---|
committer | diosmosis <benaka.moorthi@gmail.com> | 2013-03-11 04:58:21 +0400 |
commit | de5af594fdbb32744017fdd125dc3d957bc629b6 (patch) | |
tree | b7766a6cb5b17cc05d00a6fd92d395d61d30daa9 /tests | |
parent | 80ac6ac1666508cb0844dc1eac2faba303fa9f9e (diff) |
Refs #2908, refactored tests so database setup (adding sites, tracking visits) are separated from API tests. Put setup code into fixtures and reused code as much as possible.
Diffstat (limited to 'tests')
66 files changed, 3509 insertions, 4023 deletions
diff --git a/tests/PHPUnit/BaseFixture.php b/tests/PHPUnit/BaseFixture.php new file mode 100644 index 0000000000..9c7f202b27 --- /dev/null +++ b/tests/PHPUnit/BaseFixture.php @@ -0,0 +1,319 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Base type for all integration test fixtures. Integration test fixtures + * add visit and related data to the database before a test is run. Different + * tests can use the same fixtures. + * + * This class defines a set of helper methods for fixture types. The helper + * methods are public, but ideally they should only be used by fixture types. + * + * NOTE: YOU SHOULD NOT CREATE A NEW FIXTURE UNLESS THERE IS NO WAY TO MODIFY + * AN EXISTING FIXTURE TO HANDLE YOUR USE CASE. + * + * Related TODO: we should try and reduce the amount of existing fixtures by + * merging some together. + */ +abstract class Test_Piwik_BaseFixture extends PHPUnit_Framework_Assert +{ + /** Adds data to Piwik. Creates sites, tracks visits, imports log files, etc. */ + public abstract function setUp(); + + /** Does any clean up. Most of the time there will be no need to clean up. */ + public abstract function tearDown(); + + /** + * Creates a website, then sets its creation date to a day earlier than specified dateTime + * Useful to create a website now, but force data to be archived back in the past. + * + * @param string $dateTime eg '2010-01-01 12:34:56' + * @param int $ecommerce + * @param string $siteName + * + * @return int idSite of website created + */ + public static function createWebsite( $dateTime, $ecommerce = 0, $siteName = 'Piwik test', $siteUrl = false, + $siteSearch = 1, $searchKeywordParameters = null, + $searchCategoryParameters = null ) + { + $idSite = Piwik_SitesManager_API::getInstance()->addSite( + $siteName, + $siteUrl === false ? "http://piwik.net/" : $siteUrl, + $ecommerce, + $siteSearch , $searchKeywordParameters, $searchCategoryParameters, + $ips = null, + $excludedQueryParameters = null, + $timezone = null, + $currency = null + ); + + // Manually set the website creation date to a day earlier than the earliest day we record stats for + Zend_Registry::get('db')->update(Piwik_Common::prefixTable("site"), + array('ts_created' => Piwik_Date::factory($dateTime)->subDay(1)->getDatetime()), + "idsite = $idSite" + ); + + // Clear the memory Website cache + Piwik_Site::clearCache(); + + return $idSite; + } + + /** + * Returns URL to Piwik root. + * + * @return string + */ + public static function getRootUrl() + { + $piwikUrl = Piwik_Url::getCurrentUrlWithoutFileName(); + + $pathBeforeRoot = 'tests'; + // Running from a plugin + if(strpos($piwikUrl, 'plugins/') !== false) + { + $pathBeforeRoot = 'plugins'; + } + + $testsInPath = strpos($piwikUrl, $pathBeforeRoot.'/'); + if($testsInPath !== false) { + $piwikUrl = substr($piwikUrl, 0, $testsInPath); + } + return $piwikUrl; + } + + /** + * Returns URL to the proxy script, used to ensure piwik.php + * uses the test environment, and allows variable overwriting + * + * @return string + */ + public static function getTrackerUrl() + { + return self::getRootUrl().'tests/PHPUnit/proxy/piwik.php'; + } + + /** + * Returns a PiwikTracker object that you can then use to track pages or goals. + * + * @param $idSite + * @param $dateTime + * @param boolean $defaultInit If set to true, the tracker object will have default IP, user agent, time, resolution, etc. + * + * @return PiwikTracker + */ + public static function getTracker($idSite, $dateTime, $defaultInit = true, $useLocal = false ) + { + if ($useLocal) + { + require_once PIWIK_INCLUDE_PATH . '/tests/LocalTracker.php'; + $t = new Piwik_LocalTracker($idSite, self::getTrackerUrl()); + } + else + { + $t = new PiwikTracker( $idSite, self::getTrackerUrl()); + } + $t->setForceVisitDateTime($dateTime); + + if($defaultInit) + { + $t->setIp('156.5.3.2'); + + // Optional tracking + $t->setUserAgent( "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)"); + $t->setBrowserLanguage('fr'); + $t->setLocalTime( '12:34:06' ); + $t->setResolution( 1024, 768 ); + $t->setBrowserHasCookies(true); + $t->setPlugins($flash = true, $java = true, $director = false); + } + return $t; + } + + /** + * Checks that the response is a GIF image as expected. + * Will fail the test if the response is not the expected GIF + * + * @param $response + */ + public static function checkResponse($response) + { + $trans_gif_64 = "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; + $expectedResponse = base64_decode($trans_gif_64); + self::assertEquals($expectedResponse, $response, "Expected GIF beacon, got: <br/>\n" + . var_export($response, true) + . "\n If you are stuck, you can enable \$GLOBALS['PIWIK_TRACKER_DEBUG']=true; in piwik.php to get more debug info." + . base64_encode($response) + ); + } + + public static function makeLocation( $city, $region, $country, $lat = null, $long = null ) + { + return array(Piwik_UserCountry_LocationProvider::CITY_NAME_KEY => $city, + Piwik_UserCountry_LocationProvider::REGION_CODE_KEY => $region, + Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY => $country, + Piwik_UserCountry_LocationProvider::LATITUDE_KEY => $lat, + Piwik_UserCountry_LocationProvider::LONGITUDE_KEY => $long); + } + + /** + * Returns the super user token auth that can be used in tests. Can be used to + * do bulk tracking. + * + * @return string + */ + public static function getTokenAuth() + { + return Piwik_UsersManager_API::getInstance()->getTokenAuth( + Piwik_Config::getInstance()->superuser['login'], + Piwik_Config::getInstance()->superuser['password'] + ); + } + + /** + * Create one MAIL and two MOBILE scheduled reports + * + * Reports sent by mail can contain PNG graphs when the user specifies it. + * Depending on the system under test, generated images differ slightly. + * Because of this discrepancy, PNG graphs are only tested if the system under test + * has the characteristics described in 'canImagesBeIncludedInScheduledReports' + * + * @see canImagesBeIncludedInScheduledReports + * @param int $idSite id of website created + */ + public static function setUpScheduledReports($idSite) + { + // fake access is needed so API methods can call Piwik::getCurrentUserLogin(), e.g: 'PDFReports.addReport' + $pseudoMockAccess = new FakeAccess; + FakeAccess::$superUser = true; + Zend_Registry::set('access', $pseudoMockAccess); + + // retrieve available reports + $availableReportMetadata = Piwik_PDFReports_API::getReportMetadata($idSite, Piwik_PDFReports::EMAIL_TYPE); + + $availableReportIds = array(); + foreach($availableReportMetadata as $reportMetadata) + { + $availableReportIds[] = $reportMetadata['uniqueId']; + } + + //@review should we also test evolution graphs? + // set-up mail report + Piwik_PDFReports_API::getInstance()->addReport( + $idSite, + 'Mail Test report', + 'day', // overridden in getApiForTestingScheduledReports() + 0, + Piwik_PDFReports::EMAIL_TYPE, + Piwik_ReportRenderer::HTML_FORMAT, // overridden in getApiForTestingScheduledReports() + $availableReportIds, + array("displayFormat" => Piwik_PDFReports::DISPLAY_FORMAT_TABLES_ONLY) + ); + + // set-up sms report for one website + Piwik_PDFReports_API::getInstance()->addReport( + $idSite, + 'SMS Test report, one website', + 'day', // overridden in getApiForTestingScheduledReports() + 0, + Piwik_MobileMessaging::MOBILE_TYPE, + Piwik_MobileMessaging::SMS_FORMAT, + array("MultiSites_getOne"), + array("phoneNumbers"=>array()) + ); + + // set-up sms report for all websites + Piwik_PDFReports_API::getInstance()->addReport( + $idSite, + 'SMS Test report, all websites', + 'day', // overridden in getApiForTestingScheduledReports() + 0, + Piwik_MobileMessaging::MOBILE_TYPE, + Piwik_MobileMessaging::SMS_FORMAT, + array("MultiSites_getAll"), + array("phoneNumbers"=>array()) + ); + + if (self::canImagesBeIncludedInScheduledReports()) + { + // set-up mail report with images + Piwik_PDFReports_API::getInstance()->addReport( + $idSite, + 'Mail Test report', + 'day', // overridden in getApiForTestingScheduledReports() + 0, + Piwik_PDFReports::EMAIL_TYPE, + Piwik_ReportRenderer::HTML_FORMAT, // overridden in getApiForTestingScheduledReports() + $availableReportIds, + array("displayFormat" => Piwik_PDFReports::DISPLAY_FORMAT_TABLES_AND_GRAPHS) + ); + } + } + + /** + * Return true if system under test has the following characteristics : + * - php_uname() contains 'precise32' or 'ubuntu' + * - phpversion() contains '5.3.10' + * - 'GD Version' equals '2.0' + */ + public static function canImagesBeIncludedInScheduledReports() + { + $gdInfo = gd_info(); + return + (stristr(php_uname(), 'precise32') || stristr(php_uname(), 'ubuntu')) && + stristr(phpversion(), '5.3.10') && + $gdInfo['GD Version'] == '2.0'; + } + + public static $geoIpDbUrl = 'http://piwik-team.s3.amazonaws.com/GeoIP.dat.gz'; + public static $geoLiteCityDbUrl = 'http://piwik-team.s3.amazonaws.com/GeoLiteCity.dat.gz'; + + public static function downloadGeoIpDbs() + { + $geoIpOutputDir = PIWIK_INCLUDE_PATH.'/tests/lib/geoip-files'; + self::downloadAndUnzip(self::$geoIpDbUrl, $geoIpOutputDir, 'GeoIP.dat'); + self::downloadAndUnzip(self::$geoLiteCityDbUrl, $geoIpOutputDir, 'GeoIPCity.dat'); + } + + public static function downloadAndUnzip( $url, $outputDir, $filename ) + { + $bufferSize = 1024 * 1024; + + if (!is_dir($outputDir)) + { + mkdir($outputDir); + } + + $deflatedOut = $outputDir.'/'.$filename; + $outfileName = $deflatedOut.'.gz'; + + if (file_exists($deflatedOut)) + { + return; + } + + $dump = fopen($url, 'rb'); + $outfile = fopen($outfileName, 'wb'); + $bytesRead = 0; + while (!feof($dump)) + { + fwrite($outfile, fread($dump, $bufferSize), $bufferSize); + $bytesRead += $bufferSize; + } + fclose($dump); + fclose($outfile); + + // unzip the dump + exec("gunzip -c \"".$outfileName."\" > \"$deflatedOut\"", $output, $return); + if ($return !== 0) + { + throw new Exception("gunzip failed($return): ".implode("\n", $output)); + } + } +} diff --git a/tests/PHPUnit/Core/JsProxyTest.php b/tests/PHPUnit/Core/JsProxyTest.php index af875440dc..8bab94f010 100644 --- a/tests/PHPUnit/Core/JsProxyTest.php +++ b/tests/PHPUnit/Core/JsProxyTest.php @@ -44,6 +44,6 @@ class Test_Piwik_JsProxy extends PHPUnit_Framework_TestCase */ private function getStaticSrvUrl() { - return IntegrationTestCase::getRootUrl(); + return Test_Piwik_BaseFixture::getRootUrl(); } } diff --git a/tests/PHPUnit/Core/PluginsFunctions/WidgetsListTest.php b/tests/PHPUnit/Core/PluginsFunctions/WidgetsListTest.php index ee996e8e2c..803af0e111 100644 --- a/tests/PHPUnit/Core/PluginsFunctions/WidgetsListTest.php +++ b/tests/PHPUnit/Core/PluginsFunctions/WidgetsListTest.php @@ -20,7 +20,7 @@ class WidgetsListTest extends DatabaseTestCase FakeAccess::$superUser = true; Zend_Registry::set('access', $pseudoMockAccess); - IntegrationTestCase::createWebsite('2009-01-04 00:11:42'); + Test_Piwik_BaseFixture::createWebsite('2009-01-04 00:11:42'); $_GET['idSite'] = 1; @@ -66,7 +66,7 @@ class WidgetsListTest extends DatabaseTestCase FakeAccess::$superUser = true; Zend_Registry::set('access', $pseudoMockAccess); - IntegrationTestCase::createWebsite('2009-01-04 00:11:42'); + Test_Piwik_BaseFixture::createWebsite('2009-01-04 00:11:42'); Piwik_Goals_API::getInstance()->addGoal(1, 'Goal 1 - Thank you', 'title', 'Thank you', 'contains', $caseSensitive = false, $revenue = 10, $allowMultipleConversions = 1); $_GET['idSite'] = 1; @@ -105,7 +105,7 @@ class WidgetsListTest extends DatabaseTestCase FakeAccess::$superUser = true; Zend_Registry::set('access', $pseudoMockAccess); - IntegrationTestCase::createWebsite('2009-01-04 00:11:42', true); + Test_Piwik_BaseFixture::createWebsite('2009-01-04 00:11:42', true); Piwik_Goals_API::getInstance()->addGoal(1, 'Goal 1 - Thank you', 'title', 'Thank you', 'contains', $caseSensitive = false, $revenue = 10, $allowMultipleConversions = 1); $_GET['idSite'] = 1; diff --git a/tests/PHPUnit/Core/ServeStaticFileTest.php b/tests/PHPUnit/Core/ServeStaticFileTest.php index 9eca4b10b1..8e70d46cc5 100644 --- a/tests/PHPUnit/Core/ServeStaticFileTest.php +++ b/tests/PHPUnit/Core/ServeStaticFileTest.php @@ -388,7 +388,7 @@ class Test_Piwik_ServeStaticFile extends PHPUnit_Framework_TestCase */ private function getStaticSrvUrl() { - $url = IntegrationTestCase::getRootUrl(); + $url = Test_Piwik_BaseFixture::getRootUrl(); $url .= '/tests/resources/'; return $url . "staticFileServer.php?" . FILE_MODE_REQUEST_VAR . "=" . STATIC_SERVER_MODE . diff --git a/tests/PHPUnit/Fixtures/FewVisitsWithSetVisitorId.php b/tests/PHPUnit/Fixtures/FewVisitsWithSetVisitorId.php new file mode 100644 index 0000000000..0f394ad92e --- /dev/null +++ b/tests/PHPUnit/Fixtures/FewVisitsWithSetVisitorId.php @@ -0,0 +1,86 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site and tracks a couple visits using a custom visitor ID. + */ +class Test_Piwik_Fixture_FewVisitsWithSetVisitorId extends Test_Piwik_BaseFixture +{ + public $idSite = 1; + public $dateTime = '2010-03-06 11:22:33'; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + // tests run in UTC, the Tracker in UTC + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + + $t = self::getTracker($idSite, $dateTime, $defaultInit = true); + + // First, some basic tests + self::settingInvalidVisitorIdShouldThrow($t); + + // We create VISITOR A + $t->setUrl('http://example.org/index.htm'); + $t->setVisitorId(Piwik_Tracker_Visit::generateUniqueVisitorId()); + self::checkResponse($t->doTrackPageView('incredible title!')); + + // VISITOR B: few minutes later, we trigger the same tracker but with a custom visitor ID, + // => this will create a new visit B + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.05)->getDatetime()); + $t->setUrl('http://example.org/index2.htm'); + $t->setVisitorId(Piwik_Tracker_Visit::generateUniqueVisitorId()); + self::checkResponse($t->doTrackPageView('incredible title!')); + + // This new visit B will have 2 page views + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); + $t->setUrl('http://example.org/index3.htm'); + self::checkResponse($t->doTrackPageView('incredible title!')); + + // total = 2 visitors, 3 page views + + } + + private static function settingInvalidVisitorIdShouldThrow(PiwikTracker $t) + { + try { + $t->setVisitorId('test'); + $this->fail('should throw'); + } catch(Exception $e) { + //OK + } + try { + $t->setVisitorId('61e8'); + $this->fail('should throw'); + } catch(Exception $e) { + //OK + } + try { + $t->setVisitorId('61e8cc2d51fea26dabcabcabc'); + $this->fail('should throw'); + } catch(Exception $e) { + //OK + } + } +} diff --git a/tests/PHPUnit/Fixtures/InvalidVisits.php b/tests/PHPUnit/Fixtures/InvalidVisits.php new file mode 100644 index 0000000000..f7d7a004d6 --- /dev/null +++ b/tests/PHPUnit/Fixtures/InvalidVisits.php @@ -0,0 +1,104 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site and sends several invalid tracking requests. The result should be + * one website with no visits. + */ +class Test_Piwik_Fixture_InvalidVisits extends Test_Piwik_BaseFixture +{ + public $idSite = 1; + public $dateTime = '2009-01-04 00:11:42'; + + public $trackInvalidRequests = true; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + if (!$this->trackInvalidRequests) + { + return; + } + + $dateTime = $this->dateTime; + $idSite = $this->idSite; + + Piwik_SitesManager_API::getInstance()->setSiteSpecificUserAgentExcludeEnabled(true); + Piwik_SitesManager_API::getInstance()->setGlobalExcludedUserAgents('globalexcludeduseragent'); + + // Trigger empty request + $trackerUrl = self::getTrackerUrl(); + $response = Piwik_Http::fetchRemoteFile($trackerUrl); + self::assertTrue(strpos($response, 'is a free open source web') !== false, 'Piwik empty request response not correct: ' . $response); + + $t = self::getTracker($idSite, $dateTime, $defaultInit = true); + + // test GoogleBot UA visitor + $t->setUserAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); + self::checkResponse($t->doTrackPageView('bot visit, please do not record')); + + // Test IP Exclusion works with or without IP exclusion + foreach (array(false, true) as $enable) { + $excludedIp = '154.1.12.34'; + Piwik_SitesManager_API::getInstance()->updateSite($idSite, 'new site name', $url = array('http://site.com'), $ecommerce = 0, $ss = 1, $ss_kwd = '', $ss_cat = '', $excludedIp . ',1.2.3.4', $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = 'excludeduseragentstring'); + + // Enable IP Anonymization + $t->DEBUG_APPEND_URL = '&forceIpAnonymization=' . (int)$enable; + + // test with excluded User Agent + $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729) (excludeduseragentstring)'); + $t->setIp('211.1.2.3'); + self::checkResponse($t->doTrackPageView('visit from excluded User Agent')); + + // test w/ global excluded User Agent + $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729) (globalexcludeduseragent)'); + $t->setIp('211.1.2.3'); + self::checkResponse($t->doTrackPageView('visit from global excluded User Agent')); + + // test with excluded IP + $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)'); // restore normal user agent + $t->setIp($excludedIp); + self::checkResponse($t->doTrackPageView('visit from IP excluded')); + + // test with global list of excluded IPs + $excludedIpBis = '145.5.3.4'; + Piwik_SitesManager_API::getInstance()->setGlobalExcludedIps($excludedIpBis); + $t->setIp($excludedIpBis); + self::checkResponse($t->doTrackPageView('visit from IP globally excluded')); + } + + try { + @$t->setAttributionInfo(array()); + self::fail(); + } catch (Exception $e) { + } + + try { + $t->setAttributionInfo(json_encode('test')); + self::fail(); + } catch (Exception $e) { + } + + $t->setAttributionInfo(json_encode(array())); + } +} diff --git a/tests/PHPUnit/Fixtures/ManySitesImportedLogs.php b/tests/PHPUnit/Fixtures/ManySitesImportedLogs.php new file mode 100644 index 0000000000..1f69bc56dd --- /dev/null +++ b/tests/PHPUnit/Fixtures/ManySitesImportedLogs.php @@ -0,0 +1,154 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Imports visits from several log files using the python log importer. + */ +class Test_Piwik_Fixture_ManySitesImportedLogs extends Test_Piwik_BaseFixture +{ + public $dateTime = '2010-03-06 11:22:33'; + public $idSite = 1; + public $idSite2 = 2; + public $idGoal = 1; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + self::downloadGeoIpDbs(); + + Piwik_UserCountry_LocationProvider::$providers = null; + Piwik_UserCountry_LocationProvider_GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files'; + Piwik_UserCountry_LocationProvider::setCurrentProvider('geoip_php'); + + $this->trackVisits(); + } + + public function tearDown() + { + Piwik_UserCountry_LocationProvider::$providers = null; + Piwik_UserCountry_LocationProvider_GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files'; + Piwik_UserCountry_LocationProvider::setCurrentProvider('default'); + } + + public function setUpWebsitesAndGoals() + { + // for conversion testing + self::createWebsite($this->dateTime); + Piwik_Goals_API::getInstance()->addGoal($this->idSite, 'all', 'url', 'http', 'contains', false, 5); + self::createWebsite($this->dateTime, $ecommerce = 0, $siteName = 'Piwik test two', + $siteUrl = 'http://example-site-two.com'); + } + + private function trackVisits() + { + $this->logVisitsWithStaticResolver(); + $this->logVisitsWithAllEnabled(); + $this->replayLogFile(); + } + + /** + * Logs a couple visits for Aug 9, Aug 10, Aug 11 of 2012, for site we create. + */ + private function logVisitsWithStaticResolver() + { + $logFile = PIWIK_INCLUDE_PATH.'/tests/resources/fake_logs.log'; # log file + + $opts = array('--idsite' => $this->idSite, + '--token-auth' => self::getTokenAuth(), + '--recorders' => '4', + '--recorder-max-payload-size' => '2'); + + self::executeLogImporter($logFile, $opts); + } + + /** + * Logs a couple visits for the site we created and two new sites that do not + * exist yet. Visits are from Aug 12, 13 & 14 of 2012. + */ + public function logVisitsWithDynamicResolver() + { + $logFile = PIWIK_INCLUDE_PATH.'/tests/resources/fake_logs_dynamic.log'; # log file + + $opts = array('--add-sites-new-hosts' => false, + '--token-auth' => self::getTokenAuth(), + '--recorders' => '4', + '--recorder-max-payload-size' => '1'); + + self::executeLogImporter($logFile, $opts); + } + + /** + * Logs a couple visits for the site we created w/ all log importer options + * enabled. Visits are for Aug 11 of 2012. + */ + private function logVisitsWithAllEnabled() + { + $logFile = PIWIK_INCLUDE_PATH.'/tests/resources/fake_logs_enable_all.log'; + + $opts = array('--idsite' => $this->idSite, + '--token-auth' => self::getTokenAuth(), + '--recorders' => '4', + '--recorder-max-payload-size' => '2', + '--enable-static' => false, + '--enable-bots' => false, + '--enable-http-errors' => false, + '--enable-http-redirects' => false, + '--enable-reverse-dns' => false); + + self::executeLogImporter($logFile, $opts); + } + + /** + * Logs a couple visit using log entries that are tracking requests to a piwik.php file. + * Adds two visits to idSite=1 and two to non-existant sites. + */ + private function replayLogFile() + { + $logFile = PIWIK_INCLUDE_PATH.'/tests/resources/fake_logs_replay.log'; + + $opts = array('--token-auth' => self::getTokenAuth(), + '--recorders' => '4', + '--recorder-max-payload-size' => '2', + '--replay-tracking' => false); + + self::executeLogImporter($logFile, $opts); + } + + private static function executeLogImporter( $logFile, $options ) + { + $python = Piwik_Common::isWindows() ? "C:\Python27\python.exe" : 'python'; + + // create the command + $cmd = $python + . ' "'.PIWIK_INCLUDE_PATH.'/misc/log-analytics/import_logs.py" ' # script loc + . '-ddd ' // debug + . '--url="'.self::getRootUrl().'tests/PHPUnit/proxy/" ' # proxy so that piwik uses test config files + ; + + foreach ($options as $name => $value) + { + $cmd .= $name; + if ($value !== false) + { + $cmd .= '="'.$value.'"'; + } + $cmd .= ' '; + } + + $cmd .= '"'.$logFile.'" 2>&1'; + + // run the command + exec($cmd, $output, $result); + if ($result !== 0) + { + throw new Exception("log importer failed: ".implode("\n", $output)."\n\ncommand used: $cmd"); + } + + return $output; + } +} diff --git a/tests/PHPUnit/Fixtures/ManyVisitsOverSeveralDaysWithSearchEngineReferrers.php b/tests/PHPUnit/Fixtures/ManyVisitsOverSeveralDaysWithSearchEngineReferrers.php new file mode 100644 index 0000000000..44d519f888 --- /dev/null +++ b/tests/PHPUnit/Fixtures/ManyVisitsOverSeveralDaysWithSearchEngineReferrers.php @@ -0,0 +1,77 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one website and tracks visits on different days over a month + * using referrer URLs with search engines. + */ +class Test_Piwik_Fixture_ManyVisitsOverSeveralDaysWithSearchEngineReferrers extends Test_Piwik_BaseFixture +{ + public $today = '2010-03-06 11:22:33'; + public $idSite = 1; + public $keywords = array( + 'free > proprietary', // testing a keyword containing > + 'peace "," not war', // testing a keyword containing , + 'justice )(&^#%$ NOT corruption!', + ); + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite('2010-02-01 11:22:33'); + Piwik_Goals_API::getInstance()->addGoal($this->idSite, 'triggered php', 'manually', '', ''); + Piwik_Goals_API::getInstance()->addGoal( + $this->idSite, 'another triggered php', 'manually', '', '', false, false, true); + } + + private function trackVisits() + { + $dateTime = $this->today; + $idSite = $this->idSite; + + $t = self::getTracker($idSite, $dateTime, $defaultInit = true); + $t->setTokenAuth(self::getTokenAuth()); + $t->enableBulkTracking(); + for ($daysIntoPast = 30; $daysIntoPast >= 0; $daysIntoPast--) + { + // Visit 1: referrer website + test page views + $visitDateTime = Piwik_Date::factory($dateTime)->subDay($daysIntoPast)->getDatetime(); + + $t->setNewVisitorId(); + + $t->setUrlReferrer('http://www.referrer' . ($daysIntoPast % 5) . '.com/theReferrerPage' . ($daysIntoPast % 2) . '.html'); + $t->setUrl('http://example.org/my/dir/page' . ($daysIntoPast % 4) . '?foo=bar&baz=bar'); + $t->setForceVisitDateTime($visitDateTime); + self::assertTrue($t->doTrackPageView('incredible title ' . ($daysIntoPast % 3))); + + // Trigger goal n°1 once + self::assertTrue($t->doTrackGoal(1)); + + // Trigger goal n°2 twice + self::assertTrue($t->doTrackGoal(2)); + $t->setForceVisitDateTime(Piwik_Date::factory($visitDateTime)->addHour(0.1)->getDatetime()); + self::assertTrue($t->doTrackGoal(2)); + + // VISIT 2: search engine + $t->setForceVisitDateTime(Piwik_Date::factory($visitDateTime)->addHour(3)->getDatetime()); + $t->setUrlReferrer('http://google.com/search?q=' . urlencode($this->keywords[$daysIntoPast % 3])); + self::assertTrue($t->doTrackPageView('not an incredible title ')); + } + self::checkResponse($t->doBulkTrack()); + } +} diff --git a/tests/PHPUnit/Fixtures/ManyVisitsWithGeoIP.php b/tests/PHPUnit/Fixtures/ManyVisitsWithGeoIP.php new file mode 100644 index 0000000000..4aa03d8f6a --- /dev/null +++ b/tests/PHPUnit/Fixtures/ManyVisitsWithGeoIP.php @@ -0,0 +1,189 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/MockLocationProvider.php'; + +/** + * Adds one new website and tracks 35 visits from 18 visitors with geolocation using + * free GeoIP databases. The GeoIP databases are downloaded if they do not exist already. + */ +class Test_Piwik_Fixture_ManyVisitsWithGeoIP extends Test_Piwik_BaseFixture +{ + const GEOIP_IMPL_TO_TEST = 'geoip_php'; + + public $idSite = 1; + public $dateTime = '2010-01-03 11:22:33'; + + public $ips = array( + '194.57.91.215', // in Besançon, FR (unicode city name) + '::ffff:137.82.130.49', // in British Columbia (mapped ipv4) + '137.82.130.0', // anonymization tests + '137.82.0.0', + '2001:db8:85a3:0:0:8a2e:370:7334', // ipv6 (geoip lookup not supported) + '113.62.1.1', // in Lhasa, Tibet + '151.100.101.92', // in Rome, Italy (using country DB, so only Italy will show) + '103.29.196.229', // in Indonesia (Bali), (only Indonesia will show up) + ); + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + self::downloadGeoIpDbs(); + + $this->setMockLocationProvider(); + $this->trackVisits(9, false); + + $this->setLocationProvider('GeoIPCity.dat'); + $this->trackVisits(2, true, $useLocal = false); + $this->trackVisits(4, true, $useLocal = false, $doBulk = true); + + $this->setLocationProvider('GeoIP.dat'); + $this->trackVisits(2, true); + + $this->trackOtherVisits(); + + $this->setLocationProvider('GeoIPCity.dat'); + } + + public function tearDown() + { + $this->unsetLocationProvider(); + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime, 0, "Site 1"); + Piwik_Goals_API::getInstance()->addGoal($this->idSite, 'all', 'url', 'http', 'contains', false, 5); + } + + private function trackVisits( $visitorCount, $setIp = false, $useLocal = true, $doBulk = false ) + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + + // use local tracker so mock location provider can be used + $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useLocal); + if ($doBulk) + { + $t->enableBulkTracking(); + $t->setTokenAuth(self::getTokenAuth()); + } + for ($i = 0; $i != $visitorCount; ++$i) + { + $t->setNewVisitorId(); + if ($setIp) + { + $t->setIp(current($this->ips)); + next($this->ips); + } + else + { + $t->setIp("1.2.4.$i"); + } + + // first visit + $date = Piwik_Date::factory($dateTime)->addDay($i); + $t->setForceVisitDateTime($date->getDatetime()); + $t->setUrl("http://piwik.net/grue/lair"); + $r = $t->doTrackPageView('It\'s pitch black...'); + if (!$doBulk) + { + self::checkResponse($r); + } + + // second visit + $date = $date->addHour(1); + $t->setForceVisitDateTime($date->getDatetime()); + $t->setUrl("http://piwik.net/space/quest/iv"); + $r = $t->doTrackPageView("Space Quest XII"); + if (!$doBulk) + { + self::checkResponse($r); + } + } + if ($doBulk) + { + self::checkResponse($t->doBulkTrack()); + } + } + + private function trackOtherVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + + $t = self::getTracker($idSite, $dateTime, $defaultInit = true); + $t->setTokenAuth(self::getTokenAuth()); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addDay(20)->getDatetime()); + $t->setIp('194.57.91.215'); + $t->setCountry('us'); + $t->setRegion('CA'); + $t->setCity('not a city'); + $t->setLatitude(1); + $t->setLongitude(2); + $t->setUrl("http://piwik.net/grue/lair"); + self::checkResponse($t->doTrackPageView('It\'s pitch black...')); + } + + private function setLocationProvider( $file ) + { + Piwik_UserCountry_LocationProvider_GeoIp::$dbNames['loc'] = array($file); + Piwik_UserCountry_LocationProvider_GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files'; + Piwik_UserCountry_LocationProvider::$providers = null; + Piwik_UserCountry_LocationProvider::setCurrentProvider(self::GEOIP_IMPL_TO_TEST); + + if (Piwik_UserCountry_LocationProvider::getCurrentProviderId() !== self::GEOIP_IMPL_TO_TEST) + { + throw new Exception("Failed to set the current location provider to '".self::GEOIP_IMPL_TO_TEST."'."); + } + + $possibleFiles = Piwik_UserCountry_LocationProvider_GeoIp::$dbNames['loc']; + if (Piwik_UserCountry_LocationProvider_GeoIp::getPathToGeoIpDatabase($possibleFiles) === false) + { + throw new Exception("The GeoIP location provider cannot find the '$file' file! Tests will fail."); + } + } + + private function setMockLocationProvider() + { + Piwik_UserCountry_LocationProvider::$providers = null; + Piwik_UserCountry_LocationProvider::setCurrentProvider('mock_provider'); + MockLocationProvider::$locations = array( + self::makeLocation('Stratford-upon-Avon', 'P3', 'gb', 123.456, 21.321), // template location + + // same region, different city, same country + self::makeLocation('Nuneaton and Bedworth', 'P3', 'gb'), + + // same region, city & country (different lat/long) + self::makeLocation('Stratford-upon-Avon', 'P3', 'gb', 124.456, 22.231), + + // same country, different region & city + self::makeLocation('London', 'H9', 'gb'), + + // same country, different region, same city + self::makeLocation('Stratford-upon-Avon', 'G5', 'gb'), + + // different country, diff region, same city + self::makeLocation('Stratford-upon-Avon', '66', 'ru'), + + // different country, diff region (same as last), different city + self::makeLocation('Hluboká nad Vltavou', '66', 'ru'), + + // different country, diff region (same as last), same city + self::makeLocation('Stratford-upon-Avon', '66', 'mk'), + + // unknown location + self::makeLocation(null, null, null), + ); + } + + private function unsetLocationProvider() + { + Piwik_UserCountry_LocationProvider::setCurrentProvider('default'); + } +} diff --git a/tests/PHPUnit/Fixtures/ManyVisitsWithMockLocationProvider.php b/tests/PHPUnit/Fixtures/ManyVisitsWithMockLocationProvider.php new file mode 100644 index 0000000000..ea116f545a --- /dev/null +++ b/tests/PHPUnit/Fixtures/ManyVisitsWithMockLocationProvider.php @@ -0,0 +1,209 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/MockLocationProvider.php'; + +/** + * Adds one site and tracks 60 visits (15 visitors, one action per visit). + */ +class Test_Piwik_Fixture_ManyVisitsWithMockLocationProvider extends Test_Piwik_BaseFixture +{ + public $idSite = 1; + public $dateTime = '2010-01-03 01:22:33'; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->setMockLocationProvider(); + $this->trackVisits(); + } + + public function tearDown() + { + $this->unsetMockLocationProvider(); + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + $linuxFirefoxA = "Mozilla/5.0 (X11; Linux i686; rv:6.0) Gecko/20100101 Firefox/6.0"; + $win7FirefoxA = "Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.1.6) Gecko/20100101 Firefox/6.0"; + $win7ChromeA = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.38 Safari/532.0"; + $linuxChromeA = "Mozilla/5.0 (X11; Linux i686; rv:6.0) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.38 Safari/532.0"; + $linuxSafariA = "Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/531.2+ (KHTML, like Gecko) Version/5.0 Safari/531.2+"; + $iPadSafariA = "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/531.2+ (KHTML, like Gecko) Version/5.0 Safari/531.2+"; + $iPadFirefoxB = "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) Gecko/20100101 Firefox/14.0.1"; + $androidFirefoxB = "Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) Gecko/20100101 Firefox/14.0.1"; + $androidChromeB = "Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"; + $androidIEA = "Mozilla/5.0 (compatible; MSIE 10.6; Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0"; + $iPhoneOperaA = "Opera/9.80 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; ja-jp) Presto/2.9.181 Version/12.00"; + $win8IEB = "Mozilla/5.0 (compatible; MSIE 10.0; Windows 8; Trident/5.0)"; + $winVistaIEB = "Mozilla/5.0 (compatible; MSIE 10.0; Windows Vista; Trident/5.0)"; + $osxOperaB = "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52"; + $userAgents = array( + $linuxFirefoxA, $linuxFirefoxA, $win7FirefoxA, $win7ChromeA, $linuxChromeA, $linuxSafariA, + $iPadSafariA, $iPadFirefoxB, $androidFirefoxB, $androidChromeB, $androidIEA, $iPhoneOperaA, + $win8IEB, $winVistaIEB, $osxOperaB + ); + + $resolutions = array( + "1920x1080", "1920x1080", "1920x1080", "1920x1080", "1366x768", "1366x768", "1366x768", + "1280x1024", "1280x1024", "1280x1024", "1680x1050", "1680x1050", "1024x768", "800x600", + "320x480" + ); + + $referrers = array( + // website referrers (8) + 'http://whatever0.com/0', 'http://whatever0.com/0', 'http://whatever0.com/1', 'http://whatever0.com/2', + 'http://whatever1.com/0', 'http://whatever.com1/1', 'http://whatever1.com/2', 'http://whatever3.com/3', + + // search engines w/ keyword (12) + 'http://www.google.com/search?q=this+search+term', + 'http://www.google.com/search?q=that+search+term', + 'http://search.yahoo.com/search?p=this+search+term', + 'http://search.yahoo.com/search?p=that+search+term', + 'http://www.ask.com/web?q=this+search+term', + 'http://www.bing.com/search?q=search+term+1', + 'http://search.babylon.com/?q=search+term+2', + 'http://alexa.com/search?q=search+term+2', + 'http://www.google.com/search?q=search+term+3', + 'http://search.yahoo.com/search?p=search+term+4', + 'http://www.ask.com/web?q=search+term+3', + 'http://www.bing.com/search?q=search+term+4', + ); + + $customVars = array( + 'name' => array('thing0', 'thing1', 'thing2', 'thing3', 'thing4', 'thing5', 'thing6', 'thing7', + 'thing8', 'thing9', 'thing10', 'thing11', 'thing12', 'thing13', 'thing14', + 'thing15', 'thing16', 'thing17', 'thing18', 'thing19'), + 'rating' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20), + 'tweeted' => array('y', 'n', 'm', 'n', 'y', 'n', 'y', 'n', 'y', 'n', 'y', 'n', 'y', 'n', 'y', 'n', + 'm', 'n', 'm', 'n'), + 'liked' => array('yes', 'y', 'y', 'no', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', + 'y', 'y', 'no', 'n'), + ); + $downloadCustomVars = array( + 'size' => array(1024, 1024, 1024, 2048, 2048, 3072, 3072, 3072, 3072, 4096, 4096, 4096, + 512, 512, 256, 128, 64, 32, 48, 48) + ); + + $visitorCounter = 0; + $t = self::getTracker($this->idSite, $this->dateTime, $defaultInit = true, $useLocal = true); + + // track regular actions + $this->trackActions($t, $visitorCounter, 'pageview', $userAgents, $resolutions, $referrers, $customVars); + + // track downloads + $this->trackActions($t, $visitorCounter, 'download', $userAgents, $resolutions, null, $downloadCustomVars); + + // track outlinks + $this->trackActions($t, $visitorCounter, 'outlink', $userAgents, $resolutions); + } + + private function trackActions($t, &$visitorCounter, $actionType, $userAgents, $resolutions, + $referrers = null, $customVars = null) + { + for ($i = 0; $i != 5; ++$i, ++$visitorCounter) + { + $visitDate = Piwik_Date::factory($this->dateTime); + + $t->setNewVisitorId(); + $t->setIp("156.5.3.$visitorCounter"); + + $t->setUserAgent($userAgents[$visitorCounter]); + list($w, $h) = explode('x', $resolutions[$visitorCounter]); + $t->setResolution((int)$w, (int)$h); + + // one visit to root url + $t->setUrl("http://piwik.net/$visitorCounter/"); + $t->setUrlReferrer(null); + $t->setForceVisitDateTime($visitDate->getDatetime()); + $this->trackAction($t, $actionType, $visitorCounter, null); + + for ($j = 0; $j != 4; ++$j) + { + // NOTE: to test referers w/o creating too many visits, we don't actually track 4 actions, but + // 4 separate visits + $actionDate = $visitDate->addHour($j + 1); + + $actionIdx = $i * 4 + $j; + $actionNum = $visitorCounter * 4 + $j; + + $t->setUrl("http://piwik.net/$visitorCounter/$actionNum"); + $t->setForceVisitDateTime($actionDate->getDatetime()); + + if (!is_null($referrers)) + { + $t->setUrlReferrer($referrers[$actionIdx]); + } + else + { + $t->setUrlReferrer(null); + } + + if (!is_null($customVars)) + { + $k = 1; + foreach ($customVars as $name => $values) + { + $value = $values[$actionIdx]; + $t->setCustomVariable($k, $name, $value, $scope = 'page'); + + ++$k; + } + } + + $this->trackAction($t, $actionType, $visitorCounter, $actionNum); + } + } + } + + private function trackAction($t, $actionType, $visitorCounter, $actionNum) + { + if ($actionType == 'pageview') + { + self::checkResponse($t->doTrackPageView( + is_null($actionNum) ? "title_$visitorCounter" : "title_$visitorCounter / title_$actionNum")); + } + else if ($actionType == 'download') + { + $root = is_null($actionNum) ? "http://cloudsite$visitorCounter.com" + : "http://cloudsite$visitorCounter.com/$actionNum"; + + self::checkResponse($t->doTrackAction("$root/download", 'download')); + } + else if ($actionType == 'outlink') + { + self::checkResponse($t->doTrackAction(is_null($actionNum) ? "http://othersite$visitorCounter.com/" + : "http://othersite$visitorCounter.com/$actionNum/", 'link')); + } + } + + private function setMockLocationProvider() + { + Piwik_UserCountry_LocationProvider::setCurrentProvider('mock_provider'); + MockLocationProvider::$locations = array( + self::makeLocation('Toronto', 'ON', 'CA'), + + self::makeLocation('Nice', 'B8', 'FR'), + + self::makeLocation('Melbourne', '07', 'AU'), + + self::makeLocation('Yokohama', '19', 'JP'), + ); + } + + private function unsetMockLocationProvider() + { + Piwik_UserCountry_LocationProvider::setCurrentProvider('default'); + } +} diff --git a/tests/PHPUnit/Fixtures/ManyVisitsWithSubDirReferrersAndCustomVars.php b/tests/PHPUnit/Fixtures/ManyVisitsWithSubDirReferrersAndCustomVars.php new file mode 100644 index 0000000000..5234c21ffb --- /dev/null +++ b/tests/PHPUnit/Fixtures/ManyVisitsWithSubDirReferrersAndCustomVars.php @@ -0,0 +1,59 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site and tracks 13 visits all with custom variables and referrer URLs + * w/ sub-dirs (ie, /path/to/page/has/many/dirs.htm). + */ +class Test_Piwik_Fixture_ManyVisitsWithSubDirReferrersAndCustomVars extends Test_Piwik_BaseFixture +{ + public $dateTime = '2010-03-06 11:22:33'; + public $idSite = 1; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + + for ($referrerSite = 1; $referrerSite < 4; $referrerSite++) { + for ($referrerPage = 1; $referrerPage < 3; $referrerPage++) { + $offset = $referrerSite * 3 + $referrerPage; + $t = self::getTracker($idSite, Piwik_Date::factory($dateTime)->addHour($offset)->getDatetime()); + $t->setUrlReferrer('http://www.referrer' . $referrerSite . '.com/sub/dir/page' . $referrerPage . '.html'); + $t->setCustomVariable(1, 'CustomVarVisit', 'CustomVarValue' . $referrerPage, 'visit'); + for ($page = 0; $page < 3; $page++) { + $t->setUrl('http://example.org/dir' . $referrerSite . '/sub/dir/page' . $page . '.html'); + $t->setCustomVariable(1, 'CustomVarPage', 'CustomVarValue' . $page, 'page'); + self::checkResponse($t->doTrackPageView('title')); + } + } + } + + $t = self::getTracker($idSite, Piwik_Date::factory($dateTime)->addHour(24)->getDatetime()); + $t->setCustomVariable(1, 'CustomVarVisit', 'CustomVarValue1', 'visit'); + $t->setUrl('http://example.org/sub/dir/dir1/page1.html'); + $t->setCustomVariable(1, 'CustomVarPage', 'CustomVarValue1', 'page'); + self::checkResponse($t->doTrackPageView('title')); + } +} diff --git a/tests/PHPUnit/Fixtures/OneVisitSeveralPageViews.php b/tests/PHPUnit/Fixtures/OneVisitSeveralPageViews.php new file mode 100644 index 0000000000..de9a020986 --- /dev/null +++ b/tests/PHPUnit/Fixtures/OneVisitSeveralPageViews.php @@ -0,0 +1,64 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site and tracks one visit with several pageviews. + */ +class Test_Piwik_Fixture_OneVisitSeveralPageViews extends Test_Piwik_BaseFixture +{ + public $dateTime = '2010-03-06 11:22:33'; + public $idSite = 1; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useThirdPartyCookie = 1); + + $t->setUrlReferrer('http://www.google.com.vn/url?sa=t&rct=j&q=%3C%3E%26%5C%22the%20pdo%20extension%20is%20required%20for%20this%20adapter%20but%20the%20extension%20is%20not%20loaded&source=web&cd=4&ved=0FjAD&url=http%3A%2F%2Fforum.piwik.org%2Fread.php%3F2%2C1011&ei=y-HHAQ&usg=AFQjCN2-nt5_GgDeg&cad=rja'); + $t->setUrl('http://example.org/%C3%A9%C3%A9%C3%A9%22%27...%20%3Cthis%20is%20cool%3E!'); + self::checkResponse($t->doTrackPageView('incredible title! <>,;')); + + $t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); + self::checkResponse($t->doTrackPageView('incredible title! <>,;')); + + $t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar2'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); + self::checkResponse($t->doTrackPageView('incredible parent title! <>,; / subtitle <>,;')); + + $t->setUrl('http://example.org/dir2/file.php?foo=bar&foo2=bar'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); + self::checkResponse($t->doTrackPageView('incredible title! <>,;')); + + $t->setUrl('http://example.org/dir2/sub/0/file.php'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); + self::checkResponse($t->doTrackPageView('incredible title! <>,;')); + + $t->setUrl('http://example.org/0'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); + self::checkResponse($t->doTrackPageView('I am URL zero!')); + + } +} diff --git a/tests/PHPUnit/Fixtures/OneVisitWithAbnormalPageviewUrls.php b/tests/PHPUnit/Fixtures/OneVisitWithAbnormalPageviewUrls.php new file mode 100644 index 0000000000..439433cefe --- /dev/null +++ b/tests/PHPUnit/Fixtures/OneVisitWithAbnormalPageviewUrls.php @@ -0,0 +1,64 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site and tracks one visit w/ pageview URLs that are not normalized. + * These URLs use different protocols and a mix of lowercase & uppercase letters. + */ +class Test_Piwik_Fixture_OneVisitWithAbnormalPageviewUrls extends Test_Piwik_BaseFixture +{ + public $dateTime = '2010-03-06 11:22:33'; + public $idSite = 1; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useThirdPartyCookie = 1); + + $t->setUrlReferrer('http://www.google.com/search?q=piwik'); + $t->setUrl('http://example.org/foo/bar.html'); + self::checkResponse($t->doTrackPageView('http://incredible.title/')); + + $t->setUrl('https://example.org/foo/bar.html'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); + self::checkResponse($t->doTrackPageView('https://incredible.title/')); + + $t->setUrl('https://wWw.example.org/foo/bar2.html'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); + self::checkResponse($t->doTrackPageView('http://www.incredible.title/')); + + $t->setUrl('http://WwW.example.org/foo/bar2.html'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); + self::checkResponse($t->doTrackPageView('https://www.incredible.title/')); + + $t->setUrl('http://www.example.org/foo/bar3.html'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.5)->getDatetime()); + self::checkResponse($t->doTrackPageView('incredible.title/')); + + $t->setUrl('https://example.org/foo/bar4.html'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.6)->getDatetime()); + self::checkResponse($t->doTrackPageView('incredible.title/')); + } +} diff --git a/tests/PHPUnit/Fixtures/OneVisitorTwoVisits.php b/tests/PHPUnit/Fixtures/OneVisitorTwoVisits.php new file mode 100644 index 0000000000..3177a41c3f --- /dev/null +++ b/tests/PHPUnit/Fixtures/OneVisitorTwoVisits.php @@ -0,0 +1,156 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * This fixture adds one website and tracks two visits by one visitor. + */ +class Test_Piwik_Fixture_OneVisitorTwoVisits extends Test_Piwik_BaseFixture +{ + public $idSite = 1; + public $dateTime = '2010-03-06 11:22:33'; + + public $useThirdPartyCookies = false; + public $useSiteSearch = false; + public $excludeMozilla = false; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + + if ($this->excludeMozilla) + { + Piwik_SitesManager_API::getInstance()->setSiteSpecificUserAgentExcludeEnabled(false); + } + + $t = self::getTracker($idSite, $dateTime, $defaultInit = true); + + if ($this->useThirdPartyCookies) + { + $t->DEBUG_APPEND_URL = '&forceUseThirdPartyCookie=1'; + } + + $t->disableCookieSupport(); + + $t->setUrlReferrer('http://referer.com/page.htm?param=valuewith some spaces'); + + // testing URL excluded parameters + $parameterToExclude = 'excluded_parameter'; + Piwik_SitesManager_API::getInstance()->updateSite( + $idSite, + 'new name', + $url = array('http://site.com'), + $ecommerce = 0, + $siteSearch = $this->useSiteSearch ? 1 : 0, + $searchKeywordParameters = $this->useSiteSearch ? '' : null, + $searchCategoryParameters = $this->useSiteSearch ? 'notparam' : null, + $excludedIps = null, + $parameterToExclude . ',anotherParameter', + $timezone = null, + $currency = null, + $group = null, + $startDate = null, + // test that visit won't be excluded since site-specific exclude is not enabled + $excludedUserAgents = $this->excludeMozilla ? 'mozilla' : null + ); + + // Record 1st page view + $urlPage1 = 'http://example.org/index.htm?excluded_Parameter=SHOULD_NOT_DISPLAY¶meter=Should display'; + $t->setUrl($urlPage1); + self::checkResponse($t->doTrackPageView('incredible title!')); + + // testing that / and index.htm above record with different URLs + // Recording the 2nd page after 3 minutes + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.05)->getDatetime()); + $t->setUrl('http://example.org/'); + self::checkResponse($t->doTrackPageView('Second page view - should be registered as URL /')); + + // Click on external link after 6 minutes (3rd action) + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); + self::checkResponse($t->doTrackAction('http://dev.piwik.org/svn', 'link')); + + // Click on file download after 12 minutes (4th action) + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); + self::checkResponse($t->doTrackAction('http://piwik.org/path/again/latest.zip', 'download')); + + // Click on two more external links, one the same as before (5th & 6th actions) + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.22)->getDateTime()); + self::checkResponse($t->doTrackAction('http://outlinks.org/other_outlink', 'link')); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.25)->getDateTime()); + self::checkResponse($t->doTrackAction('http://dev.piwik.org/svn', 'link')); + + // Create Goal 1: Triggered by JS, after 18 minutes + $idGoal = Piwik_Goals_API::getInstance()->addGoal($idSite, 'triggered js', 'manually', '', ''); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); + + // Change to Thai browser to ensure the conversion is credited to FR instead (the visitor initial country) + $t->setBrowserLanguage('th'); + self::checkResponse($t->doTrackGoal($idGoal, $revenue = 42)); + + // Track same Goal twice (after 24 minutes), should only be tracked once + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); + self::checkResponse($t->doTrackGoal($idGoal, $revenue = 42)); + + $t->setBrowserLanguage('fr'); + + if ($this->useSiteSearch) + { + // Site Search request + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.42)->getDatetime()); + $t->setUrl('http://example.org/index.htm?q=Banks Own The World'); + self::checkResponse($t->doTrackPageView('Site Search request')); + + // Final page view (after 27 min) + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.45)->getDatetime()); + $t->setUrl('http://example.org/index.htm'); + self::checkResponse($t->doTrackPageView('Looking at homepage after site search...')); + } + else + { + // Final page view (after 27 min) + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.45)->getDatetime()); + $t->setUrl('http://example.org/index.htm#ignoredFragment#'); + self::checkResponse($t->doTrackPageView('Looking at homepage (again)...')); + } + + // - + // End of first visit: 24min + + // Create Goal 2: Matching on URL + Piwik_Goals_API::getInstance()->addGoal($idSite, 'matching purchase.htm', 'url', '(.*)store\/purchase\.(.*)', 'regex', false, $revenue = 1); + + // - + // Start of returning visit, 1 hour after first page view + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); + $t->setUrl('http://example.org/store/purchase.htm'); + $t->setUrlReferrer('http://search.yahoo.com/search?p=purchase'); + // Temporary, until we implement 1st party cookies in PiwikTracker + $t->DEBUG_APPEND_URL = '&_idvc=2'; + + // Goal Tracking URL matching, testing custom referer including keyword + self::checkResponse($t->doTrackPageView('Checkout/Purchasing...')); + // - + // End of second visit + } +} diff --git a/tests/PHPUnit/Fixtures/SomeVisitsAllConversions.php b/tests/PHPUnit/Fixtures/SomeVisitsAllConversions.php new file mode 100644 index 0000000000..72b3b8d1c9 --- /dev/null +++ b/tests/PHPUnit/Fixtures/SomeVisitsAllConversions.php @@ -0,0 +1,80 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site and tracks a couple conversions. + */ +class Piwik_Test_Fixture_SomeVisitsAllConversions extends Test_Piwik_BaseFixture +{ + public $dateTime = '2009-01-04 00:11:42'; + public $idSite = 1; + public $idGoal_OneConversionPerVisit = 1; + public $idGoal_MultipleConversionPerVisit = 2; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + + // First, a goal that is only recorded once per visit + Piwik_Goals_API::getInstance()->addGoal( + $this->idSite, 'triggered js ONCE', 'title', 'Thank you', 'contains', $caseSensitive = false, + $revenue = 10, $allowMultipleConversions = false + ); + + // Second, a goal allowing multiple conversions + Piwik_Goals_API::getInstance()->addGoal( + $this->idSite, 'triggered js MULTIPLE ALLOWED', 'manually', '', '', $caseSensitive = false, + $revenue = 10, $allowMultipleConversions = true + ); + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + $idGoal_OneConversionPerVisit = $this->idGoal_OneConversionPerVisit; + $idGoal_MultipleConversionPerVisit = $this->idGoal_MultipleConversionPerVisit; + + $t = self::getTracker($idSite, $dateTime, $defaultInit = true); + + // Record 1st goal, should only have 1 conversion + $t->setUrl('http://example.org/index.htm'); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); + self::checkResponse($t->doTrackPageView('Thank you mate')); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); + self::checkResponse($t->doTrackGoal($idGoal_OneConversionPerVisit, $revenue = 10000000)); + + // Record 2nd goal, should record both conversions + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.5)->getDatetime()); + self::checkResponse($t->doTrackGoal($idGoal_MultipleConversionPerVisit, $revenue = 300)); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.6)->getDatetime()); + self::checkResponse($t->doTrackGoal($idGoal_MultipleConversionPerVisit, $revenue = 366)); + + // Update & set to not allow multiple + $goals = Piwik_Goals_API::getInstance()->getGoals($idSite); + $goal = $goals[$idGoal_OneConversionPerVisit]; + self::assertTrue($goal['allow_multiple'] == 0); + Piwik_Goals_API::getInstance()->updateGoal($idSite, $idGoal_OneConversionPerVisit, $goal['name'], @$goal['match_attribute'], @$goal['pattern'], @$goal['pattern_type'], @$goal['case_sensitive'], $goal['revenue'], $goal['allow_multiple'] = 1); + self::assertTrue($goal['allow_multiple'] == 1); + + // 1st goal should Now be tracked + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.61)->getDatetime()); + self::checkResponse($t->doTrackGoal($idGoal_OneConversionPerVisit, $revenue = 656)); + } +} diff --git a/tests/PHPUnit/Fixtures/SomeVisitsCustomVariablesCampaignsNotHeuristics.php b/tests/PHPUnit/Fixtures/SomeVisitsCustomVariablesCampaignsNotHeuristics.php new file mode 100644 index 0000000000..4ccbdf624a --- /dev/null +++ b/tests/PHPUnit/Fixtures/SomeVisitsCustomVariablesCampaignsNotHeuristics.php @@ -0,0 +1,118 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Add one site and track many visits with custom variables & campaign IDs and + * use visit ID instead of heuristics. + */ +class Test_Piwik_Fixture_SomeVisitsCustomVariablesCampaignsNotHeuristics extends Test_Piwik_BaseFixture +{ + public $dateTime = '2009-01-04 00:11:42'; + public $idSite = 1; + public $idGoal = 1; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + Piwik_Goals_API::getInstance()->addGoal($this->idSite, 'triggered js', 'manually', '', ''); + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + $idGoal = $this->idGoal; + + $t = self::getTracker($idSite, $dateTime, $defaultInit = true); + + // Record 1st page view + $t->setUrl('http://example.org/index.htm?utm_campaign=GA Campaign&piwik_kwd=Piwik kwd&utm_term=GA keyword SHOULD NOT DISPLAY#pk_campaign=NOT TRACKED!!&pk_kwd=NOT TRACKED!!'); + self::checkResponse($t->doTrackPageView('incredible title!')); + + $visitorId = $t->getVisitorId(); + self::assertTrue(strlen($visitorId) == 16); + + // test setting/getting the first party cookie via the PHP Tracking Client + $_COOKIE['_pk_id_1_1fff'] = 'ca0afe7b6b692ff5.1302307497.1.1302307497.1302307497'; + $_COOKIE['_pk_ref_1_1fff'] = '["YEAH","RIGHT!",1302307497,"http://referrer.example.org/page/sub?query=test&test2=test3"]'; + $_COOKIE['_pk_cvar_1_1fff'] = '{"1":["VAR 1 set, var 2 not set","yes"],"3":["var 3 set","yes!!!!"]}'; + self::assertEquals('ca0afe7b6b692ff5', $t->getVisitorId()); + self::assertEquals($t->getAttributionInfo(), $_COOKIE['_pk_ref_1_1fff']); + self::assertEquals(array("VAR 1 set, var 2 not set", "yes"), $t->getCustomVariable(1)); + self::assertFalse($t->getCustomVariable(2)); + self::assertEquals(array("var 3 set", "yes!!!!"), $t->getCustomVariable(3)); + self::assertFalse($t->getCustomVariable(4)); + self::assertFalse($t->getCustomVariable(5)); + self::assertFalse($t->getCustomVariable(6)); + self::assertFalse($t->getCustomVariable(-1)); + unset($_COOKIE['_pk_id_1_1fff']); + unset($_COOKIE['_pk_ref_1_1fff']); + unset($_COOKIE['_pk_cvar_1_1fff']); + + // Create a new Tracker object, with different attributes + $t2 = self::getTracker($idSite, $dateTime, $defaultInit = false); + + // Make sure the ID is different at first + $visitorId2 = $t2->getVisitorId(); + self::assertTrue($visitorId != $visitorId2); + + // Then force the visitor ID + $t2->setVisitorId($visitorId); + + // And Record a Goal: The previous visit should be updated rather than a new visit Created + $t2->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); + self::checkResponse($t2->doTrackGoal($idGoal, $revenue = 42.256)); + + // Yet another visitor, this time with a manual goal conversion, which should be credited to the campaign + $t3 = self::getTracker($idSite, $dateTime); + $t3->setUrlReferrer('http://example.org/referrer'); + $t3->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.3)->getDatetime()); + // fake a website ref cookie, the campaign should be credited for conversion, not referrer.example.com nor example.org + $t3->DEBUG_APPEND_URL = '&_ref=http%3A%2F%2Freferrer.example.com%2Fpage%2Fsub%3Fquery%3Dtest%26test2%3Dtest3'; + $t3->setUrl('http://example.org/index.htm#pk_campaign=CREDITED TO GOAL PLEASE'); + self::checkResponse($t3->doTrackGoal($idGoal, 42)); + + // visitor #4, test for blank referrer campaign keyword + $t4 = self::getTracker($idSite, $dateTime); + $t4->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(3)->getDatetime()); + $t4->setUrlReferrer('http://bing.com/search?q=whatever'); + $t4->setUrl('http://example.org/index.html?utm_campaign=GA+Campaign'); + self::checkResponse($t4->doTrackPageView('first page')); + + // No campaign keyword specified, will use the referrer hostname + $t4->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(4)->getDatetime()); + $t4->setUrlReferrer('http://thing1.com/a/b/c.html?a=b&d=c'); + $t4->setUrl('http://example.org/index.html?utm_campaign=GA+Campaign'); + self::checkResponse($t4->doTrackPageView('second page')); + + // Test with Google adsense type URL: + $adsenseRefererUrl = 'http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-12345&output=html&h=280&slotname=123&w=336&lmt=1359388321&202&url=http%3A%2F%2Fwww.adsense-publisher-website.org%2F&dt=123&bpp=13&shv=r22&jsv=1565606614&correlator=ss&ga_vid=aaa&ga_sid=1359435122&ga_hid=1801871121&ga_fc=0&u_tz=780&u_his=4&u_java=1&u_h=900&u_w=1600&u_ah=876&u_aw=1551&u_cd=24&u_nplug=4&u_nmime=5&dff=georgia&dfs=16&adx=33&ady=201&biw=1551&bih=792&oid=3&fu=0&ifi=1&dtd=608&p=http%3A//www.adsense-publisher-website.com'; + $t4->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(5)->getDatetime()); + $t4->setUrlReferrer($adsenseRefererUrl); + $t4->setUrl('http://example.org/index.html?utm_campaign=Adsense campaign'); + self::checkResponse($t4->doTrackPageView('second page')); + + // Test with google Adwords URL + $adwordsUrl = 'http://www.google.co.nz/aclk?sa=L&ai=uYmFyiZgAf0oO0J&num=3&sig=EpOCR4xQ&ved=ENEM&adurl=http://pixel.everesttech.net/3163/cq%3Fev_sid%3D3%26ev_cmpid%3D33%26ev_ln%3Dused%2520wii%2520consoles%26ev_crx%528386%26ev_mt%3Db%26ev_n%3Dg%26ev_ltx%3D%26ev_pl%3D%26ev_pos%3D1s2%26url%3Dhttp%253A//au.shopping.com/used%2520wii%2520consoles/products%253Flinkin_id%253D8077872&rct=j&q=nintendo+consoles+second+hand'; + $t4->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(6)->getDatetime()); + $t4->setUrlReferrer($adwordsUrl); + $t4->setUrl('http://example.org/index.html?utm_campaign=Adwords campaign'); + self::checkResponse($t4->doTrackPageView('second page')); + } +} diff --git a/tests/PHPUnit/Fixtures/SomeVisitsManyPageviewsWithTransitions.php b/tests/PHPUnit/Fixtures/SomeVisitsManyPageviewsWithTransitions.php new file mode 100644 index 0000000000..dc7ea10572 --- /dev/null +++ b/tests/PHPUnit/Fixtures/SomeVisitsManyPageviewsWithTransitions.php @@ -0,0 +1,91 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site and tracks a couple visits with many pageviews. The + * pageviews are designed to have many transitions between pages. + */ +class Test_Piwik_Fixture_SomeVisitsManyPageviewsWithTransitions extends Test_Piwik_BaseFixture +{ + public $dateTime = '2010-03-06 11:22:33'; + public $idSite = 1; + + private $prefixCounter = 0; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + $visit1 = $this->createVisit(1); + $visit1->setUrlReferrer('http://www.google.com.vn/url?sa=t&rct=j&q=%3C%3E%26%5C%22the%20pdo%20extension%20is%20required%20for%20this%20adapter%20but%20the%20extension%20is%20not%20loaded&source=web&cd=4&ved=0FjAD&url=http%3A%2F%2Fforum.piwik.org%2Fread.php%3F2%2C1011&ei=y-HHAQ&usg=AFQjCN2-nt5_GgDeg&cad=rja'); + $this->trackPageView($visit1, 0, 'page/one.html'); + $this->trackPageView($visit1, 0.1, 'sub/dir/page2.html'); + $this->trackPageView($visit1, 0.2, 'page/one.html'); + $this->trackPageView($visit1, 0.3, 'the/third_page.html?foo=bar'); + $this->trackPageView($visit1, 0.4, 'page/one.html'); + $this->trackPageView($visit1, 0.5, 'the/third_page.html?foo=bar'); + $this->trackPageView($visit1, 0.6, 'page/one.html'); + $this->trackPageView($visit1, 0.7, 'the/third_page.html?foo=baz#anchor1'); + $this->trackPageView($visit1, 0.8, 'page/one.html'); + $this->trackPageView($visit1, 0.9, 'page/one.html'); + $this->trackPageView($visit1, 1.0, 'the/third_page.html?foo=baz#anchor2'); + $this->trackPageView($visit1, 1.1, 'page/one.html'); + $this->trackPageView($visit1, 1.2, 'page3.html'); + + $visit2 = $this->createVisit(2); + $visit2->setUrlReferrer('http://www.external.com.vn/referrerPage-notCounted.html'); + $this->trackPageView($visit2, 0, 'sub/dir/page2.html'); + $this->trackPageView($visit2, 0.1, 'the/third_page.html?foo=bar'); + $this->trackPageView($visit2, 0.2, 'page/one.html'); + $this->trackPageView($visit2, 0.3, 'the/third_page.html?foo=baz#anchor1'); + + $visit3 = $this->createVisit(3); + $visit3->setUrlReferrer('http://www.external.com.vn/referrerPage-counted.html'); + $this->trackPageView($visit3, 0.1, 'page/one.html'); + $this->trackPageView($visit3, 0.2, 'sub/dir/page2.html'); + $this->trackPageView($visit3, 0.3, 'page/one.html'); + + $visit4 = $this->createVisit(4); + $this->trackPageView($visit4, 0, 'page/one.html?pk_campaign=TestCampaign&pk_kwd=TestKeyword'); + + $visit5 = $this->createVisit(5); + $this->trackPageView($visit5, 0, 'page/one.html'); + } + + private function createVisit($id) { + $visit = self::getTracker($this->idSite, $this->dateTime, $defaultInit = true); + $visit->setIp('156.5.3.'.$id); + return $visit; + } + + private function trackPageView($visit, $timeOffset, $path) { + // rotate protocol and www to make sure it doesn't matter + $prefixes = array('http://', 'http://www.', 'https://', 'https://'); + $prefix = $prefixes[$this->prefixCounter]; + $this->prefixCounter = ($this->prefixCounter + 1) % 4; + + /** @var $visit PiwikTracker */ + $visit->setUrl($prefix.'example.org/'.$path); + $visit->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour($timeOffset)->getDatetime()); + self::checkResponse($visit->doTrackPageView('page title')); + } +} diff --git a/tests/PHPUnit/Fixtures/SomeVisitsWithLongUrls.php b/tests/PHPUnit/Fixtures/SomeVisitsWithLongUrls.php new file mode 100644 index 0000000000..d0335f45db --- /dev/null +++ b/tests/PHPUnit/Fixtures/SomeVisitsWithLongUrls.php @@ -0,0 +1,102 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site and tracks 7 visits w/ some long-ish urls (as page urls and + * referrer urls). + */ +class Test_Piwik_Fixture_SomeVisitsWithLongUrls extends Test_Piwik_BaseFixture +{ + public $dateTime = '2010-03-06 01:22:33'; + public $idSite = 1; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + // tests run in UTC, the Tracker in UTC + $dateTime = $this->dateTime; + $idSite = $this->idSite; + + // Visit 1: keyword and few URLs + $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useThirdPartyCookie = 1); + $t->setUrlReferrer('http://bing.com/search?q=Hello world'); + + // Generate a few page views that will be truncated + $t->setUrl('http://example.org/category/Page1'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page2'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page3'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page3'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page4'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page4'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page4'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category.htm'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/page.htm'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/index.htm'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/page.htm'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/page.htm'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/contact.htm'); + self::checkResponse($t->doTrackPageView('Hello')); + + // VISIT 2 = Another keyword + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); + $t->setUrlReferrer('http://www.google.com.vn/url?q=Salut'); + self::checkResponse($t->doTrackPageView('incredible title!')); + + // Visit 3 = Another keyword + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); + $t->setUrlReferrer('http://www.google.com.vn/url?q=Kia Ora'); + self::checkResponse($t->doTrackPageView('incredible title!')); + + // Visit 4 = Kia Ora again + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(3)->getDatetime()); + $t->setUrlReferrer('http://www.google.com.vn/url?q=Kia Ora'); + self::checkResponse($t->doTrackPageView('incredible title!')); + + // Visit 5 = Another search engine + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(4)->getDatetime()); + $t->setUrlReferrer('http://nz.search.yahoo.com/search?p=Kia Ora'); + self::checkResponse($t->doTrackPageView('incredible title!')); + + // Visit 6 = Another search engine + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(5)->getDatetime()); + $t->setUrlReferrer('http://images.search.yahoo.com/search/images;_ylt=A2KcWcNKJzF?p=Kia%20Ora%20'); + self::checkResponse($t->doTrackPageView('incredible title!')); + + // Visit 7 = Another search engine + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(6)->getDatetime()); + $t->setUrlReferrer('http://nz.bing.com/images/search?q=+++Kia+ora+++'); + self::checkResponse($t->doTrackPageView('incredible title!')); + } +} diff --git a/tests/PHPUnit/Fixtures/SomeVisitsWithNonUnicodePageTitles.php b/tests/PHPUnit/Fixtures/SomeVisitsWithNonUnicodePageTitles.php new file mode 100644 index 0000000000..b87111433b --- /dev/null +++ b/tests/PHPUnit/Fixtures/SomeVisitsWithNonUnicodePageTitles.php @@ -0,0 +1,97 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one website and some visits with non unicode page titles. + */ +class Test_Piwik_Fixture_SomeVisitsWithNonUnicodePageTitles extends Test_Piwik_BaseFixture +{ + public $idSite1 = 1; + public $dateTime = '2010-01-03 11:22:33'; + + public function setUp() + { + $this->setUpWebsites(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + /** + * One site with custom search parameters, + * One site using default search parameters, + * One site with disabled site search + */ + private function setUpWebsites() + { + Piwik_SitesManager_API::getInstance()->setGlobalSearchParameters($searchKeywordParameters='gkwd', $searchCategoryParameters='gcat'); + self::createWebsite(Piwik_Date::factory($this->dateTime)->getDatetime(), 0, "Site 1 - Site search", $siteurl=false, $search=1, $searchKwd='q,mykwd,p', $searchCat='cats' ); + } + + private function trackVisits() + { + $idSite1 = $this->idSite1; + $dateTime = $this->dateTime; + + self::assertTrue(function_exists('mb_check_encoding'), ' check mb_check_encoding '); + self::assertTrue(function_exists('mb_convert_encoding'), ' check mb_convert_encoding '); + + // Visitor site1 + $visitor = self::getTracker($idSite1, $dateTime, $defaultInit = true); + + // Test w/ iso-8859-15 + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); + $visitor->setUrlReferrer('http://anothersite.com/whatever.html?whatever=Ato%FC'); + // Also testing that the value is encoded when passed as an array + $visitor->setUrl('http://example.org/index.htm?random=param&mykwd[]=Search 2%FC&test&cats= Search Kategory &search_count=INCORRECT!'); + $visitor->setPageCharset('iso-8859-15'); + self::checkResponse($visitor->doTrackPageView('Site Search results')); + $visitor->setPageCharset(''); + + // Test w/ windows-1251 + $visitor = self::getTracker($idSite1, $dateTime, $defaultInit = true); + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); + $visitor->setUrlReferrer('http://anothersite.com/whatever.html?txt=%EC%E5%F8%EA%EE%E2%FB%E5'); + $visitor->setUrl('http://example.org/page/index.htm?whatever=%EC%E5%F8%EA%EE%E2%FB%E5'); + $visitor->setPageCharset('windows-1251'); + self::checkResponse($visitor->doTrackPageView('Page title is always UTF-8')); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); + $nonUnicodeKeyword = '%EC%E5%F8%EA%EE%E2%FB%E5'; + $visitor->setUrl('http://example.org/page/index.htm?q='.$nonUnicodeKeyword); + $visitor->setPageCharset('windows-1251'); + self::checkResponse($visitor->doTrackPageView('Site Search')); + + + // Test URL with non unicode Site Search keyword + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.5)->getDatetime()); + //TESTS: on jenkins somehow the "<-was here" was cut off so removing this test case and simply append the wrong keyword +// $visitor->setUrl('http://example.org/page/index.htm?q=non unicode keyword %EC%E5%F8%EAe%EE%E2%FBf%E5 <-was here'); + $visitor->setUrl('http://example.org/page/index.htm?q=non unicode keyword %EC%E5%F8%EA%EE%E2%FB%E5'); + $visitor->setPageCharset('utf-8'); + self::checkResponse($visitor->doTrackPageView('Site Search')); + + + $visitor->setPageCharset(''); + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.5)->getDatetime()); + $visitor->setUrl('http://example.org/exit-page'); + self::checkResponse($visitor->doTrackPageView('Page title is always UTF-8')); + + // Test set invalid page char set + $visitor = self::getTracker($idSite1, $dateTime, $defaultInit = true); + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); + $visitor->setUrlReferrer('http://anothersite.com/whatever.html'); + $visitor->setUrl('http://example.org/index.htm?random=param&mykwd=a+keyword&test&cats= Search Kategory &search_count=INCORRECT!'); + $visitor->setPageCharset('GTF-42'); // galactic transformation format + self::checkResponse($visitor->doTrackPageView('Site Search results')); + $visitor->setPageCharset(''); + } +} diff --git a/tests/PHPUnit/Fixtures/ThreeGoalsOnePageview.php b/tests/PHPUnit/Fixtures/ThreeGoalsOnePageview.php new file mode 100644 index 0000000000..4bd1586509 --- /dev/null +++ b/tests/PHPUnit/Fixtures/ThreeGoalsOnePageview.php @@ -0,0 +1,59 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Fixture that adds one site with three goals and tracks one pageview & one manual + * goal conversion. + */ +class Test_Piwik_Fixture_ThreeGoalsOnePageview extends Test_Piwik_BaseFixture +{ + public $dateTime = '2009-01-04 00:11:42'; + public $idSite = 1; + public $idGoal = 1; + public $idGoal2 = 2; + public $idGoal3 = 3; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime, $ecommerce = 1); + Piwik_Goals_API::getInstance()->addGoal( + $this->idSite, 'Goal 1 - Thank you', 'title', 'Thank you', 'contains', $caseSensitive = false, + $revenue = 10, $allowMultipleConversions = 1 + ); + + Piwik_Goals_API::getInstance()->addGoal( + $this->idSite, 'Goal 2 - Hello', 'url', 'hellow', 'contains', $caseSensitive = false, + $revenue = 10, $allowMultipleConversions = 0 + ); + + Piwik_Goals_API::getInstance()->addGoal($this->idSite, 'triggered js', 'manually', '', ''); + } + + private function trackVisits() + { + $t = self::getTracker($this->idSite, $this->dateTime, $defaultInit = true); + + // Record 1st page view + $t->setUrl('http://example.org/index.htm'); + self::checkResponse($t->doTrackPageView('incredible title!')); + + $t->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.3)->getDatetime()); + self::checkResponse($t->doTrackGoal($this->idGoal3, $revenue = 42.256)); + } +} diff --git a/tests/PHPUnit/Fixtures/ThreeSitesWithManyVisitsWithSiteSearch.php b/tests/PHPUnit/Fixtures/ThreeSitesWithManyVisitsWithSiteSearch.php new file mode 100644 index 0000000000..8f02a2d875 --- /dev/null +++ b/tests/PHPUnit/Fixtures/ThreeSitesWithManyVisitsWithSiteSearch.php @@ -0,0 +1,191 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds three websites with different site search configurations and adds + * several visits to each of them. + */ +class Test_Piwik_Fixture_ThreeSitesWithManyVisitsWithSiteSearch extends Test_Piwik_BaseFixture +{ + public $idSite1 = 1; + public $idSite2 = 2; + public $idSite3 = 3; + public $dateTime = '2010-01-03 11:22:33'; + + public function setUp() + { + self::setUpWebsites(); + self::trackVisits(); + } + + public function tearDown() + { + // empty + } + + /** + * One site with custom search parameters, + * One site using default search parameters, + * One site with disabled site search + */ + protected function setUpWebsites() + { + Piwik_SitesManager_API::getInstance()->setGlobalSearchParameters($searchKeywordParameters='gkwd', $searchCategoryParameters='gcat'); + self::createWebsite(Piwik_Date::factory($this->dateTime)->subHour(200)->getDatetime(), 0, "Site 1 - Site search", $siteurl=false, $search=1, $searchKwd='q,mykwd,p', $searchCat='cats' ); + self::createWebsite(Piwik_Date::factory($this->dateTime)->subHour(400)->getDatetime(), 0, "Site 2 - Site search use default", $siteurl = false, $search=1, $searchKwd='', $searchCat='' ); + self::createWebsite(Piwik_Date::factory($this->dateTime)->subHour(600)->getDatetime(), 0, "Site 3 - No site search", $siteurl = false, $search=0); + } + + protected function trackVisits() + { + $this->recordVisitorsSite1(); + $this->recordVisitorSite2(); + $this->recordVisitorSite3(); + } + + protected function recordVisitorsSite1() + { + // - + // Visitor site1 + $visitor = self::getTracker($this->idSite1, $this->dateTime, $defaultInit = true); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.2)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?q=Search 1 '); + self::checkResponse($visitor->doTrackPageView('Site Search results')); + + // Normal page view + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.22)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm'); + self::checkResponse($visitor->doTrackPageView('Im just a page')); + + // IS_FOLLOWING_SEARCH: Not this time + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.23)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?random=PAGEVIEW, NOT SEARCH&mykwd=&IS_FOLLOWING_SEARCH ONCE'); + self::checkResponse($visitor->doTrackPageView('This is a pageview, not a Search - IS_FOLLOWING_SEARCH ONCE')); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.25)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?standard=query&but=also#hash&q='.urlencode('Search 1')); + self::checkResponse($visitor->doTrackPageView('Site Search results - URL Fragment')); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.26)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm#q=Search 1&search_count=10'); + self::checkResponse($visitor->doTrackPageView('Site Search results - URL Fragment')); + + // &search_count=0 so it's a "No Result" keyword, but it will not appear in the report, because it also has other seraches with results + // and the archiving does a MAX() + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.27)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?hello=world#q=Search 1&search_count=0'); + self::checkResponse($visitor->doTrackPageView('Site Search results - URL Fragment')); + + // Testing with non urlencoded values + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.3)->getDatetime()); + // ALso testing that array[] notation is detected + $visitor->setUrl('http://example.org/index.htm?random=param&mykwd[]=Search 2&test&cats= Search Category &search_count=INCORRECT!'); + self::checkResponse($visitor->doTrackPageView('Site Search results')); + + // Testing with urlencoded values + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.32)->getDatetime()); + // Also testing with random case 'myKwd' + $visitor->setUrl('http://example.org/index.htm?random=param&myKwd=Search 1&test&cats='.urlencode(' Search Category '). ' &search_count=0'); + self::checkResponse($visitor->doTrackPageView('Site Search results')); + + // IS_FOLLOWING_SEARCH: Yes + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.35)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?random=PAGEVIEW, NOT SEARCH&mykwd=&IS_FOLLOWING_SEARCH ONCE'); + self::checkResponse($visitor->doTrackPageView('This is a pageview, not a Search - IS_FOLLOWING_SEARCH ONCE')); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.4)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?gkwd=SHOULD be a PageView, NOT a search'); + self::checkResponse($visitor->doTrackPageView('Pageview, not search')); + + $visitor->setUrl('http://example.org/hello?THIS IS A SITE SEARCH TRACKING API, NOT PAGEVIEW!'); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(24.41)->getDatetime()); + self::checkResponse($visitor->doTrackSiteSearch("Keyword - Tracking API")); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(24.42)->getDatetime()); + self::checkResponse($visitor->doTrackSiteSearch("Keyword - Tracking API", "Category", $count = 5)); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(24.43)->getDatetime()); + self::checkResponse($visitor->doTrackSiteSearch("No Result Keyword!", "Bad No Result Category :(", $count = 0)); + + // Keyword in iso-8859-15 charset with funny character + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(24.5)->getDatetime()); + $visitor->setPageCharset('iso-8859-15'); + $visitor->setUrl('http://example.org/index.htm?q=Final%20t%FCte%20Keyword%20Searched%20for%20now&search_count=10'); + self::checkResponse($visitor->doTrackPageView(false)); + + // - + // Visitor BIS + $visitorB = self::getTracker($this->idSite1, $this->dateTime, $defaultInit = true); + $visitorB->setIp('156.66.6.66'); + $visitorB->setResolution(1600, 1000); + + $visitorB->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(2.26)->getDatetime()); + $visitorB->setUrl('http://example.org/index.htm#q=' . urlencode('No Result Keyword!') . '&search_count=0'); + self::checkResponse($visitorB->doTrackPageView('Site Search results - URL Fragment')); + + $visitorB->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(2.27)->getDatetime()); + $visitorB->setUrl('http://example.org/index.htm?hello=world#q=Search 1&search_count=10'); + self::checkResponse($visitorB->doTrackPageView('Site Search results - URL Fragment')); + + $visitorB->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(2.3)->getDatetime()); + $visitorB->setUrl('http://example.org/index.htm?random=param&mykwd=Search 2&test&cats= Search Category &search_count=10'); + self::checkResponse($visitorB->doTrackPageView('Site Search results')); + } + + protected function recordVisitorSite3() + { // - + // Third new visitor on Idsite 3 + $visitor = self::getTracker($this->idSite3, $this->dateTime, $defaultInit = true); + $visitor->setResolution(1801, 1301); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.2)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?q=Search 1&IsPageView=1'); + $visitor->setCustomVariable(1, 'test cvar name', 'test cvar value'); + self::checkResponse($visitor->doTrackPageView('IsPageView')); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.35)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?gkwd=test not a keyword&gcat=Cat not but not keyword, so this is not search'); + self::checkResponse($visitor->doTrackPageView('This is a pageview, not a Search')); + + // Testing UTF8 Title & URL + $crazyTitle = '%2C%20%C3%8Dslenska%2C%20Italiano%2C%20%E6%97%A5%E6%9C%AC%E8%AA%9E%2C%20%E1%83%A5%E1%83%90%E1%83%A0%E1%83%97%E1%83%A3%E1%83%9A%E1%83%98%2C%20%ED%95%9C%EA%B5%AD%EC%96%B4%2C%20Lietuvi%C5%B3%2C%20Latvie%C5%A1u%2C%20Norsk%20(bokm%C3%A5l)%2C%20Nederlands%2C%20Norsk%20(nynorsk)%2C%20Polski%2C%20Portugu%C3%AAs%20brasileiro%2C%20Portugu%C3%AAs%2C%20Rom%C3%A2n%C4%83%2C%20%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9%2C%20Slovensky%2C%20Sloven%C5%A1%C4%8Dina%2C%20Shqip%2C%20Srpski%2C%20Svenska%2C%20%E0%B0%A4%E0%B1%86%E0%B0%B2%E0%B1%81%E0%B0%97%E0%B1%81%2C%20%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B9%84%E0%B8%97%E0%B8%A2%2C%20T%C3%BCrk%C3%A7e%2C%20%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B0%2C%20%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87%2C%20%E7%B9%81%E9%AB%94%E4%B8%AD%E6%96%87.'; + $visitor->setUrl('http://example.org/index.htm?' . $crazyTitle); + self::checkResponse($visitor->doTrackPageView('Pageview: ' . $crazyTitle)); + } + + protected function recordVisitorSite2() + { + $visitor = self::getTracker($this->idSite2, $this->dateTime, $defaultInit = true); + $visitor->setResolution(801, 301); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.2)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?q=Search 1&IsPageView=1'); + self::checkResponse($visitor->doTrackPageView('IsPageView')); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.35)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?random=PAGEVIEW, NOT SEARCH&gcat=Cat not but not keyword, so this is not search'); + self::checkResponse($visitor->doTrackPageView('This is a pageview, not a Search')); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.4)->getDatetime()); + $visitor->setUrl('http://example.org/index.htm?gkwd=SHOULD be a Search with no result!&search_count=0'); + self::checkResponse($visitor->doTrackPageView('This is a Search')); + + // Testing UTF8 keywords + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.45)->getDatetime()); + $crazySearchTerm = 'You%20can%20use%20Piwik%20in%3A%20%E1%8A%A0%E1%88%9B%E1%88%AD%E1%8A%9B%2C%20%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9%2C%20%D0%91%D0%B5%D0%BB%D0%B0%D1%80%D1%83%D1%81%D0%BA%D0%B0%D1%8F%2C%20%D0%91%D1%8A%D0%BB%D0%B3%D0%B0%D1%80%D1%81%D0%BA%D0%B8%2C%20Catal%C3%A0%2C%20%C4%8Cesky%2C%20Dansk%2C%20Deutsch%2C%20%CE%95%CE%BB%CE%BB%CE%B7%CE%BD%CE%B9%CE%BA%CE%AC%2C%20English%2C%20Espa%C3%B1ol%2C%20Eesti%20keel%2C%20Euskara%2C%20%D9%81%D8%A7%D8%B1%D8%B3%DB%8C%2C%20Suomi%2C%20Fran%C3%A7ais%2C%20Galego%2C%20%D7%A2%D7%91%D7%A8%D7%99%D7%AA%2C%20Magyar%2C%20Bahasa%20Indonesia%2C%20%C3%8Dslenska%2C%20Italiano%2C%20%E6%97%A5%E6%9C%AC%E8%AA%9E%2C%20%E1%83%A5%E1%83%90%E1%83%A0%E1%83%97%E1%83%A3%E1%83%9A%E1%83%98%2C%20%ED%95%9C%EA%B5%AD%EC%96%B4%2C%20Lietuvi%C5%B3%2C%20Latvie%C5%A1u%2C%20Norsk%20(bokm%C3%A5l)%2C%20Nederlands%2C%20Norsk%20(nynorsk)%2C%20Polski%2C%20Portugu%C3%AAs%20brasileiro%2C%20Portugu%C3%AAs%2C%20Rom%C3%A2n%C4%83%2C%20%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9%2C%20Slovensky%2C%20Sloven%C5%A1%C4%8Dina%2C%20Shqip%2C%20Srpski%2C%20Svenska%2C%20%E0%B0%A4%E0%B1%86%E0%B0%B2%E0%B1%81%E0%B0%97%E0%B1%81%2C%20%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B9%84%E0%B8%97%E0%B8%A2%2C%20T%C3%BCrk%C3%A7e%2C%20%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B0%2C%20%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87%2C%20%E7%B9%81%E9%AB%94%E4%B8%AD%E6%96%87.'; + $visitor->setUrl('http://example.org/index.htm?gkwd=' . $crazySearchTerm . '&gcat=' . $crazySearchTerm . '&search_count=1'); + self::checkResponse($visitor->doTrackPageView('Site Search with 1 result')); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($this->dateTime)->addHour(0.5)->getDatetime()); + self::checkResponse($visitor->doTrackSiteSearch("No Result Keyword!", "Bad No Result Category bis :(", $count = 0)); + return array($defaultInit, $visitor); + } +} + diff --git a/tests/PHPUnit/Fixtures/TwoSitesEcommerceOrderWithItems.php b/tests/PHPUnit/Fixtures/TwoSitesEcommerceOrderWithItems.php new file mode 100644 index 0000000000..543b2e29f4 --- /dev/null +++ b/tests/PHPUnit/Fixtures/TwoSitesEcommerceOrderWithItems.php @@ -0,0 +1,186 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds two sites and tracks some visits with ecommerce orders. + */ +class Test_Piwik_Fixture_TwoSitesEcommerceOrderWithItems extends Test_Piwik_BaseFixture +{ + public $dateTime = '2011-04-05 00:11:42'; + public $idSite = 1; + public $idSite2 = 2; + public $idGoalStandard = 1; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + self::setUpScheduledReports($this->idSite); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime, $ecommerce = 1); + self::createWebsite($this->dateTime); + Piwik_Goals_API::getInstance()->addGoal( + $this->idSite, 'title match, triggered ONCE', 'title', 'incredible', 'contains', + $caseSensitive = false, $revenue = 10, $allowMultipleConversions = true + ); + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + $idSite2 = $this->idSite2; + + $t = self::getTracker($idSite, $dateTime, $defaultInit = true); + // VISIT NO 1 + $t->setUrl('http://example.org/index.htm'); + $category = 'Electronics & Cameras'; + $price = 1111.11111; + + // VIEW product page + $t->setEcommerceView('SKU2', 'PRODUCT name', $category, $price); + $t->setCustomVariable(5, 'VisitorType', 'NewLoggedOut', 'visit'); + $t->setCustomVariable(4, 'ValueIsZero', '0', 'visit'); + self::assertEquals(array('_pks', 'SKU2'), $t->getCustomVariable(3, 'page')); + self::assertEquals(array('_pkn', 'PRODUCT name'), $t->getCustomVariable(4, 'page')); + self::assertEquals(array('_pkc', $category), $t->getCustomVariable(5, 'page')); + self::assertEquals(array('_pkp', $price), $t->getCustomVariable(2, 'page')); + self::assertEquals(array('VisitorType', 'NewLoggedOut'), $t->getCustomVariable(5, 'visit')); + self::checkResponse($t->doTrackPageView('incredible title!')); + + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); + $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $category, $price = 666); + self::checkResponse($t->doTrackPageView('Another Product page')); + + // Note: here testing to pass a timestamp to the tracking API rather than the datetime string + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getTimestampUTC()); + $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', ''); + self::checkResponse($t->doTrackPageView('Another Product page with no category')); + + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); + $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $categories = array('Multiple Category 1', '', 0, 'Multiple Category 2', 'Electronics & Cameras', 'Multiple Category 4', 'Multiple Category 5', 'SHOULD NOT BE REPORTEDSSSSSSSSSSSSSSssssssssssssssssssssssssssstttttttttttttttttttttttuuuu!')); + self::checkResponse($t->doTrackPageView('Another Product page with multiple categories')); + + // VISIT NO 2 + + // Fake the returning visit cookie + $t->setDebugStringAppend("&_idvc=2"); + + // VIEW category page + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.6)->getDatetime()); + $t->setEcommerceView('', '', $category); + self::checkResponse($t->doTrackPageView('Looking at ' . $category . ' page with a page level custom variable')); + + // VIEW category page again + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.7)->getDatetime()); + $t->setEcommerceView('', '', $category); + self::checkResponse($t->doTrackPageView('Looking at ' . $category . ' page again')); + + // VIEW product page + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.8)->getDatetime()); + $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $category = 'Electronics & Cameras', $price = 666); + self::checkResponse($t->doTrackPageView('Looking at product page')); + + // ADD TO CART + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.9)->getDatetime()); + $t->setCustomVariable(3, 'VisitorName', 'Great name!', 'visit'); + $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $category = 'Electronics & Cameras', $price = 500, $quantity = 1); + $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $category = 'Electronics & Cameras', $price = 500, $quantity = 2); + $t->addEcommerceItem($sku = 'SKU WILL BE DELETED', $name = 'BLABLA DELETED', $category = '', $price = 5000000, $quantity = 20); + self::checkResponse($t->doTrackEcommerceCartUpdate($grandTotal = 1000)); + + // ORDER NO 1 + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); + $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $categories, $price = 500, $quantity = 2); + $t->addEcommerceItem($sku = 'ANOTHER SKU HERE', $name = 'PRODUCT name BIS', $category = '', $price = 100, $quantity = 6); + self::checkResponse($t->doTrackEcommerceOrder($orderId = '937nsjusu 3894', $grandTotal = 1111.11, $subTotal = 1000, $tax = 111, $shipping = 0.11, $discount = 666)); + + // ORDER NO 2 + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2.1)->getDatetime()); + $t->addEcommerceItem($sku = 'SKU2', $name = 'Canon SLR', $category = 'Electronics & Cameras', $price = 1500, $quantity = 1); + // Product bought with empty category + $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', '', $price = 11.22, $quantity = 1); + + // test to delete all custom vars, they should be copied from visits + // This is a frequent use case: ecommerce shops tracking the order from backoffice + // without passing the custom variable 1st party cookie along since it's not known by back office + $visitorCustomVarSave = $t->visitorCustomVar; + $t->visitorCustomVar = false; + self::checkResponse($t->doTrackEcommerceOrder($orderId = '1037nsjusu4s3894', $grandTotal = 2000, $subTotal = 1500, $tax = 400, $shipping = 100, $discount = 0)); + $t->visitorCustomVar = $visitorCustomVarSave; + + // ORDER SHOULD DEDUPE + // Refresh the page with the receipt for the second order, should be ignored + // we test that both the order, and the products, are not updated on subsequent "Receipt" views + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2.2)->getDatetime()); + $t->addEcommerceItem($sku = 'SKU2', $name = 'Canon SLR NOT!', $category = 'Electronics & Cameras NOT!', $price = 15000000000, $quantity = 10000); + self::checkResponse($t->doTrackEcommerceOrder($orderId = '1037nsjusu4s3894', $grandTotal = 20000000, $subTotal = 1500, $tax = 400, $shipping = 100, $discount = 0)); + + // Leave with an opened cart + // No category + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2.3)->getDatetime()); + $t->addEcommerceItem($sku = 'SKU IN ABANDONED CART ONE', $name = 'PRODUCT ONE LEFT in cart', $category = '', $price = 500.11111112, $quantity = 2); + self::checkResponse($t->doTrackEcommerceCartUpdate($grandTotal = 1000)); + + // Record the same visit leaving twice an abandoned cart + foreach (array(0, 5, 24) as $offsetHour) { + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.4)->getDatetime()); + // Also recording an order the day after + if ($offsetHour >= 24) { + $t->setDebugStringAppend("&_idvc=1"); + $t->addEcommerceItem($sku = 'SKU2', $name = 'Canon SLR', $category = 'Electronics & Cameras', $price = 1500, $quantity = 1); + self::checkResponse($t->doTrackEcommerceOrder($orderId = '1037nsjusu4s3894', $grandTotal = 20000000, $subTotal = 1500, $tax = 400, $shipping = 100, $discount = 0)); + } + + // VIEW PRODUCT PAGES + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.5)->getDatetime()); + $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT THREE LEFT in cart', $category = '', $price = 999); + self::checkResponse($t->doTrackPageView("View product left in cart")); + + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.55)->getDatetime()); + $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT THREE LEFT in cart', $category = '', $price = 333); + self::checkResponse($t->doTrackPageView("View product left in cart")); + + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.6)->getDatetime()); + $t->setEcommerceView($sku = 'SKU IN ABANDONED CART TWO', $name = 'PRODUCT TWO LEFT in cart', $category = 'Category TWO LEFT in cart'); + self::checkResponse($t->doTrackPageView("View product left in cart")); + + // ABANDONED CART + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.7)->getDatetime()); + $t->addEcommerceItem($sku = 'SKU IN ABANDONED CART ONE', $name = 'PRODUCT ONE LEFT in cart', $category = '', $price = 500.11111112, $quantity = 1); + $t->addEcommerceItem($sku = 'SKU IN ABANDONED CART TWO', $name = 'PRODUCT TWO LEFT in cart', $category = 'Category TWO LEFT in cart', $price = 1000, $quantity = 2); + $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT THREE LEFT in cart', $category = 'Electronics & Cameras', $price = 10, $quantity = 1); + self::checkResponse($t->doTrackEcommerceCartUpdate($grandTotal = 2510.11111112)); + } + + // One more Ecommerce order to check weekly archiving works fine on orders + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(30.7)->getDatetime()); + $t->addEcommerceItem($sku = 'TRIPOD SKU', $name = 'TRIPOD - bought day after', $category = 'Tools', $price = 100, $quantity = 2); + self::checkResponse($t->doTrackEcommerceOrder($orderId = '666', $grandTotal = 240, $subTotal = 200, $tax = 20, $shipping = 20, $discount = 20)); + + // One more Ecommerce order, without any product in it, because we still track orders without products + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(30.8)->getDatetime()); + self::checkResponse($t->doTrackEcommerceOrder($orderId = '777', $grandTotal = 10000)); + + // testing the same order in a different website should record + $t = self::getTracker($idSite2, $dateTime, $defaultInit = true); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(30.9)->getDatetime()); + $t->addEcommerceItem($sku = 'TRIPOD SKU', $name = 'TRIPOD - bought day after', $category = 'Tools', $price = 100, $quantity = 2); + self::checkResponse($t->doTrackEcommerceOrder($orderId = '777', $grandTotal = 250)); + //------------------------------------- End tracking + } +} + diff --git a/tests/PHPUnit/Fixtures/TwoSitesTwoVisitorsDifferentDays.php b/tests/PHPUnit/Fixtures/TwoSitesTwoVisitorsDifferentDays.php new file mode 100644 index 0000000000..3156b12eba --- /dev/null +++ b/tests/PHPUnit/Fixtures/TwoSitesTwoVisitorsDifferentDays.php @@ -0,0 +1,133 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds two websites and tracks visits from two visitors on different days. + */ +class Test_Piwik_Fixture_TwoSitesTwoVisitorsDifferentDays extends Test_Piwik_BaseFixture +{ + public $idSite1 = 1; + public $idSite2 = 2; + public $idGoal1 = 1; + public $idGoal2 = 2; + public $dateTime = '2010-01-03 11:22:33'; + + public $allowConversions = false; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + self::setUpScheduledReports($this->idSite1); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + // tests run in UTC, the Tracker in UTC + $ecommerce = $this->allowConversions ? 1 : 0; + + self::createWebsite($this->dateTime, $ecommerce, "Site 1"); + self::createWebsite($this->dateTime, 0, "Site 2"); + + if ($this->allowConversions) { + Piwik_Goals_API::getInstance()->addGoal($this->idSite1, 'all', 'url', 'http', 'contains', false, 5); + Piwik_Goals_API::getInstance()->addGoal($this->idSite2, 'all', 'url', 'http', 'contains'); + } + + Piwik_SitesManager_API::getInstance()->updateSite( + $this->idSite1, "Site 1", $urls = null, $ecommerce = null, $siteSearch = null, + $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, + $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, + $startDate = null, $excludedUserAgents = null, $keepURLFragments = 2); // KEEP_URL_FRAGMENT_NO No for idSite 1 + Piwik_SitesManager_API::getInstance()->updateSite( + $this->idSite2, "Site 2", $urls = null, $ecommerce = null, $siteSearch = null, + $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, + $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, + $startDate = null, $excludedUserAgents = null, $keepURLFragments = 1); // KEEP_URL_FRAGMENT_YES Yes for idSite 2 + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite1; + $idSite2 = $this->idSite2; + + // - + // First visitor on Idsite 1: two page views + $datetimeSpanOverTwoDays = '2010-01-03 23:55:00'; + $visitorA = self::getTracker($idSite, $datetimeSpanOverTwoDays, $defaultInit = true); + $visitorA->setUrlReferrer('http://referer.com/page.htm?param=valuewith some spaces'); + $visitorA->setUrl('http://example.org/index.htm#ignoredFragment'); + $visitorA->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($datetimeSpanOverTwoDays)->getTimestamp(); + self::checkResponse($visitorA->doTrackPageView('first page view')); + + $visitorA->setForceVisitDateTime(Piwik_Date::factory($datetimeSpanOverTwoDays)->addHour(0.1)->getDatetime()); + // testing with empty URL and empty page title + $visitorA->setUrl(' '); + self::checkResponse($visitorA->doTrackPageView(' ')); + + // - + // Second new visitor on Idsite 1: one page view + $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); + $visitorB->enableBulkTracking(); + $visitorB->setTokenAuth(self::getTokenAuth()); + $visitorB->setIp('100.52.156.83'); + $visitorB->setResolution(800, 300); + $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); + $visitorB->setUrlReferrer(''); + $visitorB->setUserAgent('Opera/9.63 (Windows NT 5.1; U; en) Presto/2.1.1'); + $visitorB->setUrl('http://example.org/products'); + $visitorB->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($dateTime)->addHour(1)->getTimestamp(); + self::assertTrue($visitorB->doTrackPageView('first page view')); + + // - + // Second visitor again on Idsite 1: 2 page views 2 days later, 2010-01-05 + $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->getDatetime()); + // visitor_returning is set to 1 only when visit count more than 1 + // Temporary, until we implement 1st party cookies in PiwikTracker + $visitorB->DEBUG_APPEND_URL .= '&_idvc=2&_viewts=' . Piwik_Date::factory($dateTime)->getTimestamp(); + + $visitorB->setUrlReferrer('http://referer.com/Other_Page.htm'); + $visitorB->setUrl('http://example.org/index.htm'); + self::assertTrue($visitorB->doTrackPageView('second visitor/two days later/a new visit')); + // Second page view 6 minutes later + $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.1)->getDatetime()); + $visitorB->setUrl('http://example.org/thankyou'); + self::assertTrue($visitorB->doTrackPageView('second visitor/two days later/second page view')); + + // testing a strange combination causing an error in r3767 + $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.2)->getDatetime()); + self::assertTrue($visitorB->doTrackAction('mailto:test@example.org', 'link')); + $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.25)->getDatetime()); + self::assertTrue($visitorB->doTrackAction('mailto:test@example.org/strangelink', 'link')); + + // Actions.getPageTitle tested with this title + $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.25)->getDatetime()); + self::assertTrue($visitorB->doTrackPageView('Checkout / Purchasing...')); + self::checkResponse($visitorB->doBulkTrack()); + + // - + // First visitor on Idsite 2: one page view, with Website referer + $visitorAsite2 = self::getTracker($idSite2, Piwik_Date::factory($dateTime)->addHour(24)->getDatetime(), $defaultInit = true); + $visitorAsite2->setUserAgent('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)'); + $visitorAsite2->setUrlReferrer('http://only-homepage-referer.com/'); + $visitorAsite2->setUrl('http://example2.com/home#notIgnoredFragment#'); + $visitorAsite2->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($dateTime)->addHour(24)->getTimestamp(); + self::checkResponse($visitorAsite2->doTrackPageView('Website 2 page view')); + // test with invalid URL + $visitorAsite2->setUrl('this is invalid url'); + // and an empty title + self::checkResponse($visitorAsite2->doTrackPageView('')); + } +} + diff --git a/tests/PHPUnit/Fixtures/TwoSitesVisitsInPast.php b/tests/PHPUnit/Fixtures/TwoSitesVisitsInPast.php new file mode 100644 index 0000000000..2584eb8b46 --- /dev/null +++ b/tests/PHPUnit/Fixtures/TwoSitesVisitsInPast.php @@ -0,0 +1,104 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds two sites and tracks several visits all in the past. + */ +class Test_Piwik_Fixture_TwoSitesVisitsInPast extends Test_Piwik_BaseFixture +{ + public $dateTimeFirstDateWebsite1 = '2010-03-06 01:22:33'; + public $dateTimeDateInPastWebsite1 = '2010-01-06 01:22:33'; + public $dateTimeFirstDateWebsite2 = '2010-01-03 20:22:33'; + public $dateTimeDateInPastWebsite2 = '2009-10-30 01:22:33'; + public $idSite = 1; + public $idSite2 = 2; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + public function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTimeFirstDateWebsite1); + self::createWebsite($this->dateTimeFirstDateWebsite2); + } + + protected function trackVisits() + { + /** + * Track Visits normal date for the 2 websites + */ + // WEBSITE 1 + $t = self::getTracker($this->idSite, $this->dateTimeFirstDateWebsite1, $defaultInit = true); + $t->setUrl('http://example.org/category/Page1'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page2'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page3'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/Home'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/Contact'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/Contact/ThankYou'); + self::checkResponse($t->doTrackPageView('Hello')); + + // WEBSITE 2 + $t = self::getTracker($this->idSite2, $this->dateTimeFirstDateWebsite2, $defaultInit = true); + $t->setIp('156.15.13.12'); + $t->setUrl('http://example.org/category/Page1'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page2'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page3'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/Home'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/Contact'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/Contact/ThankYou'); + self::checkResponse($t->doTrackPageView('Hello')); + + /** + * Track visits in the past (before website creation date) for the 2 websites + */ + // WEBSITE1 + $t = self::getTracker($this->idSite, $this->dateTimeDateInPastWebsite1, $defaultInit = true); + $t->setIp('156.5.55.2'); + $t->setUrl('http://example.org/category/Page1'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page1'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page2'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Pagexx'); + self::checkResponse($t->doTrackPageView('Blabla')); + + // WEBSITE2 + $t = self::getTracker($this->idSite2, $this->dateTimeDateInPastWebsite2, $defaultInit = true); + $t->setIp('156.52.3.22'); + $t->setUrl('http://example.org/category/Page1'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page1'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Page2'); + self::checkResponse($t->doTrackPageView('Hello')); + $t->setUrl('http://example.org/category/Pageyy'); + self::checkResponse($t->doTrackPageView('Blabla')); + $t->setForceVisitDateTime(Piwik_Date::factory($this->dateTimeDateInPastWebsite2)->addHour(0.1)->getDatetime()); + $t->setUrl('http://example.org/category/Pageyy'); + self::checkResponse($t->doTrackPageView('Blabla')); + } +} diff --git a/tests/PHPUnit/Fixtures/TwoSitesWithAnnotations.php b/tests/PHPUnit/Fixtures/TwoSitesWithAnnotations.php new file mode 100644 index 0000000000..19d03b78e5 --- /dev/null +++ b/tests/PHPUnit/Fixtures/TwoSitesWithAnnotations.php @@ -0,0 +1,71 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * A fixture that adds two websites and annotations for each website. + */ +class Test_Piwik_Fixture_TwoSitesWithAnnotations extends Test_Piwik_BaseFixture +{ + public $dateTime = '2011-01-01 00:11:42'; + public $idSite1 = 1; + public $idSite2 = 2; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->addAnnotations(); + } + + public function tearDown() + { + // empty + } + + private function addAnnotations() + { + // create fake access for fake username + $access = new FakeAccess(); + FakeAccess::$superUser = true; + Zend_Registry::set('access', $access); + + // add two annotations per week for three months, starring every third annotation + // first month in 2011, second two in 2012 + $count = 0; + $dateStart = Piwik_Date::factory('2011-12-01'); + $dateEnd = Piwik_Date::factory('2012-03-01'); + while ($dateStart->getTimestamp() < $dateEnd->getTimestamp()) + { + $starred = $count % 3 == 0 ? 1 : 0; + $site1Text = "$count: Site 1 annotation for ".$dateStart->toString(); + $site2Text = "$count: Site 2 annotation for ".$dateStart->toString(); + + Piwik_Annotations_API::getInstance()->add($this->idSite1, $dateStart->toString(), $site1Text, $starred); + Piwik_Annotations_API::getInstance()->add($this->idSite2, $dateStart->toString(), $site2Text, $starred); + + $nextDay = $dateStart->addDay(1); + ++$count; + + $starred = $count % 3 == 0 ? 1 : 0; + $site1Text = "$count: Site 1 annotation for ".$nextDay->toString(); + $site2Text = "$count: Site 2 annotation for ".$nextDay->toString(); + + Piwik_Annotations_API::getInstance()->add($this->idSite1, $nextDay->toString(), $site1Text, $starred); + Piwik_Annotations_API::getInstance()->add($this->idSite2, $nextDay->toString(), $site2Text, $starred); + + $dateStart = $dateStart->addPeriod(1, 'WEEK'); + ++$count; + } + } + + private function setUpWebsitesAndGoals() + { + // add two websites + self::createWebsite($this->dateTime, $ecommerce = 1); + self::createWebsite($this->dateTime, $ecommerce = 1); + } +} diff --git a/tests/PHPUnit/Fixtures/TwoVisitsNoKeywordWithBot.php b/tests/PHPUnit/Fixtures/TwoVisitsNoKeywordWithBot.php new file mode 100644 index 0000000000..afb73d687d --- /dev/null +++ b/tests/PHPUnit/Fixtures/TwoVisitsNoKeywordWithBot.php @@ -0,0 +1,63 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site and tracks two visits. One visit is a bot and one has no keyword + * but is from a search engine. + */ +class Test_Piwik_Fixture_TwoVisitsNoKeywordWithBot extends Test_Piwik_BaseFixture +{ + public $dateTime = '2010-03-06 11:22:33'; + public $idSite = 1; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTime); + } + + private function trackVisits() + { + // tests run in UTC, the Tracker in UTC + $dateTime = $this->dateTime; + $idSite = $this->idSite; + $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useThirdPartyCookie = 1); + + // Also testing to record this as a bot while specifically allowing bots + $t->setUserAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); + $t->DEBUG_APPEND_URL .= '&bots=1'; + $t->DEBUG_APPEND_URL .= '&forceIpAnonymization=1'; + // VISIT 1 = Referrer is "Keyword not defined" + // Alsotrigger goal to check that attribution goes to this keyword + $t->setUrlReferrer('http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CC&url=http%3A%2F%2Fpiwik.org%2F&ei=&usg='); + $t->setUrl('http://example.org/this%20is%20cool!'); + self::checkResponse($t->doTrackPageView('incredible title!')); + $idGoal = Piwik_Goals_API::getInstance()->addGoal($idSite, 'triggered js', 'manually', '', ''); + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); + self::checkResponse($t->doTrackGoal($idGoal, $revenue = 42)); + + // VISIT 2 = Referrer has keyword, but the URL should be rewritten + // in Live Output to point to google search result page + $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); + $t->setUrlReferrer('http://www.google.com.vn/url?sa=t&rct=j&q=%3C%3E%26%5C%22the%20pdo%20extension%20is%20required%20for%20this%20adapter%20but%20the%20extension%20is%20not%20loaded&source=web&cd=4&ved=0FjAD&url=http%3A%2F%2Fforum.piwik.org%2Fread.php%3F2%2C1011&ei=y-HHAQ&usg=AFQjCN2-nt5_GgDeg&cad=rja'); + + // Test with empty title, that the output of Live is valid + self::checkResponse($t->doTrackPageView('')); + + } +} diff --git a/tests/PHPUnit/Fixtures/TwoVisitsWithCustomVariables.php b/tests/PHPUnit/Fixtures/TwoVisitsWithCustomVariables.php new file mode 100644 index 0000000000..12aa1b6213 --- /dev/null +++ b/tests/PHPUnit/Fixtures/TwoVisitsWithCustomVariables.php @@ -0,0 +1,140 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one site with two goals and tracks two visits with custom variables. + */ +class Test_Piwik_Fixture_TwoVisitsWithCustomVariables extends Test_Piwik_BaseFixture +{ + public $dateTime = '2010-01-03 11:22:33'; + public $idSite = 1; + public $idGoal1 = 1; + public $idGoal2 = 2; + public $visitorId = '61e8cc2d51fea26d'; + + public $useEscapedQuotes = true; + public $doExtraQuoteTests = true; + + public $resolutionWidthToUse = 1111; + public $resolutionHeightToUse = 222; + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + // tests run in UTC, the Tracker in UTC + self::createWebsite($this->dateTime); + Piwik_Goals_API::getInstance()->addGoal($this->idSite, 'triggered js', 'manually', '', ''); + Piwik_Goals_API::getInstance()->addGoal($this->idSite, 'second goal', 'manually', '', ''); + } + + private function trackVisits() + { + $dateTime = $this->dateTime; + $idSite = $this->idSite; + $idGoal = $this->idGoal1; + $idGoal2 = $this->idGoal2; + + $visitorA = self::getTracker($this->idSite, $this->dateTime, $defaultInit = true); + // Used to test actual referer + keyword position in Live! + $visitorA->setUrlReferrer(urldecode('http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB4QFjAA&url=http%3A%2F%2Fpiwik.org%2F&rct=j&q=this%20keyword%20should%20be%20ranked&ei=V8WfTePkKKLfiALrpZWGAw&usg=AFQjCNF_MGJRqKPvaKuUokHtZ3VvNG9ALw&sig2=BvKAdCtNixsmfNWXjsNyMw')); + + // no campaign, but a search engine to attribute the goal conversion to + $attribution = array( + '', + '', + 1302306504, + 'http://www.google.com/search?q=piwik&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a' + ); + $visitorA->setAttributionInfo(json_encode($attribution)); + + $visitorA->setResolution($this->resolutionWidthToUse, $this->resolutionHeightToUse); + + // At first, visitor custom var is set to LoggedOut + $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); + $visitorA->setUrl('http://example.org/homepage'); + $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); + self::checkResponse($visitorA->doTrackPageView('Homepage')); + self::checkResponse($visitorA->doTrackGoal($idGoal2)); + + // After login, set to LoggedIn, should overwrite previous value + $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); + $visitorA->setUrl('http://example.org/user/profile'); + $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedIn'); + $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = 'Loggedin', $scope = 'page'); + if ($this->useEscapedQuotes) { + $lookingAtProfile = 'looking at "profile page"'; + } else { + $lookingAtProfile = 'looking at profile page'; + } + $visitorA->setCustomVariable($id = 5, $name = 'Status user', $value = $lookingAtProfile, $scope = 'page'); + self::checkResponse($visitorA->doTrackPageView('Profile page')); + + $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE', $value = ''); + $visitorA->setCustomVariable($id = 1, $name = 'Language', $value = 'FR', $scope = 'page'); + $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE PAGE SCOPE', $value = '', $scope = 'page'); + $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = "looking at \"profile page\"", $scope = 'page'); + $visitorA->setCustomVariable($id = 3, $name = 'Value will be VERY long and truncated', $value = 'abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----'); + self::checkResponse($visitorA->doTrackPageView('Profile page for user *_)%')); + self::checkResponse($visitorA->doTrackGoal($idGoal)); + + if ($this->doExtraQuoteTests) { + $visitorA->setCustomVariable($id = 2, $name = 'var1', $value = 'looking at "profile page"', + $scope = 'page'); + $visitorA->setCustomVariable($id = 3, $name = 'var2', $value = '\'looking at "\profile page"\'', + $scope = 'page'); + $visitorA->setCustomVariable($id = 4, $name = 'var3', $value = '\\looking at "\profile page"\\', + $scope = 'page'); + self::checkResponse($visitorA->doTrackPageView('Concurrent page views')); + } + + // - + // Second new visitor on Idsite 1: one page view + $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); + if (!empty($this->visitorId)) + { + $visitorB->setVisitorId($this->visitorId); + } + $visitorB->setUrlReferrer(''); + + $attribution = array( + ' CAMPAIGN NAME -%20YEAH! ', + ' CAMPAIGN%20KEYWORD - RIGHT... ', + 1302306504, + 'http://www.example.org/test/really?q=yes' + ); + $visitorB->setAttributionInfo(json_encode($attribution)); + $visitorB->setResolution($this->resolutionWidthToUse, $this->resolutionHeightToUse); + $visitorB->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6'); + $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); + $visitorB->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); + $visitorB->setCustomVariable($id = 2, $name = 'Othercustom value which should be truncated abcdefghijklmnopqrstuvwxyz', $value = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'); + $visitorB->setCustomVariable($id = -2, $name = 'not tracked', $value = 'not tracked'); + $visitorB->setCustomVariable($id = 6, $name = 'not tracked', $value = 'not tracked'); + $visitorB->setCustomVariable($id = 6, $name = array('not tracked'), $value = 'not tracked'); + $visitorB->setUrl('http://example.org/homepage'); + self::checkResponse($visitorB->doTrackGoal($idGoal, 1000)); + + $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.1)->getDatetime()); + self::checkResponse($visitorB->doTrackPageView('Homepage')); + + // DIFFERENT test - + // testing that starting the visit with an outlink works (doesn't trigger errors) + $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); + self::checkResponse($visitorB->doTrackAction('http://test.com', 'link')); + } +} diff --git a/tests/PHPUnit/Fixtures/VisitsOverSeveralDays.php b/tests/PHPUnit/Fixtures/VisitsOverSeveralDays.php new file mode 100644 index 0000000000..ded57b1057 --- /dev/null +++ b/tests/PHPUnit/Fixtures/VisitsOverSeveralDays.php @@ -0,0 +1,98 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +/** + * Adds one website and tracks several visits from one visitor on + * different days that span about a month apart. + */ +class Test_Piwik_Fixture_VisitsOverSeveralDays extends Test_Piwik_BaseFixture +{ + public $dateTimes = array( + '2010-12-14 01:00:00', + '2010-12-15 01:00:00', + '2010-12-25 01:00:00', + '2011-01-15 01:00:00', + '2011-01-16 01:00:00', + ); + + public $idSite = 1; + public $idSite2 = 2; + + // one per visit + public $referrerUrls = array( + 'http://facebook.com/whatever', + 'http://www.facebook.com/another/path', + 'http://fb.me/?q=sdlfjs&n=slfjsd', + 'http://twitter.com/whatever2', + 'http://www.twitter.com/index?a=2334', + 'http://t.co/id/?y=dsfs', + 'http://www.flickr.com', + 'http://xanga.com', + 'http://skyrock.com', + 'http://mixi.jp', + ); + + public function setUp() + { + $this->setUpWebsitesAndGoals(); + $this->trackVisits(); + } + + public function tearDown() + { + // empty + } + + private function setUpWebsitesAndGoals() + { + self::createWebsite($this->dateTimes[0], $ecommerce = 0, $siteName = 'Site AAAAAA'); + self::createWebsite($this->dateTimes[0], $ecommerce = 0, $siteName = 'SITE BBbbBB'); + } + + private function trackVisits() + { + $dateTimes = $this->dateTimes; + $idSite = $this->idSite; + + $i = 0; + $ridx = 0; + foreach ($dateTimes as $dateTime) { + $i++; + $visitor = self::getTracker($idSite, $dateTime, $defaultInit = true); + // Fake the visit count cookie + $visitor->setDebugStringAppend("&_idvc=$i"); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); + $visitor->setUrl('http://example.org/homepage'); + $visitor->setUrlReferrer($this->referrerUrls[$ridx++]); + self::checkResponse($visitor->doTrackPageView('ou pas')); + + // Test change the IP, the visit should not be split but recorded to the same idvisitor + $visitor->setIp('200.1.15.22'); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); + $visitor->setUrl('http://example.org/news'); + self::checkResponse($visitor->doTrackPageView('ou pas')); + + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); + $visitor->setUrl('http://example.org/news'); + $visitor->setUrlReferrer($this->referrerUrls[$ridx++]); + self::checkResponse($visitor->doTrackPageView('ou pas')); + + + if($i <= 3 ) { + + $visitor = self::getTracker($this->idSite2, $dateTime, $defaultInit = true); + $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); + $visitor->setUrl('http://example.org/homepage'); + $visitor->setUrlReferrer($this->referrerUrls[$ridx-1]); + self::checkResponse($visitor->doTrackPageView('Second website')); + } + } + } +} diff --git a/tests/PHPUnit/Integration/AnnotationsTest.php b/tests/PHPUnit/Integration/AnnotationsTest.php index 18a813c6ad..112732731c 100755 --- a/tests/PHPUnit/Integration/AnnotationsTest.php +++ b/tests/PHPUnit/Integration/AnnotationsTest.php @@ -8,21 +8,7 @@ class AnnotationsTest extends IntegrationTestCase { - protected static $dateTime = '2011-01-01 00:11:42'; - protected static $idSite1 = 1; - protected static $idSite2 = 2; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::addAnnotations(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; public function getOutputPrefix() { @@ -31,27 +17,30 @@ class AnnotationsTest extends IntegrationTestCase public function getApiForTesting() { + $idSite1 = self::$fixture->idSite1; + $idSite2 = self::$fixture->idSite2; + return array( // get - array('Annotations.get', array('idSite' => self::$idSite1, + array('Annotations.get', array('idSite' => $idSite1, 'date' => '2012-01-01', 'periods' => 'day', 'otherRequestParameters' => array('idNote' => 1))), // getAll - array('Annotations.getAll', array('idSite' => self::$idSite1, + array('Annotations.getAll', array('idSite' => $idSite1, 'date' => '2011-12-01', 'periods' => array('day', 'week', 'month'))), - array('Annotations.getAll', array('idSite' => self::$idSite1, + array('Annotations.getAll', array('idSite' => $idSite1, 'date' => '2012-01-01', 'periods' => array('year'))), - array('Annotations.getAll', array('idSite' => self::$idSite1, + array('Annotations.getAll', array('idSite' => $idSite1, 'date' => '2012-03-01', 'periods' => array('week'), 'otherRequestParameters' => array('lastN' => 6), 'testSuffix' => '_lastN')), - array('Annotations.getAll', array('idSite' => self::$idSite1, + array('Annotations.getAll', array('idSite' => $idSite1, 'date' => '2012-01-15,2012-02-15', 'periods' => array('range'), 'otherRequestParameters' => array('lastN' => 6), @@ -62,18 +51,18 @@ class AnnotationsTest extends IntegrationTestCase 'testSuffix' => '_multipleSites')), // getAnnotationCountForDates - array('Annotations.getAnnotationCountForDates', array('idSite' => self::$idSite1, + array('Annotations.getAnnotationCountForDates', array('idSite' => $idSite1, 'date' => '2011-12-01', 'periods' => array('day', 'week', 'month'))), - array('Annotations.getAnnotationCountForDates', array('idSite' => self::$idSite1, + array('Annotations.getAnnotationCountForDates', array('idSite' => $idSite1, 'date' => '2012-01-01', 'periods' => array('year'))), - array('Annotations.getAnnotationCountForDates', array('idSite' => self::$idSite1, + array('Annotations.getAnnotationCountForDates', array('idSite' => $idSite1, 'date' => '2012-03-01', 'periods' => array('week'), 'otherRequestParameters' => array('lastN' => 6), 'testSuffix' => '_lastN')), - array('Annotations.getAnnotationCountForDates', array('idSite' => self::$idSite1, + array('Annotations.getAnnotationCountForDates', array('idSite' => $idSite1, 'date' => '2012-01-15,2012-02-15', 'periods' => array('range'), 'otherRequestParameters' => array('lastN' => 6), @@ -120,7 +109,7 @@ class AnnotationsTest extends IntegrationTestCase { try { - Piwik_Annotations_API::getInstance()->add(self::$idSite1, "invaliddate", "whatever"); + Piwik_Annotations_API::getInstance()->add(self::$fixture->idSite1, "invaliddate", "whatever"); $this->fail("add should fail when given invalid date"); } catch (Exception $ex) @@ -154,7 +143,7 @@ class AnnotationsTest extends IntegrationTestCase { try { - Piwik_Annotations_API::getInstance()->save(self::$idSite1, 0, "invaliddate"); + Piwik_Annotations_API::getInstance()->save(self::$fixture->idSite1, 0, "invaliddate"); $this->fail("save should fail when given an invalid date"); } catch (Exception $ex) @@ -171,7 +160,7 @@ class AnnotationsTest extends IntegrationTestCase { try { - Piwik_Annotations_API::getInstance()->save(self::$idSite1, -1); + Piwik_Annotations_API::getInstance()->save(self::$fixture->idSite1, -1); $this->fail("save should fail when given an invalid note id"); } catch (Exception $ex) @@ -205,7 +194,7 @@ class AnnotationsTest extends IntegrationTestCase { try { - Piwik_Annotations_API::getInstance()->delete(self::$idSite1, -1); + Piwik_Annotations_API::getInstance()->delete(self::$fixture->idSite1, -1); $this->fail("delete should fail when given an invalid site ID"); } catch (Exception $ex) @@ -239,7 +228,7 @@ class AnnotationsTest extends IntegrationTestCase { try { - Piwik_Annotations_API::getInstance()->get(self::$idSite1, -1); + Piwik_Annotations_API::getInstance()->get(self::$fixture->idSite1, -1); $this->fail("get should fail when given an invalid note ID"); } catch (Exception $ex) @@ -255,7 +244,7 @@ class AnnotationsTest extends IntegrationTestCase public function testSaveSuccess() { Piwik_Annotations_API::getInstance()->save( - self::$idSite1, 0, $date = '2011-04-01', $note = 'new note text', $starred = 1); + self::$fixture->idSite1, 0, $date = '2011-04-01', $note = 'new note text', $starred = 1); $expectedAnnotation = array( 'date' => '2011-04-01', @@ -265,7 +254,7 @@ class AnnotationsTest extends IntegrationTestCase 'idNote' => 0, 'canEditOrDelete' => true ); - $this->assertEquals($expectedAnnotation, Piwik_Annotations_API::getInstance()->get(self::$idSite1, 0)); + $this->assertEquals($expectedAnnotation, Piwik_Annotations_API::getInstance()->get(self::$fixture->idSite1, 0)); } /** @@ -274,7 +263,7 @@ class AnnotationsTest extends IntegrationTestCase */ public function testSaveNoChangesSuccess() { - Piwik_Annotations_API::getInstance()->save(self::$idSite1, 1); + Piwik_Annotations_API::getInstance()->save(self::$fixture->idSite1, 1); $expectedAnnotation = array( 'date' => '2011-12-02', @@ -284,7 +273,7 @@ class AnnotationsTest extends IntegrationTestCase 'idNote' => 1, 'canEditOrDelete' => true ); - $this->assertEquals($expectedAnnotation, Piwik_Annotations_API::getInstance()->get(self::$idSite1, 1)); + $this->assertEquals($expectedAnnotation, Piwik_Annotations_API::getInstance()->get(self::$fixture->idSite1, 1)); } /** @@ -293,11 +282,11 @@ class AnnotationsTest extends IntegrationTestCase */ public function testDeleteSuccess() { - Piwik_Annotations_API::getInstance()->delete(self::$idSite1, 1); + Piwik_Annotations_API::getInstance()->delete(self::$fixture->idSite1, 1); try { - Piwik_Annotations_API::getInstance()->get(self::$idSite1, 1); + Piwik_Annotations_API::getInstance()->get(self::$fixture->idSite1, 1); $this->fail("failed to delete annotation"); } catch (Exception $ex) @@ -345,8 +334,8 @@ class AnnotationsTest extends IntegrationTestCase // create fake access that denies user access $access = new FakeAccess(); FakeAccess::$superUser = false; - FakeAccess::$idSitesAdmin = $hasAdminAccess ? array(self::$idSite1) : array(); - FakeAccess::$idSitesView = $hasViewAccess ? array(self::$idSite1) : array(); + FakeAccess::$idSitesAdmin = $hasAdminAccess ? array(self::$fixture->idSite1) : array(); + FakeAccess::$idSitesView = $hasViewAccess ? array(self::$fixture->idSite1) : array(); Zend_Registry::set('access', $access); if ($checkException) @@ -368,47 +357,7 @@ class AnnotationsTest extends IntegrationTestCase $request->process(); } } - - private static function addAnnotations() - { - // create fake access for fake username - $access = new FakeAccess(); - FakeAccess::$superUser = true; - Zend_Registry::set('access', $access); - - // add two annotations per week for three months, starring every third annotation - // first month in 2011, second two in 2012 - $count = 0; - $dateStart = Piwik_Date::factory('2011-12-01'); - $dateEnd = Piwik_Date::factory('2012-03-01'); - while ($dateStart->getTimestamp() < $dateEnd->getTimestamp()) - { - $starred = $count % 3 == 0 ? 1 : 0; - $site1Text = "$count: Site 1 annotation for ".$dateStart->toString(); - $site2Text = "$count: Site 2 annotation for ".$dateStart->toString(); - - Piwik_Annotations_API::getInstance()->add(self::$idSite1, $dateStart->toString(), $site1Text, $starred); - Piwik_Annotations_API::getInstance()->add(self::$idSite2, $dateStart->toString(), $site2Text, $starred); - - $nextDay = $dateStart->addDay(1); - ++$count; - - $starred = $count % 3 == 0 ? 1 : 0; - $site1Text = "$count: Site 1 annotation for ".$nextDay->toString(); - $site2Text = "$count: Site 2 annotation for ".$nextDay->toString(); - - Piwik_Annotations_API::getInstance()->add(self::$idSite1, $nextDay->toString(), $site1Text, $starred); - Piwik_Annotations_API::getInstance()->add(self::$idSite2, $nextDay->toString(), $site2Text, $starred); - - $dateStart = $dateStart->addPeriod(1, 'WEEK'); - ++$count; - } - } - - private static function setUpWebsitesAndGoals() - { - // add two websites - self::createWebsite(self::$dateTime, $ecommerce = 1); - self::createWebsite(self::$dateTime, $ecommerce = 1); - } } + +AnnotationsTest::$fixture = new Test_Piwik_Fixture_TwoSitesWithAnnotations(); + diff --git a/tests/PHPUnit/Integration/ApiGetReportMetadataTest.php b/tests/PHPUnit/Integration/ApiGetReportMetadataTest.php index a2c19a4ba2..23e5ef759b 100755 --- a/tests/PHPUnit/Integration/ApiGetReportMetadataTest.php +++ b/tests/PHPUnit/Integration/ApiGetReportMetadataTest.php @@ -13,40 +13,15 @@ */ class Test_Piwik_Integration_ApiGetReportMetadata extends IntegrationTestCase { - protected static $dateTime = '2009-01-04 00:11:42'; - protected static $idSite = 1; - protected static $idGoal = 1; - protected static $idGoal2 = 2; - protected static $idGoal3 = 3; - - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - - } - - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime, $ecommerce = 1); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'Goal 1 - Thank you', 'title', 'Thank you', 'contains', $caseSensitive = false, $revenue = 10, $allowMultipleConversions = 1); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'Goal 2 - Hello', 'url', 'hellow', 'contains', $caseSensitive = false, $revenue = 10, $allowMultipleConversions = 0); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js', 'manually', '', ''); - } + public static $fixture = null; // initialized below class definition public function setUp() { parent::setUp(); - // From Piwik 1.5, we hide Goals.getConversions and other get* methods via @ignore, but we ensure that they still work - // This hack allows the API proxy to let us generate example URLs for the ignored functions + // From Piwik 1.5, we hide Goals.getConversions and other get* methods via @ignore, but we + // ensure that they still work. This hack allows the API proxy to let us generate example + // URLs for the ignored functions Piwik_API_Proxy::getInstance()->setHideIgnoredFunctions(false); } @@ -65,27 +40,30 @@ class Test_Piwik_Integration_ApiGetReportMetadata extends IntegrationTestCase public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $dateTime = self::$fixture->dateTime; + return array( - array('API', array('idSite' => self::$idSite, 'date' => self::$dateTime)), + array('API', array('idSite' => $idSite, 'date' => $dateTime)), // test w/ hideMetricsDocs=true - array('API.getMetadata', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('API.getMetadata', array('idSite' => $idSite, 'date' => $dateTime, 'apiModule' => 'Actions', 'apiAction' => 'get', 'testSuffix' => '_hideMetricsDoc', 'otherRequestParameters' => array('hideMetricsDoc' => 1)) ), - array('API.getProcessedReport', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('API.getProcessedReport', array('idSite' => $idSite, 'date' => $dateTime, 'apiModule' => 'Actions', 'apiAction' => 'get', 'testSuffix' => '_hideMetricsDoc', 'otherRequestParameters' => array('hideMetricsDoc' => 1)) ), // Test w/ showRawMetrics=true - array('API.getProcessedReport', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('API.getProcessedReport', array('idSite' => $idSite, 'date' => $dateTime, 'apiModule' => 'UserCountry', 'apiAction' => 'getCountry', 'testSuffix' => '_showRawMetrics', 'otherRequestParameters' => array('showRawMetrics' => 1)) ), // test php renderer w/ array data - array('API.getDefaultMetricTranslations', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('API.getDefaultMetricTranslations', array('idSite' => $idSite, 'date' => $dateTime, 'format' => 'php', 'testSuffix' => '_phpRenderer')), ); } @@ -99,20 +77,7 @@ class Test_Piwik_Integration_ApiGetReportMetadata extends IntegrationTestCase { $this->runApiTests($api, $params); } - - protected static function trackVisits() - { - $idSite = self::$idSite; - $dateTime = self::$dateTime; - - $t = self::getTracker($idSite, $dateTime, $defaultInit = true); - - // Record 1st page view - $t->setUrl('http://example.org/index.htm'); - self::checkResponse($t->doTrackPageView('incredible title!')); - - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); - self::checkResponse($t->doTrackGoal(self::$idGoal3, $revenue = 42.256)); - } } +Test_Piwik_Integration_ApiGetReportMetadata::$fixture = new Test_Piwik_Fixture_ThreeGoalsOnePageview(); + diff --git a/tests/PHPUnit/Integration/ApiGetReportMetadata_yearTest.php b/tests/PHPUnit/Integration/ApiGetReportMetadata_yearTest.php index b76918376e..1921112be2 100755 --- a/tests/PHPUnit/Integration/ApiGetReportMetadata_yearTest.php +++ b/tests/PHPUnit/Integration/ApiGetReportMetadata_yearTest.php @@ -12,41 +12,19 @@ */ class Test_Piwik_Integration_ApiGetReportMetadata_Year extends IntegrationTestCase { - protected static $idSite = 1; - protected static $dateTime = '2009-01-04 00:11:42'; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } - - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - } + public static $fixture = null; // initialized below class definition public function getApiForTesting() { - $params = array('idSite' => self::$idSite, - 'date' => self::$dateTime, + $params = array('idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime, 'periods' => 'year', 'language' => 'fr'); return array( array('API.getProcessedReport', $params), // @todo reenable me //array('API.getReportMetadata', $params), -// array('LanguagesManager.getTranslationsForLanguage', $params), + //array('LanguagesManager.getTranslationsForLanguage', $params), array('LanguagesManager.getAvailableLanguageNames', $params), array('SitesManager.getJavascriptTag', $params) ); @@ -68,3 +46,7 @@ class Test_Piwik_Integration_ApiGetReportMetadata_Year extends IntegrationTestCa $this->runApiTests($api, $params); } } + +Test_Piwik_Integration_ApiGetReportMetadata_Year::$fixture = new Test_Piwik_Fixture_InvalidVisits(); +Test_Piwik_Integration_ApiGetReportMetadata_Year::$fixture->trackInvalidRequests = false; + diff --git a/tests/PHPUnit/Integration/BlobReportLimitingTest.php b/tests/PHPUnit/Integration/BlobReportLimitingTest.php index 04676a7a3c..2db36b32d4 100755 --- a/tests/PHPUnit/Integration/BlobReportLimitingTest.php +++ b/tests/PHPUnit/Integration/BlobReportLimitingTest.php @@ -14,28 +14,13 @@ require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/MockLocationProvider.php'; */ class Test_Piwik_Integration_BlobReportLimitingTest extends IntegrationTestCase { - protected static $dateTime = '2010-01-03 01:22:33'; - - protected static $idSite = 1; - + public static $fixture = null; // initialized below class definition + public static function setUpBeforeClass() { self::setUpConfigOptions(); parent::_setUpBeforeClass($dbName = false, $createEmptyDatabase = true, $createConfig = false); - try { - self::setUpWebsitesAndGoals(); - self::setMockLocationProvider(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } - - public static function tearDownAfterClass() - { - self::unsetMockLocationProvider(); - parent::tearDownAfterClass(); + parent::setUpFixture(self::$fixture); } public function getApiForTesting() @@ -52,8 +37,8 @@ class Test_Piwik_Integration_BlobReportLimitingTest extends IntegrationTestCase ); return array( - array($apiToCall, array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime, 'periods' => array('day'))) ); } @@ -109,190 +94,7 @@ class Test_Piwik_Integration_BlobReportLimitingTest extends IntegrationTestCase $generalConfig['datatable_archiving_maximum_rows_standard'] = 3; $generalConfig['archiving_ranking_query_row_limit'] = 50000; } +} - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - $linuxFirefoxA = "Mozilla/5.0 (X11; Linux i686; rv:6.0) Gecko/20100101 Firefox/6.0"; - $win7FirefoxA = "Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.1.6) Gecko/20100101 Firefox/6.0"; - $win7ChromeA = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.38 Safari/532.0"; - $linuxChromeA = "Mozilla/5.0 (X11; Linux i686; rv:6.0) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.38 Safari/532.0"; - $linuxSafariA = "Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/531.2+ (KHTML, like Gecko) Version/5.0 Safari/531.2+"; - $iPadSafariA = "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/531.2+ (KHTML, like Gecko) Version/5.0 Safari/531.2+"; - $iPadFirefoxB = "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) Gecko/20100101 Firefox/14.0.1"; - $androidFirefoxB = "Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) Gecko/20100101 Firefox/14.0.1"; - $androidChromeB = "Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"; - $androidIEA = "Mozilla/5.0 (compatible; MSIE 10.6; Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0"; - $iPhoneOperaA = "Opera/9.80 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; ja-jp) Presto/2.9.181 Version/12.00"; - $win8IEB = "Mozilla/5.0 (compatible; MSIE 10.0; Windows 8; Trident/5.0)"; - $winVistaIEB = "Mozilla/5.0 (compatible; MSIE 10.0; Windows Vista; Trident/5.0)"; - $osxOperaB = "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52"; - $userAgents = array( - $linuxFirefoxA, $linuxFirefoxA, $win7FirefoxA, $win7ChromeA, $linuxChromeA, $linuxSafariA, - $iPadSafariA, $iPadFirefoxB, $androidFirefoxB, $androidChromeB, $androidIEA, $iPhoneOperaA, - $win8IEB, $winVistaIEB, $osxOperaB - ); - - $resolutions = array( - "1920x1080", "1920x1080", "1920x1080", "1920x1080", "1366x768", "1366x768", "1366x768", - "1280x1024", "1280x1024", "1280x1024", "1680x1050", "1680x1050", "1024x768", "800x600", - "320x480" - ); - - $referrers = array( - // website referrers (8) - 'http://whatever0.com/0', 'http://whatever0.com/0', 'http://whatever0.com/1', 'http://whatever0.com/2', - 'http://whatever1.com/0', 'http://whatever.com1/1', 'http://whatever1.com/2', 'http://whatever3.com/3', - - // search engines w/ keyword (12) - 'http://www.google.com/search?q=this+search+term', - 'http://www.google.com/search?q=that+search+term', - 'http://search.yahoo.com/search?p=this+search+term', - 'http://search.yahoo.com/search?p=that+search+term', - 'http://www.ask.com/web?q=this+search+term', - 'http://www.bing.com/search?q=search+term+1', - 'http://search.babylon.com/?q=search+term+2', - 'http://alexa.com/search?q=search+term+2', - 'http://www.google.com/search?q=search+term+3', - 'http://search.yahoo.com/search?p=search+term+4', - 'http://www.ask.com/web?q=search+term+3', - 'http://www.bing.com/search?q=search+term+4', - ); - - $customVars = array( - 'name' => array('thing0', 'thing1', 'thing2', 'thing3', 'thing4', 'thing5', 'thing6', 'thing7', - 'thing8', 'thing9', 'thing10', 'thing11', 'thing12', 'thing13', 'thing14', - 'thing15', 'thing16', 'thing17', 'thing18', 'thing19'), - 'rating' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20), - 'tweeted' => array('y', 'n', 'm', 'n', 'y', 'n', 'y', 'n', 'y', 'n', 'y', 'n', 'y', 'n', 'y', 'n', - 'm', 'n', 'm', 'n'), - 'liked' => array('yes', 'y', 'y', 'no', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', - 'y', 'y', 'no', 'n'), - ); - $downloadCustomVars = array( - 'size' => array(1024, 1024, 1024, 2048, 2048, 3072, 3072, 3072, 3072, 4096, 4096, 4096, - 512, 512, 256, 128, 64, 32, 48, 48) - ); - - $visitorCounter = 0; - $t = self::getTracker(self::$idSite, self::$dateTime, $defaultInit = true, $useLocal = true); - - // track regular actions - self::trackActions($t, $visitorCounter, 'pageview', $userAgents, $resolutions, $referrers, $customVars); - - // track downloads - self::trackActions($t, $visitorCounter, 'download', $userAgents, $resolutions, null, $downloadCustomVars); - - // track outlinks - self::trackActions($t, $visitorCounter, 'outlink', $userAgents, $resolutions); - } - - private static function trackActions($t, &$visitorCounter, $actionType, $userAgents, $resolutions, - $referrers = null, $customVars = null) - { - for ($i = 0; $i != 5; ++$i, ++$visitorCounter) - { - $visitDate = Piwik_Date::factory(self::$dateTime); - - $t->setNewVisitorId(); - $t->setIp("156.5.3.$visitorCounter"); - - $t->setUserAgent($userAgents[$visitorCounter]); - list($w, $h) = explode('x', $resolutions[$visitorCounter]); - $t->setResolution((int)$w, (int)$h); - - // one visit to root url - $t->setUrl("http://piwik.net/$visitorCounter/"); - $t->setUrlReferrer(null); - $t->setForceVisitDateTime($visitDate->getDatetime()); - self::trackAction($t, $actionType, $visitorCounter, null); - - for ($j = 0; $j != 4; ++$j) - { - // NOTE: to test referers w/o creating too many visits, we don't actually track 4 actions, but - // 4 separate visits - $actionDate = $visitDate->addHour($j + 1); - - $actionIdx = $i * 4 + $j; - $actionNum = $visitorCounter * 4 + $j; - - $t->setUrl("http://piwik.net/$visitorCounter/$actionNum"); - $t->setForceVisitDateTime($actionDate->getDatetime()); - - if (!is_null($referrers)) - { - $t->setUrlReferrer($referrers[$actionIdx]); - } - else - { - $t->setUrlReferrer(null); - } - - if (!is_null($customVars)) - { - $k = 1; - foreach ($customVars as $name => $values) - { - $value = $values[$actionIdx]; - $t->setCustomVariable($k, $name, $value, $scope = 'page'); - - ++$k; - } - } - - self::trackAction($t, $actionType, $visitorCounter, $actionNum); - } - } - } - - private static function trackAction($t, $actionType, $visitorCounter, $actionNum) - { - if ($actionType == 'pageview') - { - self::checkResponse($t->doTrackPageView( - is_null($actionNum) ? "title_$visitorCounter" : "title_$visitorCounter / title_$actionNum")); - } - else if ($actionType == 'download') - { - $root = is_null($actionNum) ? "http://cloudsite$visitorCounter.com" - : "http://cloudsite$visitorCounter.com/$actionNum"; - - self::checkResponse($t->doTrackAction("$root/download", 'download')); - } - else if ($actionType == 'outlink') - { - self::checkResponse($t->doTrackAction(is_null($actionNum) ? "http://othersite$visitorCounter.com/" - : "http://othersite$visitorCounter.com/$actionNum/", 'link')); - } - } - - public static function setMockLocationProvider() - { - Piwik_UserCountry_LocationProvider::setCurrentProvider('mock_provider'); - MockLocationProvider::$locations = array( - self::makeLocation('Toronto', 'ON', 'CA'), - - self::makeLocation('Nice', 'B8', 'FR'), - - self::makeLocation('Melbourne', '07', 'AU'), +Test_Piwik_Integration_BlobReportLimitingTest::$fixture = new Test_Piwik_Fixture_ManyVisitsWithMockLocationProvider(); - self::makeLocation('Yokohama', '19', 'JP'), - ); - } - - public static function unsetMockLocationProvider() - { - Piwik_UserCountry_LocationProvider::setCurrentProvider('default'); - } - - public static function makeLocation( $city, $region, $country ) - { - return array(Piwik_UserCountry_LocationProvider::CITY_NAME_KEY => $city, - Piwik_UserCountry_LocationProvider::REGION_CODE_KEY => $region, - Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY => $country); - } -} diff --git a/tests/PHPUnit/Integration/CsvExportTest.php b/tests/PHPUnit/Integration/CsvExportTest.php index 99a8848f07..44cb1c5e41 100755 --- a/tests/PHPUnit/Integration/CsvExportTest.php +++ b/tests/PHPUnit/Integration/CsvExportTest.php @@ -11,132 +11,13 @@ */ class Test_Piwik_Integration_CsvExport extends IntegrationTestCase { - protected static $dateTime = '2010-01-03 11:22:33'; - protected static $width = 1111; - protected static $height = 222; - - protected static $idSite = 1; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - - protected static $useEscapedQuotes = false; - protected static $doExtraQuoteTests = false; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } - - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js', 'manually', '', ''); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'second goal', 'manually', '', ''); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idGoal = self::$idGoal1; - $idGoal2 = self::$idGoal2; - - $visitorA = self::getTracker($idSite, $dateTime, $defaultInit = true); - // Used to test actual referer + keyword position in Live! - $visitorA->setUrlReferrer(urldecode('http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB4QFjAA&url=http%3A%2F%2Fpiwik.org%2F&rct=j&q=this%20keyword%20should%20be%20ranked&ei=V8WfTePkKKLfiALrpZWGAw&usg=AFQjCNF_MGJRqKPvaKuUokHtZ3VvNG9ALw&sig2=BvKAdCtNixsmfNWXjsNyMw')); - - // no campaign, but a search engine to attribute the goal conversion to - $attribution = array( - '', - '', - 1302306504, - 'http://www.google.com/search?q=piwik&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a' - ); - $visitorA->setAttributionInfo(json_encode($attribution)); - - $visitorA->setResolution(self::$width, self::$height); - - // At first, visitor custom var is set to LoggedOut - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitorA->setUrl('http://example.org/homepage'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - self::checkResponse($visitorA->doTrackPageView('Homepage')); - self::checkResponse($visitorA->doTrackGoal($idGoal2)); - - // After login, set to LoggedIn, should overwrite previous value - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $visitorA->setUrl('http://example.org/user/profile'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedIn'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = 'Loggedin', $scope = 'page'); - if (self::$useEscapedQuotes) { - $lookingAtProfile = 'looking at "profile page"'; - } else { - $lookingAtProfile = 'looking at profile page'; - } - $visitorA->setCustomVariable($id = 5, $name = 'Status user', $value = $lookingAtProfile, $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Profile page')); - - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE', $value = ''); - $visitorA->setCustomVariable($id = 1, $name = 'Language', $value = 'FR', $scope = 'page'); - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE PAGE SCOPE', $value = '', $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = "looking at \"profile page\"", $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'Value will be VERY long and truncated', $value = 'abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----'); - self::checkResponse($visitorA->doTrackPageView('Profile page for user *_)%')); - self::checkResponse($visitorA->doTrackGoal($idGoal)); - - if (self::$doExtraQuoteTests) { - $visitorA->setCustomVariable($id = 2, $name = 'var1', $value = 'looking at "profile page"', - $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'var2', $value = '\'looking at "\profile page"\'', - $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'var3', $value = '\\looking at "\profile page"\\', - $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Concurrent page views')); - } - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->setUrlReferrer(''); - - $attribution = array( - ' CAMPAIGN NAME -%20YEAH! ', - ' CAMPAIGN%20KEYWORD - RIGHT... ', - 1302306504, - 'http://www.example.org/test/really?q=yes' - ); - $visitorB->setAttributionInfo(json_encode($attribution)); - $visitorB->setResolution(self::$width, self::$height); - $visitorB->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6'); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - $visitorB->setCustomVariable($id = 2, $name = 'Othercustom value which should be truncated abcdefghijklmnopqrstuvwxyz', $value = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'); - $visitorB->setCustomVariable($id = -2, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = array('not tracked'), $value = 'not tracked'); - $visitorB->setUrl('http://example.org/homepage'); - self::checkResponse($visitorB->doTrackGoal($idGoal, 1000)); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.1)->getDatetime()); - self::checkResponse($visitorB->doTrackPageView('Homepage')); - - // DIFFERENT test - - // testing that starting the visit with an outlink works (doesn't trigger errors) - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - self::checkResponse($visitorB->doTrackAction('http://test.com', 'link')); - } - + public static $fixture = null; // initialized below class definition public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $dateTime = self::$fixture->dateTime; + $apiToCall = array('VisitsSummary.get', 'CustomVariables.getCustomVariables'); $enExtraParam = array('expanded' => 0, 'flat' => 1, 'include_aggregate_rows' => 0, 'translateColumnNames' => 1); @@ -144,21 +25,21 @@ class Test_Piwik_Integration_CsvExport extends IntegrationTestCase $deExtraParam = array('expanded' => 0, 'flat' => 1, 'include_aggregate_rows' => 1, 'translateColumnNames' => 1); return array( - array($apiToCall, array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => $idSite, + 'date' => $dateTime, 'format' => 'csv', 'otherRequestParameters' => array('expanded' => 0, 'flat' => 0), 'testSuffix' => '_xp0')), - array($apiToCall, array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => $idSite, + 'date' => $dateTime, 'format' => 'csv', 'otherRequestParameters' => $enExtraParam, 'language' => 'en', 'testSuffix' => '_xp1_inner0_trans-en')), - array($apiToCall, array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => $idSite, + 'date' => $dateTime, 'format' => 'csv', 'otherRequestParameters' => $deExtraParam, 'language' => 'de', @@ -181,3 +62,9 @@ class Test_Piwik_Integration_CsvExport extends IntegrationTestCase return 'csvExport'; } } + +Test_Piwik_Integration_CsvExport::$fixture = new Test_Piwik_Fixture_TwoVisitsWithCustomVariables(); +Test_Piwik_Integration_CsvExport::$fixture->visitorId = null; +Test_Piwik_Integration_CsvExport::$fixture->useEscapedQuotes = false; +Test_Piwik_Integration_CsvExport::$fixture->doExtraQuoteTests = false; + diff --git a/tests/PHPUnit/Integration/EcommerceOrderWithItemsTest.php b/tests/PHPUnit/Integration/EcommerceOrderWithItemsTest.php index abbfbdfe3f..0bb23213c7 100755 --- a/tests/PHPUnit/Integration/EcommerceOrderWithItemsTest.php +++ b/tests/PHPUnit/Integration/EcommerceOrderWithItemsTest.php @@ -11,23 +11,7 @@ */ class Test_Piwik_Integration_EcommerceOrderWithItems extends IntegrationTestCase { - protected static $dateTime = '2011-04-05 00:11:42'; - protected static $idSite = 1; - protected static $idSite2 = 2; - protected static $idGoalStandard = 1; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::setUpScheduledReports(self::$idSite); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @group Integration @@ -50,6 +34,10 @@ class Test_Piwik_Integration_EcommerceOrderWithItems extends IntegrationTestCase public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $idSite2 = self::$fixture->idSite2; + $dateTime = self::$fixture->dateTime; + $dayApi = array('VisitsSummary.get', 'VisitTime', 'CustomVariables.getCustomVariables', 'Live.getLastVisitsDetails', 'UserCountry', 'API.getProcessedReport', 'Goals.get', 'Goals.getConversions', 'Goals.getItemsSku', 'Goals.getItemsName', 'Goals.getItemsCategory'); @@ -64,280 +52,131 @@ class Test_Piwik_Integration_EcommerceOrderWithItems extends IntegrationTestCase return array_merge(array( // day tests - array($dayApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, 'periods' => array('day'), 'otherRequestParameters' => array('_leavePiwikCoreVariables' => 1))), + array($dayApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'otherRequestParameters' => array('_leavePiwikCoreVariables' => 1))), // goals API week tests - array($goalWeekApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, 'periods' => array('week'))), + array($goalWeekApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('week'))), // abandoned carts tests - array($goalItemApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, + array($goalItemApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day', 'week'), 'abandonedCarts' => 1, 'testSuffix' => '_AbandonedCarts')), // multiple periods tests - array($goalItemApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, 'periods' => array('day'), + array($goalItemApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'setDateLastN' => true, 'testSuffix' => 'multipleDates')), // multiple periods & multiple websites tests - array($goalItemApi, array('idSite' => sprintf("%u,%u", self::$idSite, self::$idSite2), 'date' => self::$dateTime, + array($goalItemApi, array('idSite' => sprintf("%u,%u", $idSite, $idSite2), 'date' => $dateTime, 'periods' => array('day'), 'setDateLastN' => true, 'testSuffix' => 'multipleDates_andMultipleWebsites')), // test metadata products - array($processedReportApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, + array($processedReportApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'apiModule' => 'Goals', 'apiAction' => 'getItemsSku', 'testSuffix' => '_Metadata_ItemsSku')), - array($processedReportApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, + array($processedReportApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'apiModule' => 'Goals', 'apiAction' => 'getItemsCategory', 'testSuffix' => '_Metadata_ItemsCategory')), // test metadata Goals.get for Ecommerce orders & Carts - array($processedReportApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, + array($processedReportApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'apiModule' => 'Goals', 'apiAction' => 'get', 'idGoal' => Piwik_Archive::LABEL_ECOMMERCE_ORDER, 'testSuffix' => '_Metadata_Goals.Get_Order')), - array($processedReportApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, + array($processedReportApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'apiModule' => 'Goals', 'apiAction' => 'get', 'idGoal' => Piwik_Archive::LABEL_ECOMMERCE_CART, 'testSuffix' => '_Metadata_Goals.Get_AbandonedCart')), // normal standard goal test - array($processedReportApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, + array($processedReportApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'apiModule' => 'Goals', 'apiAction' => 'get', - 'idGoal' => self::$idGoalStandard, + 'idGoal' => self::$fixture->idGoalStandard, 'testSuffix' => '_Metadata_Goals.Get_NormalGoal')), // non-existant goal test - array($processedReportApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, + array($processedReportApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'apiModule' => 'Goals', 'apiAction' => 'get', 'idGoal' => 'FAKE IDGOAL', 'testSuffix' => '_Metadata_Goals.Get_NotExistingGoal')), // While we're at it, test for a standard Metadata report with zero entries - array($processedReportApi, array('idSite' => self::$idSite, 'date' => self::$dateTime, + array($processedReportApi, array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'apiModule' => 'VisitTime', 'apiAction' => 'getVisitInformationPerServerTime', 'testSuffix' => '_Metadata_VisitTime.getVisitInformationPerServerTime')), // Standard non metadata Goals.get // test Goals.get with idGoal=ecommerceOrder and ecommerceAbandonedCart - array('Goals.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('Goals.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day', 'week'), 'idGoal' => Piwik_Archive::LABEL_ECOMMERCE_CART, 'testSuffix' => '_GoalAbandonedCart')), - array('Goals.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('Goals.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day', 'week'), 'idGoal' => Piwik_Archive::LABEL_ECOMMERCE_ORDER, 'testSuffix' => '_GoalOrder')), - array('Goals.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('Goals.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day', 'week'), 'idGoal' => 1, 'testSuffix' => '_GoalMatchTitle')), - array('Goals.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('Goals.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day', 'week'), 'idGoal' => '', 'testSuffix' => '_GoalOverall')), - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'segment' => 'visitEcommerceStatus==none', 'testSuffix' => '_SegmentNoEcommerce')), - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'testSuffix' => '_SegmentOrderedSomething', 'segment' => 'visitEcommerceStatus==ordered,visitEcommerceStatus==orderedThenAbandonedCart')), - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'testSuffix' => '_SegmentAbandonedCart', 'segment' => 'visitEcommerceStatus==abandonedCart,visitEcommerceStatus==orderedThenAbandonedCart')), // test segment visitConvertedGoalId - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day', 'week'), 'testSuffix' => '_SegmentConvertedGoalId1', - 'segment' => "visitConvertedGoalId==".self::$idGoalStandard)), - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + 'segment' => "visitConvertedGoalId==".self::$fixture->idGoalStandard)), + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'testSuffix' => '_SegmentDidNotConvertGoalId1', - 'segment' => "visitConvertedGoalId!=".self::$idGoalStandard)), + 'segment' => "visitConvertedGoalId!=".self::$fixture->idGoalStandard)), // test segment visitorType - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('week'), 'segment' => 'visitorType==new', 'testSuffix' => '_SegmentNewVisitors')), - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('week'), 'segment' => 'visitorType==returning', 'testSuffix' => '_SegmentReturningVisitors')), - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('week'), 'segment' => 'visitorType==returningCustomer', 'testSuffix' => '_SegmentReturningCustomers')), // test segment pageTitle - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'segment' => 'pageTitle==incredible title!', 'testSuffix' => '_SegmentPageTitleMatch')), // test Live! output is OK also for the visit that just bought something (other visits leave an abandoned cart) - array('Live.getLastVisitsDetails', array('idSite' => self::$idSite, - 'date' => Piwik_Date::factory(self::$dateTime)->addHour(30.65)->getDatetime(), + array('Live.getLastVisitsDetails', array('idSite' => $idSite, + 'date' => Piwik_Date::factory($dateTime)->addHour(30.65)->getDatetime(), 'periods' => array('day'), 'testSuffix' => '_LiveEcommerceStatusOrdered')), // test API.get method - array('API.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, 'periods' => array('day', 'week'), + array('API.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day', 'week'), 'otherRequestParameters' => array( 'columns' => 'nb_pageviews,nb_visits,avg_time_on_site,nb_visits_converted'), 'testSuffix' => '_API_get')), // Website2 - array($goalWeekApi, array('idSite' => self::$idSite2, 'date' => self::$dateTime, 'periods' => array('week'), + array($goalWeekApi, array('idSite' => $idSite2, 'date' => $dateTime, 'periods' => array('week'), 'testSuffix' => '_Website2')), - ), self::getApiForTestingScheduledReports(self::$dateTime, 'week')); + ), self::getApiForTestingScheduledReports($dateTime, 'week')); } public function getOutputPrefix() { return 'ecommerceOrderWithItems'; } +} - public static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime, $ecommerce = 1); - self::createWebsite(self::$dateTime); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'title match, triggered ONCE', 'title', 'incredible', 'contains', $caseSensitive = false, $revenue = 10, $allowMultipleConversions = true); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idSite2 = self::$idSite2; - - $t = self::getTracker($idSite, $dateTime, $defaultInit = true); - // VISIT NO 1 - $t->setUrl('http://example.org/index.htm'); - $category = 'Electronics & Cameras'; - $price = 1111.11111; - - // VIEW product page - $t->setEcommerceView('SKU2', 'PRODUCT name', $category, $price); - $t->setCustomVariable(5, 'VisitorType', 'NewLoggedOut', 'visit'); - $t->setCustomVariable(4, 'ValueIsZero', '0', 'visit'); - self::assertEquals(array('_pks', 'SKU2'), $t->getCustomVariable(3, 'page')); - self::assertEquals(array('_pkn', 'PRODUCT name'), $t->getCustomVariable(4, 'page')); - self::assertEquals(array('_pkc', $category), $t->getCustomVariable(5, 'page')); - self::assertEquals(array('_pkp', $price), $t->getCustomVariable(2, 'page')); - self::assertEquals(array('VisitorType', 'NewLoggedOut'), $t->getCustomVariable(5, 'visit')); - self::checkResponse($t->doTrackPageView('incredible title!')); - - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $category, $price = 666); - self::checkResponse($t->doTrackPageView('Another Product page')); - - // Note: here testing to pass a timestamp to the tracking API rather than the datetime string - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getTimestampUTC()); - $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', ''); - self::checkResponse($t->doTrackPageView('Another Product page with no category')); - - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $categories = array('Multiple Category 1', '', 0, 'Multiple Category 2', 'Electronics & Cameras', 'Multiple Category 4', 'Multiple Category 5', 'SHOULD NOT BE REPORTEDSSSSSSSSSSSSSSssssssssssssssssssssssssssstttttttttttttttttttttttuuuu!')); - self::checkResponse($t->doTrackPageView('Another Product page with multiple categories')); - - // VISIT NO 2 - - // Fake the returning visit cookie - $t->setDebugStringAppend("&_idvc=2"); - - // VIEW category page - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.6)->getDatetime()); - $t->setEcommerceView('', '', $category); - self::checkResponse($t->doTrackPageView('Looking at ' . $category . ' page with a page level custom variable')); - - // VIEW category page again - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.7)->getDatetime()); - $t->setEcommerceView('', '', $category); - self::checkResponse($t->doTrackPageView('Looking at ' . $category . ' page again')); - - // VIEW product page - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.8)->getDatetime()); - $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $category = 'Electronics & Cameras', $price = 666); - self::checkResponse($t->doTrackPageView('Looking at product page')); - - // ADD TO CART - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.9)->getDatetime()); - $t->setCustomVariable(3, 'VisitorName', 'Great name!', 'visit'); - $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $category = 'Electronics & Cameras', $price = 500, $quantity = 1); - $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $category = 'Electronics & Cameras', $price = 500, $quantity = 2); - $t->addEcommerceItem($sku = 'SKU WILL BE DELETED', $name = 'BLABLA DELETED', $category = '', $price = 5000000, $quantity = 20); - self::checkResponse($t->doTrackEcommerceCartUpdate($grandTotal = 1000)); - - // ORDER NO 1 - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', $categories, $price = 500, $quantity = 2); - $t->addEcommerceItem($sku = 'ANOTHER SKU HERE', $name = 'PRODUCT name BIS', $category = '', $price = 100, $quantity = 6); - self::checkResponse($t->doTrackEcommerceOrder($orderId = '937nsjusu 3894', $grandTotal = 1111.11, $subTotal = 1000, $tax = 111, $shipping = 0.11, $discount = 666)); - - // ORDER NO 2 - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2.1)->getDatetime()); - $t->addEcommerceItem($sku = 'SKU2', $name = 'Canon SLR', $category = 'Electronics & Cameras', $price = 1500, $quantity = 1); - // Product bought with empty category - $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT name', '', $price = 11.22, $quantity = 1); - - // test to delete all custom vars, they should be copied from visits - // This is a frequent use case: ecommerce shops tracking the order from backoffice - // without passing the custom variable 1st party cookie along since it's not known by back office - $visitorCustomVarSave = $t->visitorCustomVar; - $t->visitorCustomVar = false; - self::checkResponse($t->doTrackEcommerceOrder($orderId = '1037nsjusu4s3894', $grandTotal = 2000, $subTotal = 1500, $tax = 400, $shipping = 100, $discount = 0)); - $t->visitorCustomVar = $visitorCustomVarSave; - - // ORDER SHOULD DEDUPE - // Refresh the page with the receipt for the second order, should be ignored - // we test that both the order, and the products, are not updated on subsequent "Receipt" views - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2.2)->getDatetime()); - $t->addEcommerceItem($sku = 'SKU2', $name = 'Canon SLR NOT!', $category = 'Electronics & Cameras NOT!', $price = 15000000000, $quantity = 10000); - self::checkResponse($t->doTrackEcommerceOrder($orderId = '1037nsjusu4s3894', $grandTotal = 20000000, $subTotal = 1500, $tax = 400, $shipping = 100, $discount = 0)); - - // Leave with an opened cart - // No category - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2.3)->getDatetime()); - $t->addEcommerceItem($sku = 'SKU IN ABANDONED CART ONE', $name = 'PRODUCT ONE LEFT in cart', $category = '', $price = 500.11111112, $quantity = 2); - self::checkResponse($t->doTrackEcommerceCartUpdate($grandTotal = 1000)); - - // Record the same visit leaving twice an abandoned cart - foreach (array(0, 5, 24) as $offsetHour) { - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.4)->getDatetime()); - // Also recording an order the day after - if ($offsetHour >= 24) { - $t->setDebugStringAppend("&_idvc=1"); - $t->addEcommerceItem($sku = 'SKU2', $name = 'Canon SLR', $category = 'Electronics & Cameras', $price = 1500, $quantity = 1); - self::checkResponse($t->doTrackEcommerceOrder($orderId = '1037nsjusu4s3894', $grandTotal = 20000000, $subTotal = 1500, $tax = 400, $shipping = 100, $discount = 0)); - } - - // VIEW PRODUCT PAGES - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.5)->getDatetime()); - $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT THREE LEFT in cart', $category = '', $price = 999); - self::checkResponse($t->doTrackPageView("View product left in cart")); - - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.55)->getDatetime()); - $t->setEcommerceView($sku = 'SKU VERY nice indeed', $name = 'PRODUCT THREE LEFT in cart', $category = '', $price = 333); - self::checkResponse($t->doTrackPageView("View product left in cart")); - - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.6)->getDatetime()); - $t->setEcommerceView($sku = 'SKU IN ABANDONED CART TWO', $name = 'PRODUCT TWO LEFT in cart', $category = 'Category TWO LEFT in cart'); - self::checkResponse($t->doTrackPageView("View product left in cart")); - - // ABANDONED CART - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour($offsetHour + 2.7)->getDatetime()); - $t->addEcommerceItem($sku = 'SKU IN ABANDONED CART ONE', $name = 'PRODUCT ONE LEFT in cart', $category = '', $price = 500.11111112, $quantity = 1); - $t->addEcommerceItem($sku = 'SKU IN ABANDONED CART TWO', $name = 'PRODUCT TWO LEFT in cart', $category = 'Category TWO LEFT in cart', $price = 1000, $quantity = 2); - $t->addEcommerceItem($sku = 'SKU VERY nice indeed', $name = 'PRODUCT THREE LEFT in cart', $category = 'Electronics & Cameras', $price = 10, $quantity = 1); - self::checkResponse($t->doTrackEcommerceCartUpdate($grandTotal = 2510.11111112)); - } - - // One more Ecommerce order to check weekly archiving works fine on orders - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(30.7)->getDatetime()); - $t->addEcommerceItem($sku = 'TRIPOD SKU', $name = 'TRIPOD - bought day after', $category = 'Tools', $price = 100, $quantity = 2); - self::checkResponse($t->doTrackEcommerceOrder($orderId = '666', $grandTotal = 240, $subTotal = 200, $tax = 20, $shipping = 20, $discount = 20)); - - // One more Ecommerce order, without any product in it, because we still track orders without products - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(30.8)->getDatetime()); - self::checkResponse($t->doTrackEcommerceOrder($orderId = '777', $grandTotal = 10000)); +Test_Piwik_Integration_EcommerceOrderWithItems::$fixture = new Test_Piwik_Fixture_TwoSitesEcommerceOrderWithItems(); - // testing the same order in a different website should record - $t = self::getTracker($idSite2, $dateTime, $defaultInit = true); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(30.9)->getDatetime()); - $t->addEcommerceItem($sku = 'TRIPOD SKU', $name = 'TRIPOD - bought day after', $category = 'Tools', $price = 100, $quantity = 2); - self::checkResponse($t->doTrackEcommerceOrder($orderId = '777', $grandTotal = 250)); - //------------------------------------- End tracking - } -} diff --git a/tests/PHPUnit/Integration/FlattenReportsTest.php b/tests/PHPUnit/Integration/FlattenReportsTest.php index acb1d74a3c..16d4580267 100644 --- a/tests/PHPUnit/Integration/FlattenReportsTest.php +++ b/tests/PHPUnit/Integration/FlattenReportsTest.php @@ -11,20 +11,7 @@ */ class Test_Piwik_Integration_FlattenReports extends IntegrationTestCase { - protected static $dateTime = '2010-03-06 11:22:33'; - protected static $idSite = 1; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -38,14 +25,17 @@ class Test_Piwik_Integration_FlattenReports extends IntegrationTestCase public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $dateTime = self::$fixture->dateTime; + $return = array(); // referrers $return[] = array( 'Referers.getWebsites', array( - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'otherRequestParameters' => array( 'flat' => '1', 'expanded' => '0' @@ -56,8 +46,8 @@ class Test_Piwik_Integration_FlattenReports extends IntegrationTestCase $return[] = array( 'Actions.getPageUrls', array( - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'otherRequestParameters' => array( 'flat' => '1', 'expanded' => '0' @@ -66,8 +56,8 @@ class Test_Piwik_Integration_FlattenReports extends IntegrationTestCase $return[] = array( 'Actions.getPageUrls', array( - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'testSuffix' => '_withAggregate', 'otherRequestParameters' => array( 'flat' => '1', @@ -78,8 +68,8 @@ class Test_Piwik_Integration_FlattenReports extends IntegrationTestCase // custom variables for multiple days $return[] = array('CustomVariables.getCustomVariables', array( - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'otherRequestParameters' => array( 'date' => '2010-03-06,2010-03-08', 'flat' => '1', @@ -89,8 +79,8 @@ class Test_Piwik_Integration_FlattenReports extends IntegrationTestCase )); // test expanded=1 w/ idSubtable=X - $return[] = array('Actions.getPageUrls', array('idSite' => self::$idSite, - 'date' => self::$dateTime, + $return[] = array('Actions.getPageUrls', array('idSite' => $idSite, + 'date' => $dateTime, 'periods' => array('week'), 'apiModule' => 'Actions', 'apiAction' => 'getPageUrls', @@ -99,8 +89,8 @@ class Test_Piwik_Integration_FlattenReports extends IntegrationTestCase 'otherRequestParameters' => array('expanded' => '1'))); // test flat=1 w/ filter_pattern_recursive - $return[] = array('Actions.getPageUrls', array('idSite' => self::$idSite, - 'date' => self::$dateTime, + $return[] = array('Actions.getPageUrls', array('idSite' => $idSite, + 'date' => $dateTime, 'periods' => array('week'), 'apiModule' => 'Actions', 'apiAction' => 'getPageUrls', @@ -118,36 +108,8 @@ class Test_Piwik_Integration_FlattenReports extends IntegrationTestCase { return 'FlattenReports'; } - - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - - for ($referrerSite = 1; $referrerSite < 4; $referrerSite++) { - for ($referrerPage = 1; $referrerPage < 3; $referrerPage++) { - $offset = $referrerSite * 3 + $referrerPage; - $t = self::getTracker($idSite, Piwik_Date::factory($dateTime)->addHour($offset)->getDatetime()); - $t->setUrlReferrer('http://www.referrer' . $referrerSite . '.com/sub/dir/page' . $referrerPage . '.html'); - $t->setCustomVariable(1, 'CustomVarVisit', 'CustomVarValue' . $referrerPage, 'visit'); - for ($page = 0; $page < 3; $page++) { - $t->setUrl('http://example.org/dir' . $referrerSite . '/sub/dir/page' . $page . '.html'); - $t->setCustomVariable(1, 'CustomVarPage', 'CustomVarValue' . $page, 'page'); - self::checkResponse($t->doTrackPageView('title')); - } - } - } - - $t = self::getTracker($idSite, Piwik_Date::factory($dateTime)->addHour(24)->getDatetime()); - $t->setCustomVariable(1, 'CustomVarVisit', 'CustomVarValue1', 'visit'); - $t->setUrl('http://example.org/sub/dir/dir1/page1.html'); - $t->setCustomVariable(1, 'CustomVarPage', 'CustomVarValue1', 'page'); - self::checkResponse($t->doTrackPageView('title')); - } } +Test_Piwik_Integration_FlattenReports::$fixture = + new Test_Piwik_Fixture_ManyVisitsWithSubDirReferrersAndCustomVars(); + diff --git a/tests/PHPUnit/Integration/ImportLogsTest.php b/tests/PHPUnit/Integration/ImportLogsTest.php index f61cea3f86..bf8e328c93 100755 --- a/tests/PHPUnit/Integration/ImportLogsTest.php +++ b/tests/PHPUnit/Integration/ImportLogsTest.php @@ -11,39 +11,7 @@ */ class Test_Piwik_Integration_ImportLogs extends IntegrationTestCase { - protected static $dateTime = '2010-03-06 11:22:33'; - protected static $idSite = 1; - protected static $idSite2 = 2; - protected static $idGoal = null; - protected static $tokenAuth = null; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::$tokenAuth = self::getTokenAuth(); - - self::setUpWebsitesAndGoals(); - self::downloadGeoIpDbs(); - - Piwik_UserCountry_LocationProvider::$providers = null; - Piwik_UserCountry_LocationProvider_GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files'; - Piwik_UserCountry_LocationProvider::setCurrentProvider('geoip_php'); - - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } - - public static function tearDownAfterClass() - { - Piwik_UserCountry_LocationProvider::$providers = null; - Piwik_UserCountry_LocationProvider_GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files'; - Piwik_UserCountry_LocationProvider::setCurrentProvider('default'); - parent::tearDownAfterClass(); - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -58,11 +26,11 @@ class Test_Piwik_Integration_ImportLogs extends IntegrationTestCase public function getApiForTesting() { return array( - array('all', array('idSite' => self::$idSite, + array('all', array('idSite' => self::$fixture->idSite, 'date' => '2012-08-09', 'periods' => 'month')), - array('VisitsSummary.get', array('idSite' => self::$idSite2, + array('VisitsSummary.get', array('idSite' => self::$fixture->idSite2, 'date' => '2012-08-09', 'periods' => 'month', 'testSuffix' => '_siteIdTwo_TrackedUsingLogReplay')), @@ -75,7 +43,7 @@ class Test_Piwik_Integration_ImportLogs extends IntegrationTestCase */ public function testDynamicResolverSitesCreated() { - self::logVisitsWithDynamicResolver(self::$tokenAuth); + self::$fixture->logVisitsWithDynamicResolver(); // reload access so new sites are viewable Zend_Registry::get('access')->setSuperUser(true); @@ -95,121 +63,7 @@ class Test_Piwik_Integration_ImportLogs extends IntegrationTestCase { return 'ImportLogs'; } +} - public static function setUpWebsitesAndGoals() - { - // for conversion testing - self::$idSite = self::createWebsite(self::$dateTime); - self::$idGoal = Piwik_Goals_API::getInstance()->addGoal( - self::$idSite, 'all', 'url', 'http', 'contains', false, 5); - self::$idSite2 = self::createWebsite(self::$dateTime, $ecommerce = 0, $siteName = 'Piwik test two', $siteUrl = 'http://example-site-two.com'); - } - - protected static function trackVisits() - { - self::logVisitsWithStaticResolver(self::$tokenAuth); - self::logVisitsWithAllEnabled(self::$tokenAuth); - self::replayLogFile(self::$tokenAuth); - } +Test_Piwik_Integration_ImportLogs::$fixture = new Test_Piwik_Fixture_ManySitesImportedLogs(); - /** - * Logs a couple visits for Aug 9, Aug 10, Aug 11 of 2012, for site we create. - */ - protected static function logVisitsWithStaticResolver( $token_auth ) - { - $logFile = PIWIK_INCLUDE_PATH.'/tests/resources/fake_logs.log'; # log file - - $opts = array('--idsite' => self::$idSite, - '--token-auth' => $token_auth, - '--recorders' => '4', - '--recorder-max-payload-size' => '2'); - - self::executeLogImporter($logFile, $opts); - } - - /** - * Logs a couple visits for the site we created and two new sites that do not - * exist yet. Visits are from Aug 12, 13 & 14 of 2012. - */ - protected static function logVisitsWithDynamicResolver( $token_auth ) - { - $logFile = PIWIK_INCLUDE_PATH.'/tests/resources/fake_logs_dynamic.log'; # log file - - $opts = array('--add-sites-new-hosts' => false, - '--token-auth' => $token_auth, - '--recorders' => '4', - '--recorder-max-payload-size' => '1'); - - self::executeLogImporter($logFile, $opts); - } - - /** - * Logs a couple visits for the site we created w/ all log importer options - * enabled. Visits are for Aug 11 of 2012. - */ - protected static function logVisitsWithAllEnabled( $token_auth ) - { - $logFile = PIWIK_INCLUDE_PATH.'/tests/resources/fake_logs_enable_all.log'; - - $opts = array('--idsite' => self::$idSite, - '--token-auth' => $token_auth, - '--recorders' => '4', - '--recorder-max-payload-size' => '2', - '--enable-static' => false, - '--enable-bots' => false, - '--enable-http-errors' => false, - '--enable-http-redirects' => false, - '--enable-reverse-dns' => false); - - self::executeLogImporter($logFile, $opts); - } - - /** - * Logs a couple visit using log entries that are tracking requests to a piwik.php file. - * Adds two visits to idSite=1 and two to non-existant sites. - */ - protected static function replayLogFile( $token_auth ) - { - $logFile = PIWIK_INCLUDE_PATH.'/tests/resources/fake_logs_replay.log'; - - $opts = array('--token-auth' => $token_auth, - '--recorders' => '4', - '--recorder-max-payload-size' => '2', - '--replay-tracking' => false); - - self::executeLogImporter($logFile, $opts); - } - - protected static function executeLogImporter( $logFile, $options ) - { - $python = Piwik_Common::isWindows() ? "C:\Python27\python.exe" : 'python'; - - // create the command - $cmd = $python - . ' "'.PIWIK_INCLUDE_PATH.'/misc/log-analytics/import_logs.py" ' # script loc - . '-ddd ' // debug - . '--url="'.self::getRootUrl().'tests/PHPUnit/proxy/" ' # proxy so that piwik uses test config files - ; - - foreach ($options as $name => $value) - { - $cmd .= $name; - if ($value !== false) - { - $cmd .= '="'.$value.'"'; - } - $cmd .= ' '; - } - - $cmd .= '"'.$logFile.'" 2>&1'; - - // run the command - exec($cmd, $output, $result); - if ($result !== 0) - { - throw new Exception("log importer failed: ".implode("\n", $output)."\n\ncommand used: $cmd"); - } - - return $output; - } -} diff --git a/tests/PHPUnit/Integration/LabelFilterTest.php b/tests/PHPUnit/Integration/LabelFilterTest.php index aa7c4eb46d..44126a963f 100644 --- a/tests/PHPUnit/Integration/LabelFilterTest.php +++ b/tests/PHPUnit/Integration/LabelFilterTest.php @@ -12,20 +12,7 @@ */ class Test_Piwik_Integration_LabelFilter extends IntegrationTestCase { - protected static $dateTime = '2010-03-06 11:22:33'; - protected static $idSite = 1; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -39,6 +26,9 @@ class Test_Piwik_Integration_LabelFilter extends IntegrationTestCase public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $dateTime = self::$fixture->dateTime; + $labelsToTest = array( // first level 'shouldBeNoData' => 'nonExistent', @@ -60,8 +50,8 @@ class Test_Piwik_Integration_LabelFilter extends IntegrationTestCase foreach ($labelsToTest as $suffix => $label) { $return[] = array('Actions.getPageUrls', array( 'testSuffix' => '_' . $suffix, - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'otherRequestParameters' => array( 'label' => urlencode($label), 'expanded' => 0 @@ -72,8 +62,8 @@ class Test_Piwik_Integration_LabelFilter extends IntegrationTestCase $label = 'dir'; $return[] = array('Actions.getPageUrls', array( 'testSuffix' => '_' . $label . '_range', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'otherRequestParameters' => array( 'date' => '2010-03-06,2010-03-08', 'label' => urlencode($label), @@ -83,8 +73,8 @@ class Test_Piwik_Integration_LabelFilter extends IntegrationTestCase $return[] = array('Actions.getPageTitles', array( 'testSuffix' => '_titles', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'otherRequestParameters' => array( // note: title has no blank prefixed here. in the report it has. 'label' => urlencode('incredible title! <>,;'), @@ -94,8 +84,8 @@ class Test_Piwik_Integration_LabelFilter extends IntegrationTestCase $return[] = array('Actions.getPageTitles', array( 'testSuffix' => '_titlesRecursive', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'otherRequestParameters' => array( 'label' => urlencode( ' ' . // test trimming @@ -109,8 +99,8 @@ class Test_Piwik_Integration_LabelFilter extends IntegrationTestCase $keyword = '<>&\"the pdo extension is required for this adapter but the extension is not loaded'; $searchEngineTest = array( 'testSuffix' => '_keywords_html', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'otherRequestParameters' => array( 'label' => urlencode('Google>' . urlencode($keyword)), 'expanded' => 0 @@ -128,42 +118,7 @@ class Test_Piwik_Integration_LabelFilter extends IntegrationTestCase { return 'LabelFilter'; } - - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useThirdPartyCookie = 1); - - $t->setUrlReferrer('http://www.google.com.vn/url?sa=t&rct=j&q=%3C%3E%26%5C%22the%20pdo%20extension%20is%20required%20for%20this%20adapter%20but%20the%20extension%20is%20not%20loaded&source=web&cd=4&ved=0FjAD&url=http%3A%2F%2Fforum.piwik.org%2Fread.php%3F2%2C1011&ei=y-HHAQ&usg=AFQjCN2-nt5_GgDeg&cad=rja'); - $t->setUrl('http://example.org/%C3%A9%C3%A9%C3%A9%22%27...%20%3Cthis%20is%20cool%3E!'); - self::checkResponse($t->doTrackPageView('incredible title! <>,;')); - - $t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - self::checkResponse($t->doTrackPageView('incredible title! <>,;')); - - $t->setUrl('http://example.org/dir/file.php?foo=bar&foo2=bar2'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); - self::checkResponse($t->doTrackPageView('incredible parent title! <>,; / subtitle <>,;')); - - $t->setUrl('http://example.org/dir2/file.php?foo=bar&foo2=bar'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); - self::checkResponse($t->doTrackPageView('incredible title! <>,;')); - - $t->setUrl('http://example.org/dir2/sub/0/file.php'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); - self::checkResponse($t->doTrackPageView('incredible title! <>,;')); - - $t->setUrl('http://example.org/0'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); - self::checkResponse($t->doTrackPageView('I am URL zero!')); - - } } +Test_Piwik_Integration_LabelFilter::$fixture = new Test_Piwik_Fixture_OneVisitSeveralPageViews(); + diff --git a/tests/PHPUnit/Integration/ManyVisitorsOneWebsiteTest.php b/tests/PHPUnit/Integration/ManyVisitorsOneWebsiteTest.php index 9185998624..0ab4ecab47 100755 --- a/tests/PHPUnit/Integration/ManyVisitorsOneWebsiteTest.php +++ b/tests/PHPUnit/Integration/ManyVisitorsOneWebsiteTest.php @@ -17,55 +17,7 @@ require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/MockLocationProvider.php'; */ class Test_Piwik_Integration_ManyVisitorsOneWebsiteTest extends IntegrationTestCase { - const GEOIP_IMPL_TO_TEST = 'geoip_php'; - - protected static $idSite = 1; - protected static $dateTime = '2010-01-03 11:22:33'; - - public static $ips = array( - '194.57.91.215', // in Besançon, FR (unicode city name) - '::ffff:137.82.130.49', // in British Columbia (mapped ipv4) - '137.82.130.0', // anonymization tests - '137.82.0.0', - '2001:db8:85a3:0:0:8a2e:370:7334', // ipv6 (geoip lookup not supported) - '113.62.1.1', // in Lhasa, Tibet - '151.100.101.92', // in Rome, Italy (using country DB, so only Italy will show) - '103.29.196.229', // in Indonesia (Bali), (only Indonesia will show up) - ); - - private static $ipsIndex = 0; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::downloadGeoIpDbs(); - - self::setMockLocationProvider(); - self::trackVisits(9, false); - - self::setLocationProvider('GeoIPCity.dat'); - self::trackVisits(2, true, $useLocal = false); - self::trackVisits(4, true, $useLocal = false, $doBulk = true); - - self::setLocationProvider('GeoIP.dat'); - self::trackVisits(2, true); - - self::trackOtherVisits(); - - self::setLocationProvider('GeoIPCity.dat'); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } - - public static function tearDownAfterClass() - { - self::unsetLocationProvider(); - parent::tearDownAfterClass(); - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -79,186 +31,52 @@ class Test_Piwik_Integration_ManyVisitorsOneWebsiteTest extends IntegrationTestC public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $dateTime = self::$fixture->dateTime; + // Note: we must set 'UserCountry.getLocationFromIP' since it's "excluded" by default in setApiNotToCall $apiToCall = array('UserCountry'); return array( array( $apiToCall, - array( 'idSite' => self::$idSite, - 'date' => self::$dateTime, + array( 'idSite' => $idSite, + 'date' => $dateTime, 'periods' => array('month'))), - array($apiToCall, array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => $idSite, + 'date' => $dateTime, 'periods' => array('month'), 'testSuffix' => '_segment_region', 'segment' => 'region==P3;country==gb')), - array($apiToCall, array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => $idSite, + 'date' => $dateTime, 'periods' => array('month'), 'testSuffix' => '_segment_city', 'segment' => 'city==Stratford-upon-Avon;region==P3;country==gb')), - array($apiToCall, array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => $idSite, + 'date' => $dateTime, 'periods' => array('month'), 'testSuffix' => '_segment_lat_long', 'segment' => 'lat>45;lat<49.3;long>-125;long<-122')), - array('UserCountry.getCountry', array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array('UserCountry.getCountry', array('idSite' => $idSite, + 'date' => $dateTime, 'periods' => array('month'), 'testSuffix' => '_segment_continent', 'segment' => 'continent==eur')), array(array('UserCountry.getLocationFromIP', 'Live.getLastVisitsDetails'), array( - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'periods' => array('month'), 'otherRequestParameters' => array('ip' => '194.57.91.215') )), ); } - - public static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime, 0, "Site 1"); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'all', 'url', 'http', 'contains', false, 5); - } - - protected static function trackVisits( $visitorCount, $setIp = false, $useLocal = true, $doBulk = false ) - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - - // use local tracker so mock location provider can be used - $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useLocal); - if ($doBulk) - { - $t->enableBulkTracking(); - $t->setTokenAuth(self::getTokenAuth()); - } - for ($i = 0; $i != $visitorCount; ++$i) - { - $t->setNewVisitorId(); - if ($setIp) - { - $t->setIp(self::$ips[self::$ipsIndex]); - ++self::$ipsIndex; - } - else - { - $t->setIp("1.2.4.$i"); - } - - // first visit - $date = Piwik_Date::factory($dateTime)->addDay($i); - $t->setForceVisitDateTime($date->getDatetime()); - $t->setUrl("http://piwik.net/grue/lair"); - $r = $t->doTrackPageView('It\'s pitch black...'); - if (!$doBulk) - { - self::checkResponse($r); - } - - // second visit - $date = $date->addHour(1); - $t->setForceVisitDateTime($date->getDatetime()); - $t->setUrl("http://piwik.net/space/quest/iv"); - $r = $t->doTrackPageView("Space Quest XII"); - if (!$doBulk) - { - self::checkResponse($r); - } - } - if ($doBulk) - { - self::checkResponse($t->doBulkTrack()); - } - } - - protected static function trackOtherVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - - $t = self::getTracker($idSite, $dateTime, $defaultInit = true); - $t->setTokenAuth(self::getTokenAuth()); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addDay(20)->getDatetime()); - $t->setIp('194.57.91.215'); - $t->setCountry('us'); - $t->setRegion('CA'); - $t->setCity('not a city'); - $t->setLatitude(1); - $t->setLongitude(2); - $t->setUrl("http://piwik.net/grue/lair"); - self::checkResponse($t->doTrackPageView('It\'s pitch black...')); - } - - public static function setLocationProvider( $file ) - { - Piwik_UserCountry_LocationProvider_GeoIp::$dbNames['loc'] = array($file); - Piwik_UserCountry_LocationProvider_GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files'; - Piwik_UserCountry_LocationProvider::$providers = null; - Piwik_UserCountry_LocationProvider::setCurrentProvider(self::GEOIP_IMPL_TO_TEST); - - if (Piwik_UserCountry_LocationProvider::getCurrentProviderId() !== self::GEOIP_IMPL_TO_TEST) - { - throw new Exception("Failed to set the current location provider to '".self::GEOIP_IMPL_TO_TEST."'."); - } - - $possibleFiles = Piwik_UserCountry_LocationProvider_GeoIp::$dbNames['loc']; - if (Piwik_UserCountry_LocationProvider_GeoIp::getPathToGeoIpDatabase($possibleFiles) === false) - { - throw new Exception("The GeoIP location provider cannot find the '$file' file! Tests will fail."); - } - } - - public static function setMockLocationProvider() - { - Piwik_UserCountry_LocationProvider::$providers = null; - Piwik_UserCountry_LocationProvider::setCurrentProvider('mock_provider'); - MockLocationProvider::$locations = array( - self::makeLocation('Stratford-upon-Avon', 'P3', 'gb', 123.456, 21.321), // template location - - // same region, different city, same country - self::makeLocation('Nuneaton and Bedworth', 'P3', 'gb'), - - // same region, city & country (different lat/long) - self::makeLocation('Stratford-upon-Avon', 'P3', 'gb', 124.456, 22.231), - - // same country, different region & city - self::makeLocation('London', 'H9', 'gb'), - - // same country, different region, same city - self::makeLocation('Stratford-upon-Avon', 'G5', 'gb'), - - // different country, diff region, same city - self::makeLocation('Stratford-upon-Avon', '66', 'ru'), - - // different country, diff region (same as last), different city - self::makeLocation('Hluboká nad Vltavou', '66', 'ru'), - - // different country, diff region (same as last), same city - self::makeLocation('Stratford-upon-Avon', '66', 'mk'), - - // unknown location - self::makeLocation(null, null, null), - ); - } - - public static function unsetLocationProvider() - { - Piwik_UserCountry_LocationProvider::setCurrentProvider('default'); - } - - public static function makeLocation( $city, $region, $country, $lat = null, $long = null ) - { - return array(Piwik_UserCountry_LocationProvider::CITY_NAME_KEY => $city, - Piwik_UserCountry_LocationProvider::REGION_CODE_KEY => $region, - Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY => $country, - Piwik_UserCountry_LocationProvider::LATITUDE_KEY => $lat, - Piwik_UserCountry_LocationProvider::LONGITUDE_KEY => $long); - } } + +Test_Piwik_Integration_ManyVisitorsOneWebsiteTest::$fixture + = new Test_Piwik_Fixture_ManyVisitsWithGeoIP(); + diff --git a/tests/PHPUnit/Integration/NoVisitTest.php b/tests/PHPUnit/Integration/NoVisitTest.php index 436830118b..c9b5d18238 100755 --- a/tests/PHPUnit/Integration/NoVisitTest.php +++ b/tests/PHPUnit/Integration/NoVisitTest.php @@ -13,20 +13,7 @@ */ class Test_Piwik_Integration_NoVisit extends IntegrationTestCase { - protected static $idSite = 1; - protected static $dateTime = '2009-01-04 00:11:42'; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -42,10 +29,10 @@ class Test_Piwik_Integration_NoVisit extends IntegrationTestCase { // this will output empty XML result sets as no visit was tracked return array( - array('all', array('idSite' => self::$idSite, - 'date' => self::$dateTime)), - array('all', array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array('all', array('idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime)), + array('all', array('idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime, 'periods' => array('day', 'week'), 'setDateLastN' => true, 'testSuffix' => '_PeriodIsLast')), @@ -56,85 +43,7 @@ class Test_Piwik_Integration_NoVisit extends IntegrationTestCase { return 'noVisit'; } +} - public static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - - Piwik_SitesManager_API::getInstance()->setSiteSpecificUserAgentExcludeEnabled(true); - Piwik_SitesManager_API::getInstance()->setGlobalExcludedUserAgents('globalexcludeduseragent'); - - /* - // Trigger invalid website - $trackerInvalidWebsite = self::getTracker($idSiteFake = 0, $dateTime, $defaultInit = true); - $response = Piwik_Http::fetchRemoteFile($trackerInvalidWebsite->getUrlTrackPageView()); - self::assertTrue(strpos($response, 'Invalid idSite') !== false, 'invalid website ID'); - - // Trigger wrong website - $trackerWrongWebsite = self::getTracker($idSiteFake = 33, $dateTime, $defaultInit = true); - $response = Piwik_Http::fetchRemoteFile($trackerWrongWebsite->getUrlTrackPageView()); - self::assertTrue(strpos($response, 'The requested website id = 33 couldn\'t be found') !== false, 'non-existent website ID'); - */ - - // Trigger empty request - $trackerUrl = self::getTrackerUrl(); - $response = Piwik_Http::fetchRemoteFile($trackerUrl); - self::assertTrue(strpos($response, 'is a free open source web') !== false, 'Piwik empty request response not correct: ' . $response); - - $t = self::getTracker($idSite, $dateTime, $defaultInit = true); - - // test GoogleBot UA visitor - $t->setUserAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); - self::checkResponse($t->doTrackPageView('bot visit, please do not record')); - - // Test IP Exclusion works with or without IP exclusion - foreach (array(false, true) as $enable) { - $excludedIp = '154.1.12.34'; - Piwik_SitesManager_API::getInstance()->updateSite($idSite, 'new site name', $url = array('http://site.com'), $ecommerce = 0, $ss = 1, $ss_kwd = '', $ss_cat = '', $excludedIp . ',1.2.3.4', $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = 'excludeduseragentstring'); - - // Enable IP Anonymization - $t->DEBUG_APPEND_URL = '&forceIpAnonymization=' . (int)$enable; - - // test with excluded User Agent - $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729) (excludeduseragentstring)'); - $t->setIp('211.1.2.3'); - self::checkResponse($t->doTrackPageView('visit from excluded User Agent')); - - // test w/ global excluded User Agent - $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729) (globalexcludeduseragent)'); - $t->setIp('211.1.2.3'); - self::checkResponse($t->doTrackPageView('visit from global excluded User Agent')); - - // test with excluded IP - $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)'); // restore normal user agent - $t->setIp($excludedIp); - self::checkResponse($t->doTrackPageView('visit from IP excluded')); - - // test with global list of excluded IPs - $excludedIpBis = '145.5.3.4'; - Piwik_SitesManager_API::getInstance()->setGlobalExcludedIps($excludedIpBis); - $t->setIp($excludedIpBis); - self::checkResponse($t->doTrackPageView('visit from IP globally excluded')); - } - - try { - @$t->setAttributionInfo(array()); - self::fail(); - } catch (Exception $e) { - } - - try { - $t->setAttributionInfo(json_encode('test')); - self::fail(); - } catch (Exception $e) { - } +Test_Piwik_Integration_NoVisit::$fixture = new Test_Piwik_Fixture_InvalidVisits(); - $t->setAttributionInfo(json_encode(array())); - } -} diff --git a/tests/PHPUnit/Integration/NonUnicodeTest.php b/tests/PHPUnit/Integration/NonUnicodeTest.php index c03385ed05..995add7567 100755 --- a/tests/PHPUnit/Integration/NonUnicodeTest.php +++ b/tests/PHPUnit/Integration/NonUnicodeTest.php @@ -12,20 +12,7 @@ */ class Test_Piwik_Integration_NonUnicodeTest extends IntegrationTestCase { - protected static $idSite1 = 1; - protected static $dateTime = '2010-01-03 11:22:33'; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsites(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -47,8 +34,8 @@ class Test_Piwik_Integration_NonUnicodeTest extends IntegrationTestCase ); return array( - array($apiToCall, array('idSite' => self::$idSite1, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => self::$fixture->idSite1, + 'date' => self::$fixture->dateTime, 'periods' => 'day')) ); } @@ -58,73 +45,8 @@ class Test_Piwik_Integration_NonUnicodeTest extends IntegrationTestCase return 'NonUnicode'; } - /** - * One site with custom search parameters, - * One site using default search parameters, - * One site with disabled site search - */ - protected static function setUpWebsites() - { - Piwik_SitesManager_API::getInstance()->setGlobalSearchParameters($searchKeywordParameters='gkwd', $searchCategoryParameters='gcat'); - self::$idSite1 = self::createWebsite(Piwik_Date::factory(self::$dateTime)->getDatetime(), 0, "Site 1 - Site search", $siteurl=false, $search=1, $searchKwd='q,mykwd,p', $searchCat='cats' ); - } - - protected static function trackVisits() - { - self::assertTrue(function_exists('mb_check_encoding'), ' check mb_check_encoding '); - self::assertTrue(function_exists('mb_convert_encoding'), ' check mb_convert_encoding '); - - // Visitor site1 - $visitor = self::getTracker(self::$idSite1, self::$dateTime, $defaultInit = true); - - // Test w/ iso-8859-15 - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.3)->getDatetime()); - $visitor->setUrlReferrer('http://anothersite.com/whatever.html?whatever=Ato%FC'); - // Also testing that the value is encoded when passed as an array - $visitor->setUrl('http://example.org/index.htm?random=param&mykwd[]=Search 2%FC&test&cats= Search Kategory &search_count=INCORRECT!'); - $visitor->setPageCharset('iso-8859-15'); - self::checkResponse($visitor->doTrackPageView('Site Search results')); - $visitor->setPageCharset(''); - - // Test w/ windows-1251 - $visitor = self::getTracker(self::$idSite1, self::$dateTime, $defaultInit = true); - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.3)->getDatetime()); - $visitor->setUrlReferrer('http://anothersite.com/whatever.html?txt=%EC%E5%F8%EA%EE%E2%FB%E5'); - $visitor->setUrl('http://example.org/page/index.htm?whatever=%EC%E5%F8%EA%EE%E2%FB%E5'); - $visitor->setPageCharset('windows-1251'); - self::checkResponse($visitor->doTrackPageView('Page title is always UTF-8')); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.4)->getDatetime()); - $nonUnicodeKeyword = '%EC%E5%F8%EA%EE%E2%FB%E5'; - $visitor->setUrl('http://example.org/page/index.htm?q='.$nonUnicodeKeyword); - $visitor->setPageCharset('windows-1251'); - self::checkResponse($visitor->doTrackPageView('Site Search')); - - - // Test URL with non unicode Site Search keyword - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.5)->getDatetime()); - //TESTS: on jenkins somehow the "<-was here" was cut off so removing this test case and simply append the wrong keyword -// $visitor->setUrl('http://example.org/page/index.htm?q=non unicode keyword %EC%E5%F8%EAe%EE%E2%FBf%E5 <-was here'); - $visitor->setUrl('http://example.org/page/index.htm?q=non unicode keyword %EC%E5%F8%EA%EE%E2%FB%E5'); - $visitor->setPageCharset('utf-8'); -// var_dump("hello \n"); -// var_dump($visitor->getUrlTrackPageView('Site Search')); - self::checkResponse($visitor->doTrackPageView('Site Search')); - - - $visitor->setPageCharset(''); - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.5)->getDatetime()); - $visitor->setUrl('http://example.org/exit-page'); - self::checkResponse($visitor->doTrackPageView('Page title is always UTF-8')); - - // Test set invalid page char set - $visitor = self::getTracker(self::$idSite1, self::$dateTime, $defaultInit = true); - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(1)->getDatetime()); - $visitor->setUrlReferrer('http://anothersite.com/whatever.html'); - $visitor->setUrl('http://example.org/index.htm?random=param&mykwd=a+keyword&test&cats= Search Kategory &search_count=INCORRECT!'); - $visitor->setPageCharset('GTF-42'); // galactic transformation format - self::checkResponse($visitor->doTrackPageView('Site Search results')); - $visitor->setPageCharset(''); - } } +Test_Piwik_Integration_NonUnicodeTest::$fixture = + new Test_Piwik_Fixture_SomeVisitsWithNonUnicodePageTitles(); + diff --git a/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRangeTest.php b/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRangeTest.php index a235b7a81f..23f3b114b8 100755 --- a/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRangeTest.php +++ b/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRangeTest.php @@ -15,41 +15,7 @@ */ class Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange extends IntegrationTestCase { - protected static $dateTimes = array( - '2010-12-14 01:00:00', - '2010-12-15 01:00:00', - '2010-12-25 01:00:00', - '2011-01-15 01:00:00', - '2011-01-16 01:00:00', - ); - protected static $idSite = 1; - protected static $idSite2 = 2; - - // one per visit - protected static $referrerUrls = array( - 'http://facebook.com/whatever', - 'http://www.facebook.com/another/path', - 'http://fb.me/?q=sdlfjs&n=slfjsd', - 'http://twitter.com/whatever2', - 'http://www.twitter.com/index?a=2334', - 'http://t.co/id/?y=dsfs', - 'http://www.flickr.com', - 'http://xanga.com', - 'http://skyrock.com', - 'http://mixi.jp', - ); - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -63,6 +29,8 @@ class Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange extends I public function getApiForTesting() { + $idSite = self::$fixture->idSite; + return array( // FIRST some MultiSites API goodness! @@ -83,7 +51,7 @@ class Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange extends I // test getOne call used in MobileMessaging SMS reports array('MultiSites.getOne', array( 'date' => '2010-12-15,2011-01-15', 'periods' => array('range'), - 'idSite' => self::$idSite, + 'idSite' => $idSite, // Testing without &pattern= so should return all sites )), @@ -121,53 +89,8 @@ class Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange extends I { return 'oneVisitor_oneWebsite_severalDays_DateRange'; } - - protected static function setUpWebsitesAndGoals() - { - self::$idSite = self::createWebsite(self::$dateTimes[0], $ecommerce = 0, $siteName = 'Site AAAAAA'); - self::$idSite2 =self::createWebsite(self::$dateTimes[0], $ecommerce = 0, $siteName = 'SITE BBbbBB'); - } - - protected static function trackVisits() - { - $dateTimes = self::$dateTimes; - $idSite = self::$idSite; - - $i = 0; - $ridx = 0; - foreach ($dateTimes as $dateTime) { - $i++; - $visitor = self::getTracker($idSite, $dateTime, $defaultInit = true); - // Fake the visit count cookie - $visitor->setDebugStringAppend("&_idvc=$i"); - - $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitor->setUrl('http://example.org/homepage'); - $visitor->setUrlReferrer(self::$referrerUrls[$ridx++]); - self::checkResponse($visitor->doTrackPageView('ou pas')); - - // Test change the IP, the visit should not be split but recorded to the same idvisitor - $visitor->setIp('200.1.15.22'); - - $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $visitor->setUrl('http://example.org/news'); - self::checkResponse($visitor->doTrackPageView('ou pas')); - - $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitor->setUrl('http://example.org/news'); - $visitor->setUrlReferrer(self::$referrerUrls[$ridx++]); - self::checkResponse($visitor->doTrackPageView('ou pas')); - - - if($i <= 3 ) { - - $visitor = self::getTracker(self::$idSite2, $dateTime, $defaultInit = true); - $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitor->setUrl('http://example.org/homepage'); - $visitor->setUrlReferrer(self::$referrerUrls[$ridx-1]); - self::checkResponse($visitor->doTrackPageView('Second website')); - } - } - } } +Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange::$fixture + = new Test_Piwik_Fixture_VisitsOverSeveralDays(); + diff --git a/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTestsTest.php b/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTestsTest.php index 56f4a58d6d..4632eeb60b 100755 --- a/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTestsTest.php +++ b/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTestsTest.php @@ -12,66 +12,13 @@ */ class Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTests extends IntegrationTestCase { - protected static $dateTimes = array( - '2010-12-14 01:00:00', - '2010-12-15 01:00:00', - '2010-12-25 01:00:00', - '2011-01-15 01:00:00', - '2011-01-16 01:00:00', - ); - protected static $idSite = 1; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below test definition public function getOutputPrefix() { return 'oneVisitor_oneWebsite_severalDays_DateRange'; } - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTimes[0]); - } - - protected static function trackVisits() - { - $dateTimes = self::$dateTimes; - $idSite = self::$idSite; - - $i = 0; - foreach ($dateTimes as $dateTime) { - $i++; - $visitor = self::getTracker($idSite, $dateTime, $defaultInit = true); - // Fake the visit count cookie - $visitor->setDebugStringAppend("&_idvc=$i"); - - $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitor->setUrl('http://example.org/homepage'); - self::checkResponse($visitor->doTrackPageView('ou pas')); - - // Test change the IP, the visit should not be split but recorded to the same idvisitor - $visitor->setIp('200.1.15.22'); - - $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $visitor->setUrl('http://example.org/news'); - self::checkResponse($visitor->doTrackPageView('ou pas')); - - $visitor->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitor->setUrl('http://example.org/news'); - self::checkResponse($visitor->doTrackPageView('ou pas')); - } - } - /** * @dataProvider getApiForTesting * @group Integration @@ -84,6 +31,8 @@ class Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange_Archiving public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $apiToCall = array('Actions.getPageUrls', 'VisitsSummary.get', 'UserSettings.getResolution', @@ -101,7 +50,7 @@ class Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange_Archiving $result = array(); for ($i = 0; $i <= 1; $i++) { foreach ($segments as $segment) { - $result[] = array($apiToCall, array('idSite' => self::$idSite, 'date' => '2010-12-15,2011-01-15', + $result[] = array($apiToCall, array('idSite' => $idSite, 'date' => '2010-12-15,2011-01-15', 'periods' => array('range'), 'segment' => $segment)); } } @@ -137,13 +86,12 @@ class Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange_Archiving $sql = "SELECT count(*) FROM " . Piwik_Common::prefixTable($table) . " WHERE period = " . Piwik::$idPeriods['range']; $countBlobs = Zend_Registry::get('db')->fetchOne($sql); - // Uncomment to display a more verbose content of the table, when this test fails -// if( $expectedRows!= $countBlobs) { -// $var = Zend_Registry::get('db')->fetchAll("SELECT * FROM " . Piwik_Common::prefixTable($table) . " WHERE period = " . Piwik::$idPeriods['range']); -// Piwik::log($var); die('t'); -// } $this->assertEquals($expectedRows, $countBlobs, "$table expected $expectedRows, got $countBlobs"); } } } + +Test_Piwik_Integration_OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTests::$fixture + = new Test_Piwik_Fixture_VisitsOverSeveralDays(); + diff --git a/tests/PHPUnit/Integration/OneVisitorTwoVisitsTest.php b/tests/PHPUnit/Integration/OneVisitorTwoVisitsTest.php index 1f9eeed561..889b125f39 100755 --- a/tests/PHPUnit/Integration/OneVisitorTwoVisitsTest.php +++ b/tests/PHPUnit/Integration/OneVisitorTwoVisitsTest.php @@ -18,20 +18,7 @@ */ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase { - protected static $idSite = 1; - protected static $dateTime = '2010-03-06 11:22:33'; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class public function setUp() { @@ -55,11 +42,14 @@ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $dateTime = self::$fixture->dateTime; + $enExtraParam = array('expanded' => 1, 'flat' => 1, 'include_aggregate_rows' => 0, 'translateColumnNames' => 1); $bulkUrls = array( - "idSite=".self::$idSite."&date=2010-03-06&format=json&expanded=1&period=day&method=VisitsSummary.get", - "idSite=".self::$idSite."&date=2010-03-06&format=xml&expanded=1&period=day&method=VisitsSummary.get", - "idSite=".self::$idSite."&date=2010-03-06&format=json&expanded=1&period=day&method=" + "idSite=".$idSite."&date=2010-03-06&format=json&expanded=1&period=day&method=VisitsSummary.get", + "idSite=".$idSite."&date=2010-03-06&format=xml&expanded=1&period=day&method=VisitsSummary.get", + "idSite=".$idSite."&date=2010-03-06&format=json&expanded=1&period=day&method=" . "VisitorInterest.getNumberOfVisitsPerVisitDuration" ); foreach ($bulkUrls as &$url) @@ -67,11 +57,11 @@ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase $url = urlencode($url); } return array( - array('all', array('idSite' => self::$idSite, 'date' => self::$dateTime)), + array('all', array('idSite' => $idSite, 'date' => $dateTime)), // test API.get (for bug that incorrectly reorders columns of CSV output) // note: bug only affects rows after first - array('API.get', array('idSite' => self::$idSite, + array('API.get', array('idSite' => $idSite, 'date' => '2009-10-01', 'format' => 'csv', 'periods' => array('month'), @@ -83,8 +73,8 @@ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase array('API.getBulkRequest', array('otherRequestParameters' => array('urls' => $bulkUrls))), // test API.getProcessedReport w/ report that is its own 'actionToLoadSubTables' - array('API.getProcessedReport', array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array('API.getProcessedReport', array('idSite' => $idSite, + 'date' => $dateTime, 'periods' => array('week'), 'apiModule' => 'Actions', 'apiAction' => 'getPageUrls', @@ -92,18 +82,18 @@ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase 'testSuffix' => '__subtable')), // test hideColumns && showColumns parameters - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, 'periods' => 'day', + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => 'day', 'testSuffix' => '_hideColumns_', 'otherRequestParameters' => array( 'hideColumns' => 'nb_visits_converted,max_actions,bounce_count,nb_hits,' .'nb_visits,nb_actions,sum_visit_length,avg_time_on_site' ))), - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, 'periods' => 'day', + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => 'day', 'testSuffix' => '_showColumns_', 'otherRequestParameters' => array( 'showColumns' => 'nb_visits,nb_actions,nb_hits' ))), - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, 'periods' => 'day', + array('VisitsSummary.get', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => 'day', 'testSuffix' => '_hideAllColumns_', 'otherRequestParameters' => array( 'hideColumns' => 'nb_visits_converted,max_actions,bounce_count,nb_hits,' @@ -112,7 +102,7 @@ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase ))), // test hideColumns w/ API.getProcessedReport - array('API.getProcessedReport', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('API.getProcessedReport', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => 'day', 'apiModule' => 'Actions', 'apiAction' => 'getPageTitles', 'testSuffix' => '_hideColumns_', 'otherRequestParameters' => array( @@ -120,14 +110,14 @@ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase 'bounce_rate,nb_hits,nb_visits,avg_time_on_page' ))), - array('API.getProcessedReport', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('API.getProcessedReport', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => 'day', 'apiModule' => 'Actions', 'apiAction' => 'getPageTitles', 'testSuffix' => '_showColumns_', 'otherRequestParameters' => array( 'showColumns' => 'nb_visits_converted,xuena,entry_nb_visits,'. 'bounce_rate,nb_hits' ))), - array('API.getProcessedReport', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('API.getProcessedReport', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => 'day', 'apiModule' => 'VisitTime', 'apiAction' => 'getVisitInformationPerServerTime', 'testSuffix' => '_showColumnsWithProcessedMetrics_', @@ -136,7 +126,7 @@ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase ))), // test hideColumns w/ expanded=1 - array('Actions.getPageTitles', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('Actions.getPageTitles', array('idSite' => $idSite, 'date' => $dateTime, 'periods' => 'day', 'testSuffix' => '_hideColumns_', 'otherRequestParameters' => array( 'hideColumns' => 'nb_visits_converted,entry_nb_visits,'. @@ -156,7 +146,7 @@ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase */ public function testArchiveSinglePreFetchBlob() { - $archive = Piwik_Archive::build(self::$idSite, 'day', self::$dateTime); + $archive = Piwik_Archive::build(self::$fixture->idSite, 'day', self::$fixture->dateTime); $archive->preFetchBlob('Actions_actions'); $cache = $archive->getBlobCache(); @@ -175,99 +165,8 @@ class Test_Piwik_Integration_OneVisitorTwoVisits extends IntegrationTestCase $this->assertTrue($foundSubtable, "Actions_actions subtable was not loaded"); } +} - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - - Piwik_SitesManager_API::getInstance()->setSiteSpecificUserAgentExcludeEnabled(false); - - $t = self::getTracker($idSite, $dateTime, $defaultInit = true); - - $t->disableCookieSupport(); - - $t->setUrlReferrer('http://referer.com/page.htm?param=valuewith some spaces'); - - // testing URL excluded parameters - $parameterToExclude = 'excluded_parameter'; - Piwik_SitesManager_API::getInstance()->updateSite($idSite, 'new name', $url = array('http://site.com'), $ecommerce = 0, $siteSearch = null, - $searchKeywordParameters = null, - $searchCategoryParameters = null, $excludedIps = null, $parameterToExclude . ',anotherParameter', - $timezone = null, $currency = null, $group = null, $startDate = null, - // test that visit won't be excluded since site-specific exclude is not enabled - $excludedUserAgents = 'mozilla' - ); - - // Record 1st page view - $urlPage1 = 'http://example.org/index.htm?excluded_Parameter=SHOULD_NOT_DISPLAY¶meter=Should display'; - $t->setUrl($urlPage1); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // testing that / and index.htm above record with different URLs - // Recording the 2nd page after 3 minutes - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.05)->getDatetime()); - $urlPage2 = 'http://example.org/'; - $t->setUrl($urlPage2); -// $t->setUrlReferrer($urlPage1); - self::checkResponse($t->doTrackPageView('Second page view - should be registered as URL /')); - -// $t->setUrlReferrer($urlPage2); - // Click on external link after 6 minutes (3rd action) - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - self::checkResponse($t->doTrackAction('http://dev.piwik.org/svn', 'link')); - - // Click on file download after 12 minutes (4th action) - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - self::checkResponse($t->doTrackAction('http://piwik.org/path/again/latest.zip', 'download')); - - // Click on two more external links, one the same as before (5th & 6th actions) - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.22)->getDateTime()); - self::checkResponse($t->doTrackAction('http://outlinks.org/other_outlink', 'link')); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.25)->getDateTime()); - self::checkResponse($t->doTrackAction('http://dev.piwik.org/svn', 'link')); - - // Create Goal 1: Triggered by JS, after 18 minutes - $idGoal = Piwik_Goals_API::getInstance()->addGoal($idSite, 'triggered js', 'manually', '', ''); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); - - // Change to Thai browser to ensure the conversion is credited to FR instead (the visitor initial country) - $t->setBrowserLanguage('th'); - self::checkResponse($t->doTrackGoal($idGoal, $revenue = 42)); - - // Track same Goal twice (after 24 minutes), should only be tracked once - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); - self::checkResponse($t->doTrackGoal($idGoal, $revenue = 42)); - - $t->setBrowserLanguage('fr'); - // Final page view (after 27 min) - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.45)->getDatetime()); - $t->setUrl('http://example.org/index.htm#ignoredFragment#'); - self::checkResponse($t->doTrackPageView('Looking at homepage (again)...')); - - // - - // End of first visit: 24min - - // Create Goal 2: Matching on URL - Piwik_Goals_API::getInstance()->addGoal($idSite, 'matching purchase.htm', 'url', '(.*)store\/purchase\.(.*)', 'regex', false, $revenue = 1); - - // - - // Start of returning visit, 1 hour after first page view - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $t->setUrl('http://example.org/store/purchase.htm'); - $t->setUrlReferrer('http://search.yahoo.com/search?p=purchase'); - // Temporary, until we implement 1st party cookies in PiwikTracker - $t->DEBUG_APPEND_URL = '&_idvc=2'; +Test_Piwik_Integration_OneVisitorTwoVisits::$fixture = new Test_Piwik_Fixture_OneVisitorTwoVisits(); +Test_Piwik_Integration_OneVisitorTwoVisits::$fixture->excludeMozilla = true; - // Goal Tracking URL matching, testing custom referer including keyword - self::checkResponse($t->doTrackPageView('Checkout/Purchasing...')); - // - - // End of second visit - } -} diff --git a/tests/PHPUnit/Integration/OneVisitorTwoVisits_withCookieSupportTest.php b/tests/PHPUnit/Integration/OneVisitorTwoVisits_withCookieSupportTest.php index 5442fef4e8..cdc3b669ea 100755 --- a/tests/PHPUnit/Integration/OneVisitorTwoVisits_withCookieSupportTest.php +++ b/tests/PHPUnit/Integration/OneVisitorTwoVisits_withCookieSupportTest.php @@ -12,20 +12,7 @@ */ class Test_Piwik_Integration_OneVisitorTwoVisits_WithCookieSupport extends IntegrationTestCase { - protected static $idSite = 1; - protected static $dateTime = '2010-03-06 11:22:33'; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class /** * @dataProvider getApiForTesting @@ -45,7 +32,7 @@ class Test_Piwik_Integration_OneVisitorTwoVisits_WithCookieSupport extends Integ 'Actions', 'Live.getLastVisitsDetails'); return array( - array($apiToCall, array('idSite' => self::$idSite, 'date' => self::$dateTime)) + array($apiToCall, array('idSite' => self::$fixture->idSite, 'date' => self::$fixture->dateTime)) ); } @@ -53,98 +40,9 @@ class Test_Piwik_Integration_OneVisitorTwoVisits_WithCookieSupport extends Integ { return 'OneVisitorTwoVisits_withCookieSupport'; } +} - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - $t = self::getTracker(self::$idSite, self::$dateTime, $defaultInit = true, $useThirdPartyCookie = 1); - $t->DEBUG_APPEND_URL = '&forceUseThirdPartyCookie=1'; - - $dateTime = self::$dateTime; - $idSite = self::$idSite; - - $t->disableCookieSupport(); - - $t->setUrlReferrer('http://referer.com/page.htm?param=valuewith some spaces'); - - // testing URL excluded parameters - $parameterToExclude = 'excluded_parameter'; - Piwik_SitesManager_API::getInstance()->updateSite($idSite, 'new name', $url = array('http://site.com'), $ecommerce = 0, $ss = 1, $ss_kwd = '', $ss_cat = 'notparam', $excludedIps = null, $parameterToExclude . ',anotherParameter'); - - // Record 1st page view - $urlPage1 = 'http://example.org/index.htm?excluded_Parameter=SHOULD_NOT_DISPLAY¶meter=Should display'; - $t->setUrl($urlPage1); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // testing that / and index.htm above record with different URLs - // Recording the 2nd page after 3 minutes - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.05)->getDatetime()); - $urlPage2 = 'http://example.org/'; - $t->setUrl($urlPage2); -// $t->setUrlReferrer($urlPage1); - self::checkResponse($t->doTrackPageView('Second page view - should be registered as URL /')); - -// $t->setUrlReferrer($urlPage2); - // Click on external link after 6 minutes (3rd action) - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - self::checkResponse($t->doTrackAction('http://dev.piwik.org/svn', 'link')); - - // Click on file download after 12 minutes (4th action) - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - self::checkResponse($t->doTrackAction('http://piwik.org/path/again/latest.zip', 'download')); - - // Click on two more external links, one the same as before (5th & 6th actions) - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.22)->getDateTime()); - self::checkResponse($t->doTrackAction('http://outlinks.org/other_outlink', 'link')); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.25)->getDateTime()); - self::checkResponse($t->doTrackAction('http://dev.piwik.org/svn', 'link')); - - // Create Goal 1: Triggered by JS, after 18 minutes - $idGoal = Piwik_Goals_API::getInstance()->addGoal($idSite, 'triggered js', 'manually', '', ''); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); - - // Change to Thai browser to ensure the conversion is credited to FR instead (the visitor initial country) - $t->setBrowserLanguage('th'); - self::checkResponse($t->doTrackGoal($idGoal, $revenue = 42)); - - // Track same Goal twice (after 24 minutes), should only be tracked once - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); - self::checkResponse($t->doTrackGoal($idGoal, $revenue = 42)); - - - $t->setBrowserLanguage('fr'); - // Site Search request - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.42)->getDatetime()); - $t->setUrl('http://example.org/index.htm?q=Banks Own The World'); - self::checkResponse($t->doTrackPageView('Site Search request')); - - // Final page view (after 27 min) - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.45)->getDatetime()); - $t->setUrl('http://example.org/index.htm'); - self::checkResponse($t->doTrackPageView('Looking at homepage after site search...')); - - // - - // End of first visit: 24min - - // Create Goal 2: Matching on URL - Piwik_Goals_API::getInstance()->addGoal($idSite, 'matching purchase.htm', 'url', '(.*)store\/purchase\.(.*)', 'regex', false, $revenue = 1); - - // - - // Start of returning visit, 1 hour after first page view - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $t->setUrl('http://example.org/store/purchase.htm'); - $t->setUrlReferrer('http://search.yahoo.com/search?p=purchase'); - // Temporary, until we implement 1st party cookies in PiwikTracker - $t->DEBUG_APPEND_URL = '&_idvc=2'; +Test_Piwik_Integration_OneVisitorTwoVisits_WithCookieSupport::$fixture = new Test_Piwik_Fixture_OneVisitorTwoVisits(); +Test_Piwik_Integration_OneVisitorTwoVisits_WithCookieSupport::$fixture->useThirdPartyCookies = true; +Test_Piwik_Integration_OneVisitorTwoVisits_WithCookieSupport::$fixture->useSiteSearch = true; - // Goal Tracking URL matching, testing custom referer including keyword - self::checkResponse($t->doTrackPageView('Checkout/Purchasing...')); - // - - // End of second visit - } -} diff --git a/tests/PHPUnit/Integration/OneVisitor_LongUrlsTruncatedTest.php b/tests/PHPUnit/Integration/OneVisitor_LongUrlsTruncatedTest.php index c9c519d344..8504b51b8d 100644 --- a/tests/PHPUnit/Integration/OneVisitor_LongUrlsTruncatedTest.php +++ b/tests/PHPUnit/Integration/OneVisitor_LongUrlsTruncatedTest.php @@ -10,20 +10,7 @@ */ class Test_Piwik_Integration_OneVisitor_LongUrlsTruncated extends IntegrationTestCase { - protected static $dateTime = '2010-03-06 01:22:33'; - protected static $idSite = 1; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -40,8 +27,8 @@ class Test_Piwik_Integration_OneVisitor_LongUrlsTruncated extends IntegrationTes $apiToCall = array('Referers.getKeywords', 'Actions.getPageUrls'); return array( - array($apiToCall, array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime, 'language' => 'fr', 'otherRequestParameters' => array('expanded' => 1, 'filter_truncate' => 2))) ); @@ -51,79 +38,7 @@ class Test_Piwik_Integration_OneVisitor_LongUrlsTruncated extends IntegrationTes { return 'OneVisitor_LongUrlsTruncated'; } - - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - // tests run in UTC, the Tracker in UTC - $dateTime = self::$dateTime; - $idSite = self::$idSite; - - // Visit 1: keyword and few URLs - $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useThirdPartyCookie = 1); - $t->setUrlReferrer('http://bing.com/search?q=Hello world'); - - // Generate a few page views that will be truncated - $t->setUrl('http://example.org/category/Page1'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page2'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page3'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page3'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page4'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page4'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page4'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category.htm'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/page.htm'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/index.htm'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/page.htm'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/page.htm'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/contact.htm'); - self::checkResponse($t->doTrackPageView('Hello')); - - // VISIT 2 = Another keyword - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $t->setUrlReferrer('http://www.google.com.vn/url?q=Salut'); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // Visit 3 = Another keyword - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - $t->setUrlReferrer('http://www.google.com.vn/url?q=Kia Ora'); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // Visit 4 = Kia Ora again - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(3)->getDatetime()); - $t->setUrlReferrer('http://www.google.com.vn/url?q=Kia Ora'); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // Visit 5 = Another search engine - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(4)->getDatetime()); - $t->setUrlReferrer('http://nz.search.yahoo.com/search?p=Kia Ora'); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // Visit 6 = Another search engine - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(5)->getDatetime()); - $t->setUrlReferrer('http://images.search.yahoo.com/search/images;_ylt=A2KcWcNKJzF?p=Kia%20Ora%20'); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // Visit 7 = Another search engine - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(6)->getDatetime()); - $t->setUrlReferrer('http://nz.bing.com/images/search?q=+++Kia+ora+++'); - self::checkResponse($t->doTrackPageView('incredible title!')); - } } +Test_Piwik_Integration_OneVisitor_LongUrlsTruncated::$fixture = new Test_Piwik_Fixture_SomeVisitsWithLongUrls(); + diff --git a/tests/PHPUnit/Integration/OneVisitor_NoKeywordSpecifiedTest.php b/tests/PHPUnit/Integration/OneVisitor_NoKeywordSpecifiedTest.php index fbe7be3e95..de5fe1ab80 100755 --- a/tests/PHPUnit/Integration/OneVisitor_NoKeywordSpecifiedTest.php +++ b/tests/PHPUnit/Integration/OneVisitor_NoKeywordSpecifiedTest.php @@ -14,20 +14,7 @@ */ class Test_Piwik_Integration_OneVisitor_NoKeywordSpecified extends IntegrationTestCase { - protected static $dateTime = '2010-03-06 11:22:33'; - protected static $idSite = 1; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -44,7 +31,9 @@ class Test_Piwik_Integration_OneVisitor_NoKeywordSpecified extends IntegrationTe $apiToCall = array('Referers.getKeywords', 'Live.getLastVisitsDetails'); return array( - array($apiToCall, array('idSite' => self::$idSite, 'date' => self::$dateTime, 'language' => 'fr')) + array($apiToCall, array('idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime, + 'language' => 'fr') ) ); } @@ -52,40 +41,7 @@ class Test_Piwik_Integration_OneVisitor_NoKeywordSpecified extends IntegrationTe { return 'OneVisitor_NoKeywordSpecified'; } - - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - // tests run in UTC, the Tracker in UTC - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useThirdPartyCookie = 1); - - // Also testing to record this as a bot while specifically allowing bots - $t->setUserAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); - $t->DEBUG_APPEND_URL .= '&bots=1'; - $t->DEBUG_APPEND_URL .= '&forceIpAnonymization=1'; - // VISIT 1 = Referrer is "Keyword not defined" - // Alsotrigger goal to check that attribution goes to this keyword - $t->setUrlReferrer('http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CC&url=http%3A%2F%2Fpiwik.org%2F&ei=&usg='); - $t->setUrl('http://example.org/this%20is%20cool!'); - self::checkResponse($t->doTrackPageView('incredible title!')); - $idGoal = Piwik_Goals_API::getInstance()->addGoal($idSite, 'triggered js', 'manually', '', ''); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); - self::checkResponse($t->doTrackGoal($idGoal, $revenue = 42)); - - // VISIT 2 = Referrer has keyword, but the URL should be rewritten - // in Live Output to point to google search result page - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - $t->setUrlReferrer('http://www.google.com.vn/url?sa=t&rct=j&q=%3C%3E%26%5C%22the%20pdo%20extension%20is%20required%20for%20this%20adapter%20but%20the%20extension%20is%20not%20loaded&source=web&cd=4&ved=0FjAD&url=http%3A%2F%2Fforum.piwik.org%2Fread.php%3F2%2C1011&ei=y-HHAQ&usg=AFQjCN2-nt5_GgDeg&cad=rja'); - - // Test with empty title, that the output of Live is valid - self::checkResponse($t->doTrackPageView('')); - - } } +Test_Piwik_Integration_OneVisitor_NoKeywordSpecified::$fixture = new Test_Piwik_Fixture_TwoVisitsNoKeywordWithBot(); + diff --git a/tests/PHPUnit/Integration/PeriodIsRange_DateIsLastN_MetadataAndNormalAPITest.php b/tests/PHPUnit/Integration/PeriodIsRange_DateIsLastN_MetadataAndNormalAPITest.php index 586495cb73..28586368cf 100755 --- a/tests/PHPUnit/Integration/PeriodIsRange_DateIsLastN_MetadataAndNormalAPITest.php +++ b/tests/PHPUnit/Integration/PeriodIsRange_DateIsLastN_MetadataAndNormalAPITest.php @@ -11,18 +11,8 @@ */ class Test_Piwik_Integration_PeriodIsRange_DateIsLastN_MetadataAndNormalAPI extends IntegrationTestCase { - protected static $dateTime = null; - protected static $width = 1111; - protected static $height = 222; - - protected static $idSite = 1; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - protected static $visitorId = '61e8cc2d51fea26d'; - - protected static $useEscapedQuotes = true; - protected static $doExtraQuoteTests = false; - + public static $fixture = null; + static $shouldSkipTestThisTime = false; public static function setUpBeforeClass() @@ -35,15 +25,17 @@ class Test_Piwik_Integration_PeriodIsRange_DateIsLastN_MetadataAndNormalAPI exte return; } + self::$fixture->dateTime = Piwik_Date::factory('now')->getDateTime(); parent::setUpBeforeClass(); - try { - self::$dateTime = Piwik_Date::factory('now')->getDateTime(); - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } + } + + public static function tearDownAfterClass() + { + if (self::$shouldSkipTestThisTime) { + return; + } + + parent::tearDownAfterClass(); } /** @@ -62,6 +54,9 @@ class Test_Piwik_Integration_PeriodIsRange_DateIsLastN_MetadataAndNormalAPI exte public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $visitorId = self::$fixture->visitorId; + $apiToCall = array( 'API.getProcessedReport', 'Actions.getPageUrls', @@ -89,127 +84,23 @@ class Test_Piwik_Integration_PeriodIsRange_DateIsLastN_MetadataAndNormalAPI exte $result = array(); foreach ($segments as $segment) { foreach ($dates as $date) { - $result[] = array($apiToCall, array('idSite' => self::$idSite, 'date' => $date, + $result[] = array($apiToCall, array('idSite' => $idSite, 'date' => $date, 'periods' => array('range'), 'segment' => $segment, // testing getLastVisitsForVisitor requires a visitor ID - 'visitorId' => self::$visitorId)); + 'visitorId' => $visitorId)); } } return $result; } - public static function tearDownAfterClass() - { - if(self::$shouldSkipTestThisTime) { - return; - } - parent::tearDownAfterClass(); - } public function getOutputPrefix() { return 'periodIsRange_dateIsLastN_MetadataAndNormalAPI'; } - - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js', 'manually', '', ''); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'second goal', 'manually', '', ''); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idGoal = self::$idGoal1; - $idGoal2 = self::$idGoal2; - - $visitorA = self::getTracker($idSite, $dateTime, $defaultInit = true); - // Used to test actual referer + keyword position in Live! - $visitorA->setUrlReferrer(urldecode('http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB4QFjAA&url=http%3A%2F%2Fpiwik.org%2F&rct=j&q=this%20keyword%20should%20be%20ranked&ei=V8WfTePkKKLfiALrpZWGAw&usg=AFQjCNF_MGJRqKPvaKuUokHtZ3VvNG9ALw&sig2=BvKAdCtNixsmfNWXjsNyMw')); - - // no campaign, but a search engine to attribute the goal conversion to - $attribution = array( - '', - '', - 1302306504, - 'http://www.google.com/search?q=piwik&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a' - ); - $visitorA->setAttributionInfo(json_encode($attribution)); - - $visitorA->setResolution(self::$width, self::$height); - - // At first, visitor custom var is set to LoggedOut - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitorA->setUrl('http://example.org/homepage'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - self::checkResponse($visitorA->doTrackPageView('Homepage')); - self::checkResponse($visitorA->doTrackGoal($idGoal2)); - - // After login, set to LoggedIn, should overwrite previous value - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $visitorA->setUrl('http://example.org/user/profile'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedIn'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = 'Loggedin', $scope = 'page'); - if (self::$useEscapedQuotes) { - $lookingAtProfile = 'looking at "profile page"'; - } else { - $lookingAtProfile = 'looking at profile page'; - } - $visitorA->setCustomVariable($id = 5, $name = 'Status user', $value = $lookingAtProfile, $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Profile page')); - - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE', $value = ''); - $visitorA->setCustomVariable($id = 1, $name = 'Language', $value = 'FR', $scope = 'page'); - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE PAGE SCOPE', $value = '', $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = "looking at \"profile page\"", $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'Value will be VERY long and truncated', $value = 'abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----'); - self::checkResponse($visitorA->doTrackPageView('Profile page for user *_)%')); - self::checkResponse($visitorA->doTrackGoal($idGoal)); - - if (self::$doExtraQuoteTests) { - $visitorA->setCustomVariable($id = 2, $name = 'var1', $value = 'looking at "profile page"', - $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'var2', $value = '\'looking at "\profile page"\'', - $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'var3', $value = '\\looking at "\profile page"\\', - $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Concurrent page views')); - } - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->setVisitorId(self::$visitorId); - $visitorB->setUrlReferrer(''); - - $attribution = array( - ' CAMPAIGN NAME -%20YEAH! ', - ' CAMPAIGN%20KEYWORD - RIGHT... ', - 1302306504, - 'http://www.example.org/test/really?q=yes' - ); - $visitorB->setAttributionInfo(json_encode($attribution)); - $visitorB->setResolution(self::$width, self::$height); - $visitorB->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6'); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - $visitorB->setCustomVariable($id = 2, $name = 'Othercustom value which should be truncated abcdefghijklmnopqrstuvwxyz', $value = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'); - $visitorB->setCustomVariable($id = -2, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = array('not tracked'), $value = 'not tracked'); - $visitorB->setUrl('http://example.org/homepage'); - self::checkResponse($visitorB->doTrackGoal($idGoal, 1000)); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.1)->getDatetime()); - self::checkResponse($visitorB->doTrackPageView('Homepage')); - - // DIFFERENT test - - // testing that starting the visit with an outlink works (doesn't trigger errors) - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - self::checkResponse($visitorB->doTrackAction('http://test.com', 'link')); - } } +Test_Piwik_Integration_PeriodIsRange_DateIsLastN_MetadataAndNormalAPI::$fixture = + new Test_Piwik_Fixture_TwoVisitsWithCustomVariables(); +Test_Piwik_Integration_PeriodIsRange_DateIsLastN_MetadataAndNormalAPI::$fixture->doExtraQuoteTests = false; + diff --git a/tests/PHPUnit/Integration/RowEvolutionTest.php b/tests/PHPUnit/Integration/RowEvolutionTest.php index cebb79ac1e..56bebd6cb8 100755 --- a/tests/PHPUnit/Integration/RowEvolutionTest.php +++ b/tests/PHPUnit/Integration/RowEvolutionTest.php @@ -11,25 +11,7 @@ */ class Test_Piwik_Integration_RowEvolution extends IntegrationTestCase { - protected static $today = '2010-03-06 11:22:33'; - protected static $idSite = 1; - protected static $keywords = array( - 'free > proprietary', // testing a keyword containing > - 'peace "," not war', // testing a keyword containing , - 'justice )(&^#%$ NOT corruption!', - ); - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -43,12 +25,16 @@ class Test_Piwik_Integration_RowEvolution extends IntegrationTestCase public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $today = self::$fixture->today; + $keywords = self::$fixture->keywords; + $return = array(); $config = array( 'testSuffix' => '_referrer1', - 'idSite' => self::$idSite, - 'date' => self::$today, + 'idSite' => $idSite, + 'date' => $today, 'otherRequestParameters' => array( 'date' => '2010-02-06,2010-03-06', 'period' => 'day', @@ -76,18 +62,18 @@ class Test_Piwik_Integration_RowEvolution extends IntegrationTestCase // Keywords, label containing > and , $config['otherRequestParameters']['apiAction'] = 'getKeywords'; $config['testSuffix'] = '_LabelReservedCharacters'; - $keywords = urlencode(self::$keywords[0]) . ',' . urlencode(self::$keywords[1]); - $config['otherRequestParameters']['label'] = urlencode($keywords); + $keywordsStr = urlencode($keywords[0]) . ',' . urlencode($keywords[1]); + $config['otherRequestParameters']['label'] = urlencode($keywordsStr); $return[] = array('API.getRowEvolution', $config); // Keywords, hierarchical $config['otherRequestParameters']['apiAction'] = 'getSearchEngines'; $config['testSuffix'] = '_LabelReservedCharactersHierarchical'; - $keywords = "Google>" . urlencode(strtolower(self::$keywords[0])) - . ',Google>' . urlencode(strtolower(self::$keywords[1])) - . ',Google>' . urlencode(strtolower(self::$keywords[2])); + $keywordsStr = "Google>" . urlencode(strtolower($keywords[0])) + . ',Google>' . urlencode(strtolower($keywords[1])) + . ',Google>' . urlencode(strtolower($keywords[2])); // Test multiple labels search engines, Google should also have a 'logo' entry - $config['otherRequestParameters']['label'] = urlencode($keywords . ",Google"); + $config['otherRequestParameters']['label'] = urlencode($keywordsStr . ",Google"); $return[] = array('API.getRowEvolution', $config); // Actions > Pages titles, standard label @@ -144,48 +130,8 @@ class Test_Piwik_Integration_RowEvolution extends IntegrationTestCase { return 'RowEvolution'; } - - protected static function setUpWebsitesAndGoals() - { - self::createWebsite('2010-02-01 11:22:33'); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered php', 'manually', '', ''); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'another triggered php', 'manually', '', '', false, false, true); - } - - protected static function trackVisits() - { - $dateTime = self::$today; - $idSite = self::$idSite; - - $t = self::getTracker($idSite, $dateTime, $defaultInit = true); - $t->setTokenAuth(self::getTokenAuth()); - $t->enableBulkTracking(); - for ($daysIntoPast = 30; $daysIntoPast >= 0; $daysIntoPast--) - { - // Visit 1: referrer website + test page views - $visitDateTime = Piwik_Date::factory($dateTime)->subDay($daysIntoPast)->getDatetime(); - - $t->setNewVisitorId(); - - $t->setUrlReferrer('http://www.referrer' . ($daysIntoPast % 5) . '.com/theReferrerPage' . ($daysIntoPast % 2) . '.html'); - $t->setUrl('http://example.org/my/dir/page' . ($daysIntoPast % 4) . '?foo=bar&baz=bar'); - $t->setForceVisitDateTime($visitDateTime); - self::assertTrue($t->doTrackPageView('incredible title ' . ($daysIntoPast % 3))); - - // Trigger goal n°1 once - self::assertTrue($t->doTrackGoal(1)); - - // Trigger goal n°2 twice - self::assertTrue($t->doTrackGoal(2)); - $t->setForceVisitDateTime(Piwik_Date::factory($visitDateTime)->addHour(0.1)->getDatetime()); - self::assertTrue($t->doTrackGoal(2)); - - // VISIT 2: search engine - $t->setForceVisitDateTime(Piwik_Date::factory($visitDateTime)->addHour(3)->getDatetime()); - $t->setUrlReferrer('http://google.com/search?q=' . urlencode(self::$keywords[$daysIntoPast % 3])); - self::assertTrue($t->doTrackPageView('not an incredible title ')); - } - self::checkResponse($t->doBulkTrack()); - } } +Test_Piwik_Integration_RowEvolution::$fixture + = new Test_Piwik_Fixture_ManyVisitsOverSeveralDaysWithSearchEngineReferrers(); + diff --git a/tests/PHPUnit/Integration/SiteSearchTest.php b/tests/PHPUnit/Integration/SiteSearchTest.php index 570a5b8663..881f17530c 100755 --- a/tests/PHPUnit/Integration/SiteSearchTest.php +++ b/tests/PHPUnit/Integration/SiteSearchTest.php @@ -11,22 +11,7 @@ */ class Test_Piwik_Integration_SiteSearch extends IntegrationTestCase { - protected static $idSite1 = 1; - protected static $idSite2 = 2; - protected static $idSite3 = 3; - protected static $dateTime = '2010-01-03 11:22:33'; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsites(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -55,6 +40,9 @@ class Test_Piwik_Integration_SiteSearch extends IntegrationTestCase public function getApiForTesting() { + $dateTime = self::$fixture->dateTime; + $idSite1 = self::$fixture->idSite1; + $apiToCall = $this->getApiToCall(); $periods = array('day', 'month'); @@ -62,15 +50,15 @@ class Test_Piwik_Integration_SiteSearch extends IntegrationTestCase $result = array( // Request data for the last 6 periods and idSite=all array($apiToCall, array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => $dateTime, 'periods' => $periods, 'setDateLastN' => true, 'testSuffix' => '_AllSites')), // We also test a single period/single site to check that this use case (Reports per idSite in the response) works array($apiToCall, array( - 'idSite' => self::$idSite1, - 'date' => self::$dateTime, + 'idSite' => $idSite1, + 'date' => $dateTime, 'periods' => $periods, 'setDateLastN' => false, 'testSuffix' => '_NotLastNPeriods')), @@ -81,8 +69,8 @@ class Test_Piwik_Integration_SiteSearch extends IntegrationTestCase list($apiModule, $apiAction) = explode(".", $api); $result[] = array( - 'API.getProcessedReport', array('idSite' => self::$idSite1, - 'date' => self::$dateTime, + 'API.getProcessedReport', array('idSite' => $idSite1, + 'date' => $dateTime, 'periods' => $periods, 'setDateLastN' => true, 'apiModule' => $apiModule, @@ -97,165 +85,7 @@ class Test_Piwik_Integration_SiteSearch extends IntegrationTestCase { return 'SiteSearch'; } +} - /** - * One site with custom search parameters, - * One site using default search parameters, - * One site with disabled site search - */ - protected static function setUpWebsites() - { - Piwik_SitesManager_API::getInstance()->setGlobalSearchParameters($searchKeywordParameters='gkwd', $searchCategoryParameters='gcat'); - self::createWebsite(Piwik_Date::factory(self::$dateTime)->subHour(200)->getDatetime(), 0, "Site 1 - Site search", $siteurl=false, $search=1, $searchKwd='q,mykwd,p', $searchCat='cats' ); - self::createWebsite(Piwik_Date::factory(self::$dateTime)->subHour(400)->getDatetime(), 0, "Site 2 - Site search use default", $siteurl = false, $search=1, $searchKwd='', $searchCat='' ); - self::createWebsite(Piwik_Date::factory(self::$dateTime)->subHour(600)->getDatetime(), 0, "Site 3 - No site search", $siteurl = false, $search=0); - } - - protected static function trackVisits() - { - self::recordVisitorsSite1(); - self::recordVisitorSite2(); - self::recordVisitorSite3(); -// exit; - } - - protected static function recordVisitorsSite1() - { - // - - // Visitor site1 - $visitor = self::getTracker(self::$idSite1, self::$dateTime, $defaultInit = true); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.2)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?q=Search 1 '); - self::checkResponse($visitor->doTrackPageView('Site Search results')); - - // Normal page view - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.22)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm'); - self::checkResponse($visitor->doTrackPageView('Im just a page')); - - // IS_FOLLOWING_SEARCH: Not this time - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.23)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?random=PAGEVIEW, NOT SEARCH&mykwd=&IS_FOLLOWING_SEARCH ONCE'); - self::checkResponse($visitor->doTrackPageView('This is a pageview, not a Search - IS_FOLLOWING_SEARCH ONCE')); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.25)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?standard=query&but=also#hash&q='.urlencode('Search 1')); - self::checkResponse($visitor->doTrackPageView('Site Search results - URL Fragment')); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.26)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm#q=Search 1&search_count=10'); - self::checkResponse($visitor->doTrackPageView('Site Search results - URL Fragment')); - - // &search_count=0 so it's a "No Result" keyword, but it will not appear in the report, because it also has other seraches with results - // and the archiving does a MAX() - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.27)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?hello=world#q=Search 1&search_count=0'); - self::checkResponse($visitor->doTrackPageView('Site Search results - URL Fragment')); - - // Testing with non urlencoded values - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.3)->getDatetime()); - // ALso testing that array[] notation is detected - $visitor->setUrl('http://example.org/index.htm?random=param&mykwd[]=Search 2&test&cats= Search Category &search_count=INCORRECT!'); - self::checkResponse($visitor->doTrackPageView('Site Search results')); - - // Testing with urlencoded values - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.32)->getDatetime()); - // Also testing with random case 'myKwd' - $visitor->setUrl('http://example.org/index.htm?random=param&myKwd=Search 1&test&cats='.urlencode(' Search Category '). ' &search_count=0'); - self::checkResponse($visitor->doTrackPageView('Site Search results')); - - // IS_FOLLOWING_SEARCH: Yes - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.35)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?random=PAGEVIEW, NOT SEARCH&mykwd=&IS_FOLLOWING_SEARCH ONCE'); - self::checkResponse($visitor->doTrackPageView('This is a pageview, not a Search - IS_FOLLOWING_SEARCH ONCE')); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.4)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?gkwd=SHOULD be a PageView, NOT a search'); - self::checkResponse($visitor->doTrackPageView('Pageview, not search')); - - $visitor->setUrl('http://example.org/hello?THIS IS A SITE SEARCH TRACKING API, NOT PAGEVIEW!'); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(24.41)->getDatetime()); - self::checkResponse($visitor->doTrackSiteSearch("Keyword - Tracking API")); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(24.42)->getDatetime()); - self::checkResponse($visitor->doTrackSiteSearch("Keyword - Tracking API", "Category", $count = 5)); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(24.43)->getDatetime()); - self::checkResponse($visitor->doTrackSiteSearch("No Result Keyword!", "Bad No Result Category :(", $count = 0)); - - // Keyword in iso-8859-15 charset with funny character - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(24.5)->getDatetime()); - $visitor->setPageCharset('iso-8859-15'); - $visitor->setUrl('http://example.org/index.htm?q=Final%20t%FCte%20Keyword%20Searched%20for%20now&search_count=10'); - self::checkResponse($visitor->doTrackPageView(false)); - - // - - // Visitor BIS - $visitorB = self::getTracker(self::$idSite1, self::$dateTime, $defaultInit = true); - $visitorB->setIp('156.66.6.66'); - $visitorB->setResolution(1600, 1000); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(2.26)->getDatetime()); - $visitorB->setUrl('http://example.org/index.htm#q=' . urlencode('No Result Keyword!') . '&search_count=0'); - self::checkResponse($visitorB->doTrackPageView('Site Search results - URL Fragment')); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(2.27)->getDatetime()); - $visitorB->setUrl('http://example.org/index.htm?hello=world#q=Search 1&search_count=10'); - self::checkResponse($visitorB->doTrackPageView('Site Search results - URL Fragment')); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(2.3)->getDatetime()); - $visitorB->setUrl('http://example.org/index.htm?random=param&mykwd=Search 2&test&cats= Search Category &search_count=10'); - self::checkResponse($visitorB->doTrackPageView('Site Search results')); - } - - protected static function recordVisitorSite3() - { // - - // Third new visitor on Idsite 3 - $visitor = self::getTracker(self::$idSite3, self::$dateTime, $defaultInit = true); - $visitor->setResolution(1801, 1301); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.2)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?q=Search 1&IsPageView=1'); - $visitor->setCustomVariable(1, 'test cvar name', 'test cvar value'); - self::checkResponse($visitor->doTrackPageView('IsPageView')); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.35)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?gkwd=test not a keyword&gcat=Cat not but not keyword, so this is not search'); - self::checkResponse($visitor->doTrackPageView('This is a pageview, not a Search')); - - // Testing UTF8 Title & URL - $crazyTitle = '%2C%20%C3%8Dslenska%2C%20Italiano%2C%20%E6%97%A5%E6%9C%AC%E8%AA%9E%2C%20%E1%83%A5%E1%83%90%E1%83%A0%E1%83%97%E1%83%A3%E1%83%9A%E1%83%98%2C%20%ED%95%9C%EA%B5%AD%EC%96%B4%2C%20Lietuvi%C5%B3%2C%20Latvie%C5%A1u%2C%20Norsk%20(bokm%C3%A5l)%2C%20Nederlands%2C%20Norsk%20(nynorsk)%2C%20Polski%2C%20Portugu%C3%AAs%20brasileiro%2C%20Portugu%C3%AAs%2C%20Rom%C3%A2n%C4%83%2C%20%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9%2C%20Slovensky%2C%20Sloven%C5%A1%C4%8Dina%2C%20Shqip%2C%20Srpski%2C%20Svenska%2C%20%E0%B0%A4%E0%B1%86%E0%B0%B2%E0%B1%81%E0%B0%97%E0%B1%81%2C%20%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B9%84%E0%B8%97%E0%B8%A2%2C%20T%C3%BCrk%C3%A7e%2C%20%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B0%2C%20%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87%2C%20%E7%B9%81%E9%AB%94%E4%B8%AD%E6%96%87.'; - $visitor->setUrl('http://example.org/index.htm?' . $crazyTitle); - self::checkResponse($visitor->doTrackPageView('Pageview: ' . $crazyTitle)); - } - - protected static function recordVisitorSite2() - { - $visitor = self::getTracker(self::$idSite2, self::$dateTime, $defaultInit = true); - $visitor->setResolution(801, 301); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.2)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?q=Search 1&IsPageView=1'); - self::checkResponse($visitor->doTrackPageView('IsPageView')); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.35)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?random=PAGEVIEW, NOT SEARCH&gcat=Cat not but not keyword, so this is not search'); - self::checkResponse($visitor->doTrackPageView('This is a pageview, not a Search')); - - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.4)->getDatetime()); - $visitor->setUrl('http://example.org/index.htm?gkwd=SHOULD be a Search with no result!&search_count=0'); - self::checkResponse($visitor->doTrackPageView('This is a Search')); - - // Testing UTF8 keywords - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.45)->getDatetime()); - $crazySearchTerm = 'You%20can%20use%20Piwik%20in%3A%20%E1%8A%A0%E1%88%9B%E1%88%AD%E1%8A%9B%2C%20%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9%2C%20%D0%91%D0%B5%D0%BB%D0%B0%D1%80%D1%83%D1%81%D0%BA%D0%B0%D1%8F%2C%20%D0%91%D1%8A%D0%BB%D0%B3%D0%B0%D1%80%D1%81%D0%BA%D0%B8%2C%20Catal%C3%A0%2C%20%C4%8Cesky%2C%20Dansk%2C%20Deutsch%2C%20%CE%95%CE%BB%CE%BB%CE%B7%CE%BD%CE%B9%CE%BA%CE%AC%2C%20English%2C%20Espa%C3%B1ol%2C%20Eesti%20keel%2C%20Euskara%2C%20%D9%81%D8%A7%D8%B1%D8%B3%DB%8C%2C%20Suomi%2C%20Fran%C3%A7ais%2C%20Galego%2C%20%D7%A2%D7%91%D7%A8%D7%99%D7%AA%2C%20Magyar%2C%20Bahasa%20Indonesia%2C%20%C3%8Dslenska%2C%20Italiano%2C%20%E6%97%A5%E6%9C%AC%E8%AA%9E%2C%20%E1%83%A5%E1%83%90%E1%83%A0%E1%83%97%E1%83%A3%E1%83%9A%E1%83%98%2C%20%ED%95%9C%EA%B5%AD%EC%96%B4%2C%20Lietuvi%C5%B3%2C%20Latvie%C5%A1u%2C%20Norsk%20(bokm%C3%A5l)%2C%20Nederlands%2C%20Norsk%20(nynorsk)%2C%20Polski%2C%20Portugu%C3%AAs%20brasileiro%2C%20Portugu%C3%AAs%2C%20Rom%C3%A2n%C4%83%2C%20%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9%2C%20Slovensky%2C%20Sloven%C5%A1%C4%8Dina%2C%20Shqip%2C%20Srpski%2C%20Svenska%2C%20%E0%B0%A4%E0%B1%86%E0%B0%B2%E0%B1%81%E0%B0%97%E0%B1%81%2C%20%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B9%84%E0%B8%97%E0%B8%A2%2C%20T%C3%BCrk%C3%A7e%2C%20%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%81%D1%8C%D0%BA%D0%B0%2C%20%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87%2C%20%E7%B9%81%E9%AB%94%E4%B8%AD%E6%96%87.'; - $visitor->setUrl('http://example.org/index.htm?gkwd=' . $crazySearchTerm . '&gcat=' . $crazySearchTerm . '&search_count=1'); - self::checkResponse($visitor->doTrackPageView('Site Search with 1 result')); +Test_Piwik_Integration_SiteSearch::$fixture = new Test_Piwik_Fixture_ThreeSitesWithManyVisitsWithSiteSearch(); - $visitor->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour(0.5)->getDatetime()); - self::checkResponse($visitor->doTrackSiteSearch("No Result Keyword!", "Bad No Result Category bis :(", $count = 0)); - return array($defaultInit, $visitor); - } -} diff --git a/tests/PHPUnit/Integration/TrackCustomVariablesAndCampaigns_ForceUsingVisitIdNotHeuristicsTest.php b/tests/PHPUnit/Integration/TrackCustomVariablesAndCampaigns_ForceUsingVisitIdNotHeuristicsTest.php index b6f9d955ac..73b6f00efc 100755 --- a/tests/PHPUnit/Integration/TrackCustomVariablesAndCampaigns_ForceUsingVisitIdNotHeuristicsTest.php +++ b/tests/PHPUnit/Integration/TrackCustomVariablesAndCampaigns_ForceUsingVisitIdNotHeuristicsTest.php @@ -12,21 +12,7 @@ */ class Test_Piwik_Integration_TrackCustomVariablesAndCampaigns_ForceUsingVisitIdNotHeuristics extends IntegrationTestCase { - protected static $dateTime = '2009-01-04 00:11:42'; - protected static $idSite = 1; - protected static $idGoal = 1; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -44,7 +30,7 @@ class Test_Piwik_Integration_TrackCustomVariablesAndCampaigns_ForceUsingVisitIdN return array( // TOTAL should be: 1 visit, 1 converted goal, 1 page view - array($apiToCall, array('idSite' => self::$idSite, 'date' => self::$dateTime)) + array($apiToCall, array('idSite' => self::$fixture->idSite, 'date' => self::$fixture->dateTime)) ); } @@ -52,94 +38,8 @@ class Test_Piwik_Integration_TrackCustomVariablesAndCampaigns_ForceUsingVisitIdN { return 'PiwikTracker_trackForceUsingVisitId_insteadOfHeuristics_alsoTestsCampaignTracking'; } +} - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js', 'manually', '', ''); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idGoal = self::$idGoal; - - $t = self::getTracker($idSite, $dateTime, $defaultInit = true); - - // Record 1st page view - $t->setUrl('http://example.org/index.htm?utm_campaign=GA Campaign&piwik_kwd=Piwik kwd&utm_term=GA keyword SHOULD NOT DISPLAY#pk_campaign=NOT TRACKED!!&pk_kwd=NOT TRACKED!!'); - self::checkResponse($t->doTrackPageView('incredible title!')); - - $visitorId = $t->getVisitorId(); - self::assertTrue(strlen($visitorId) == 16); - - // test setting/getting the first party cookie via the PHP Tracking Client - $_COOKIE['_pk_id_1_1fff'] = 'ca0afe7b6b692ff5.1302307497.1.1302307497.1302307497'; - $_COOKIE['_pk_ref_1_1fff'] = '["YEAH","RIGHT!",1302307497,"http://referrer.example.org/page/sub?query=test&test2=test3"]'; - $_COOKIE['_pk_cvar_1_1fff'] = '{"1":["VAR 1 set, var 2 not set","yes"],"3":["var 3 set","yes!!!!"]}'; - self::assertEquals('ca0afe7b6b692ff5', $t->getVisitorId()); - self::assertEquals($t->getAttributionInfo(), $_COOKIE['_pk_ref_1_1fff']); - self::assertEquals(array("VAR 1 set, var 2 not set", "yes"), $t->getCustomVariable(1)); - self::assertFalse($t->getCustomVariable(2)); - self::assertEquals(array("var 3 set", "yes!!!!"), $t->getCustomVariable(3)); - self::assertFalse($t->getCustomVariable(4)); - self::assertFalse($t->getCustomVariable(5)); - self::assertFalse($t->getCustomVariable(6)); - self::assertFalse($t->getCustomVariable(-1)); - unset($_COOKIE['_pk_id_1_1fff']); - unset($_COOKIE['_pk_ref_1_1fff']); - unset($_COOKIE['_pk_cvar_1_1fff']); - - // Create a new Tracker object, with different attributes - $t2 = self::getTracker($idSite, $dateTime, $defaultInit = false); - - // Make sure the ID is different at first - $visitorId2 = $t2->getVisitorId(); - self::assertTrue($visitorId != $visitorId2); - - // Then force the visitor ID - $t2->setVisitorId($visitorId); - - // And Record a Goal: The previous visit should be updated rather than a new visit Created - $t2->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); - self::checkResponse($t2->doTrackGoal($idGoal, $revenue = 42.256)); - - // Yet another visitor, this time with a manual goal conversion, which should be credited to the campaign - $t3 = self::getTracker($idSite, $dateTime); - $t3->setUrlReferrer('http://example.org/referrer'); - $t3->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.3)->getDatetime()); - // fake a website ref cookie, the campaign should be credited for conversion, not referrer.example.com nor example.org - $t3->DEBUG_APPEND_URL = '&_ref=http%3A%2F%2Freferrer.example.com%2Fpage%2Fsub%3Fquery%3Dtest%26test2%3Dtest3'; - $t3->setUrl('http://example.org/index.htm#pk_campaign=CREDITED TO GOAL PLEASE'); - self::checkResponse($t3->doTrackGoal($idGoal, 42)); - - // visitor #4, test for blank referrer campaign keyword - $t4 = self::getTracker($idSite, $dateTime); - $t4->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(3)->getDatetime()); - $t4->setUrlReferrer('http://bing.com/search?q=whatever'); - $t4->setUrl('http://example.org/index.html?utm_campaign=GA+Campaign'); - self::checkResponse($t4->doTrackPageView('first page')); - - // No campaign keyword specified, will use the referrer hostname - $t4->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(4)->getDatetime()); - $t4->setUrlReferrer('http://thing1.com/a/b/c.html?a=b&d=c'); - $t4->setUrl('http://example.org/index.html?utm_campaign=GA+Campaign'); - self::checkResponse($t4->doTrackPageView('second page')); - - // Test with Google adsense type URL: - $adsenseRefererUrl = 'http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-12345&output=html&h=280&slotname=123&w=336&lmt=1359388321&202&url=http%3A%2F%2Fwww.adsense-publisher-website.org%2F&dt=123&bpp=13&shv=r22&jsv=1565606614&correlator=ss&ga_vid=aaa&ga_sid=1359435122&ga_hid=1801871121&ga_fc=0&u_tz=780&u_his=4&u_java=1&u_h=900&u_w=1600&u_ah=876&u_aw=1551&u_cd=24&u_nplug=4&u_nmime=5&dff=georgia&dfs=16&adx=33&ady=201&biw=1551&bih=792&oid=3&fu=0&ifi=1&dtd=608&p=http%3A//www.adsense-publisher-website.com'; - $t4->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(5)->getDatetime()); - $t4->setUrlReferrer($adsenseRefererUrl); - $t4->setUrl('http://example.org/index.html?utm_campaign=Adsense campaign'); - self::checkResponse($t4->doTrackPageView('second page')); - - // Test with google Adwords URL - $adwordsUrl = 'http://www.google.co.nz/aclk?sa=L&ai=uYmFyiZgAf0oO0J&num=3&sig=EpOCR4xQ&ved=ENEM&adurl=http://pixel.everesttech.net/3163/cq%3Fev_sid%3D3%26ev_cmpid%3D33%26ev_ln%3Dused%2520wii%2520consoles%26ev_crx%528386%26ev_mt%3Db%26ev_n%3Dg%26ev_ltx%3D%26ev_pl%3D%26ev_pos%3D1s2%26url%3Dhttp%253A//au.shopping.com/used%2520wii%2520consoles/products%253Flinkin_id%253D8077872&rct=j&q=nintendo+consoles+second+hand'; - $t4->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(6)->getDatetime()); - $t4->setUrlReferrer($adwordsUrl); - $t4->setUrl('http://example.org/index.html?utm_campaign=Adwords campaign'); - self::checkResponse($t4->doTrackPageView('second page')); +Test_Piwik_Integration_TrackCustomVariablesAndCampaigns_ForceUsingVisitIdNotHeuristics::$fixture = + new Test_Piwik_Fixture_SomeVisitsCustomVariablesCampaignsNotHeuristics(); - } -} diff --git a/tests/PHPUnit/Integration/TrackGoals_AllowMultipleConversionsPerVisitTest.php b/tests/PHPUnit/Integration/TrackGoals_AllowMultipleConversionsPerVisitTest.php index 0e7d0ec4e6..0127a38161 100755 --- a/tests/PHPUnit/Integration/TrackGoals_AllowMultipleConversionsPerVisitTest.php +++ b/tests/PHPUnit/Integration/TrackGoals_AllowMultipleConversionsPerVisitTest.php @@ -12,22 +12,7 @@ */ class Test_Piwik_Integration_TrackGoals_AllowMultipleConversionsPerVisit extends IntegrationTestCase { - protected static $dateTime = '2009-01-04 00:11:42'; - protected static $idSite = 1; - protected static $idGoal_OneConversionPerVisit = 1; - protected static $idGoal_MultipleConversionPerVisit = 2; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; /** * @dataProvider getApiForTesting @@ -46,13 +31,13 @@ class Test_Piwik_Integration_TrackGoals_AllowMultipleConversionsPerVisit extends */ public function testCheck() { - $idSite = self::$idSite; + $idSite = self::$fixture->idSite; // test delete is working as expected $goals = Piwik_Goals_API::getInstance()->getGoals($idSite); $this->assertTrue(2 == count($goals)); - Piwik_Goals_API::getInstance()->deleteGoal($idSite, self::$idGoal_OneConversionPerVisit); - Piwik_Goals_API::getInstance()->deleteGoal($idSite, self::$idGoal_MultipleConversionPerVisit); + Piwik_Goals_API::getInstance()->deleteGoal($idSite, self::$fixture->idGoal_OneConversionPerVisit); + Piwik_Goals_API::getInstance()->deleteGoal($idSite, self::$fixture->idGoal_MultipleConversionPerVisit); $goals = Piwik_Goals_API::getInstance()->getGoals($idSite); $this->assertTrue(empty($goals)); } @@ -62,7 +47,7 @@ class Test_Piwik_Integration_TrackGoals_AllowMultipleConversionsPerVisit extends $apiToCall = array('VisitTime.getVisitInformationPerServerTime', 'VisitsSummary.get'); return array( - array($apiToCall, array('idSite' => self::$idSite, 'date' => self::$dateTime)) + array($apiToCall, array('idSite' => self::$fixture->idSite, 'date' => self::$fixture->dateTime)) ); } @@ -70,49 +55,7 @@ class Test_Piwik_Integration_TrackGoals_AllowMultipleConversionsPerVisit extends { return 'trackGoals_allowMultipleConversionsPerVisit'; } - - public static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - - // First, a goal that is only recorded once per visit - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js ONCE', 'title', 'Thank you', 'contains', $caseSensitive = false, $revenue = 10, $allowMultipleConversions = false); - - // Second, a goal allowing multiple conversions - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js MULTIPLE ALLOWED', 'manually', '', '', $caseSensitive = false, $revenue = 10, $allowMultipleConversions = true); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idGoal_OneConversionPerVisit = self::$idGoal_OneConversionPerVisit; - $idGoal_MultipleConversionPerVisit = self::$idGoal_MultipleConversionPerVisit; - - $t = self::getTracker($idSite, $dateTime, $defaultInit = true); - - // Record 1st goal, should only have 1 conversion - $t->setUrl('http://example.org/index.htm'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); - self::checkResponse($t->doTrackPageView('Thank you mate')); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); - self::checkResponse($t->doTrackGoal($idGoal_OneConversionPerVisit, $revenue = 10000000)); - - // Record 2nd goal, should record both conversions - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.5)->getDatetime()); - self::checkResponse($t->doTrackGoal($idGoal_MultipleConversionPerVisit, $revenue = 300)); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.6)->getDatetime()); - self::checkResponse($t->doTrackGoal($idGoal_MultipleConversionPerVisit, $revenue = 366)); - - // Update & set to not allow multiple - $goals = Piwik_Goals_API::getInstance()->getGoals($idSite); - $goal = $goals[$idGoal_OneConversionPerVisit]; - self::assertTrue($goal['allow_multiple'] == 0); - Piwik_Goals_API::getInstance()->updateGoal($idSite, $idGoal_OneConversionPerVisit, $goal['name'], @$goal['match_attribute'], @$goal['pattern'], @$goal['pattern_type'], @$goal['case_sensitive'], $goal['revenue'], $goal['allow_multiple'] = 1); - self::assertTrue($goal['allow_multiple'] == 1); - - // 1st goal should Now be tracked - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.61)->getDatetime()); - self::checkResponse($t->doTrackGoal($idGoal_OneConversionPerVisit, $revenue = 656)); - } } + +Test_Piwik_Integration_TrackGoals_AllowMultipleConversionsPerVisit::$fixture + = new Piwik_Test_Fixture_SomeVisitsAllConversions(); diff --git a/tests/PHPUnit/Integration/TrackingAPI_SetVisitorIdTest.php b/tests/PHPUnit/Integration/TrackingAPI_SetVisitorIdTest.php index e43c9aabe2..0bce1fbad2 100644 --- a/tests/PHPUnit/Integration/TrackingAPI_SetVisitorIdTest.php +++ b/tests/PHPUnit/Integration/TrackingAPI_SetVisitorIdTest.php @@ -12,20 +12,7 @@ */ class Test_Piwik_Integration_TrackingAPI_SetVisitorId extends IntegrationTestCase { - protected static $idSite = 1; - protected static $dateTime = '2010-03-06 11:22:33'; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition public function setUp() { @@ -51,68 +38,14 @@ class Test_Piwik_Integration_TrackingAPI_SetVisitorId extends IntegrationTestCas { return array( // test hideColumns && showColumns parameters - array('VisitsSummary.get', array('idSite' => self::$idSite, 'date' => self::$dateTime, + array('VisitsSummary.get', array('idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime, 'periods' => 'day', 'testSuffix' => '', )) ); } +} - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $t = self::getTracker($idSite, $dateTime, $defaultInit = true); - - // First, some basic tests - self::settingInvalidVisitorIdShouldThrow($t); - - // We create VISITOR A - $t->setUrl('http://example.org/index.htm'); - $t->setVisitorId(Piwik_Tracker_Visit::generateUniqueVisitorId()); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // VISITOR B: few minutes later, we trigger the same tracker but with a custom visitor ID, - // => this will create a new visit B - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.05)->getDatetime()); - $t->setUrl('http://example.org/index2.htm'); - $t->setVisitorId(Piwik_Tracker_Visit::generateUniqueVisitorId()); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // This new visit B will have 2 page views - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $t->setUrl('http://example.org/index3.htm'); - self::checkResponse($t->doTrackPageView('incredible title!')); - - // total = 2 visitors, 3 page views +Test_Piwik_Integration_TrackingAPI_SetVisitorId::$fixture = new Test_Piwik_Fixture_FewVisitsWithSetVisitorId(); - } - - static protected function settingInvalidVisitorIdShouldThrow(PiwikTracker $t) - { - try { - $t->setVisitorId('test'); - $this->fail('should throw'); - } catch(Exception $e) { - //OK - } - try { - $t->setVisitorId('61e8'); - $this->fail('should throw'); - } catch(Exception $e) { - //OK - } - try { - $t->setVisitorId('61e8cc2d51fea26dabcabcabc'); - $this->fail('should throw'); - } catch(Exception $e) { - //OK - } - } -} diff --git a/tests/PHPUnit/Integration/TransitionsTest.php b/tests/PHPUnit/Integration/TransitionsTest.php index 20d494ebf1..1d9f8375e2 100644 --- a/tests/PHPUnit/Integration/TransitionsTest.php +++ b/tests/PHPUnit/Integration/TransitionsTest.php @@ -5,22 +5,7 @@ */ class Test_Piwik_Integration_Transitions extends IntegrationTestCase { - protected static $dateTime = '2010-03-06 11:22:33'; - protected static $idSite = 1; - - private static $prefixCounter = 0; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs during setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -36,8 +21,8 @@ class Test_Piwik_Integration_Transitions extends IntegrationTestCase { $return = array(); $return[] = array('Transitions.getTransitionsForPageUrl', array( - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => self::$fixture->idSite, + 'date' => self::$fixture->dateTime, 'otherRequestParameters' => array( 'pageUrl' => 'http://example.org/page/one.html', 'limitBeforeGrouping' => 2 @@ -50,66 +35,7 @@ class Test_Piwik_Integration_Transitions extends IntegrationTestCase { return 'Transitions'; } - - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - $visit1 = self::createVisit(1); - $visit1->setUrlReferrer('http://www.google.com.vn/url?sa=t&rct=j&q=%3C%3E%26%5C%22the%20pdo%20extension%20is%20required%20for%20this%20adapter%20but%20the%20extension%20is%20not%20loaded&source=web&cd=4&ved=0FjAD&url=http%3A%2F%2Fforum.piwik.org%2Fread.php%3F2%2C1011&ei=y-HHAQ&usg=AFQjCN2-nt5_GgDeg&cad=rja'); - self::trackPageView($visit1, 0, 'page/one.html'); - self::trackPageView($visit1, 0.1, 'sub/dir/page2.html'); - self::trackPageView($visit1, 0.2, 'page/one.html'); - self::trackPageView($visit1, 0.3, 'the/third_page.html?foo=bar'); - self::trackPageView($visit1, 0.4, 'page/one.html'); - self::trackPageView($visit1, 0.5, 'the/third_page.html?foo=bar'); - self::trackPageView($visit1, 0.6, 'page/one.html'); - self::trackPageView($visit1, 0.7, 'the/third_page.html?foo=baz#anchor1'); - self::trackPageView($visit1, 0.8, 'page/one.html'); - self::trackPageView($visit1, 0.9, 'page/one.html'); - self::trackPageView($visit1, 1.0, 'the/third_page.html?foo=baz#anchor2'); - self::trackPageView($visit1, 1.1, 'page/one.html'); - self::trackPageView($visit1, 1.2, 'page3.html'); - - $visit2 = self::createVisit(2); - $visit2->setUrlReferrer('http://www.external.com.vn/referrerPage-notCounted.html'); - self::trackPageView($visit2, 0, 'sub/dir/page2.html'); - self::trackPageView($visit2, 0.1, 'the/third_page.html?foo=bar'); - self::trackPageView($visit2, 0.2, 'page/one.html'); - self::trackPageView($visit2, 0.3, 'the/third_page.html?foo=baz#anchor1'); - - $visit3 = self::createVisit(3); - $visit3->setUrlReferrer('http://www.external.com.vn/referrerPage-counted.html'); - self::trackPageView($visit3, 0.1, 'page/one.html'); - self::trackPageView($visit3, 0.2, 'sub/dir/page2.html'); - self::trackPageView($visit3, 0.3, 'page/one.html'); - - $visit4 = self::createVisit(4); - self::trackPageView($visit4, 0, 'page/one.html?pk_campaign=TestCampaign&pk_kwd=TestKeyword'); - - $visit5 = self::createVisit(5); - self::trackPageView($visit5, 0, 'page/one.html'); - } - - private static function createVisit($id) { - $visit = self::getTracker(self::$idSite, self::$dateTime, $defaultInit = true); - $visit->setIp('156.5.3.'.$id); - return $visit; - } - - private static function trackPageView($visit, $timeOffset, $path) { - // rotate protocol and www to make sure it doesn't matter - $prefixes = array('http://', 'http://www.', 'https://', 'https://'); - $prefix = $prefixes[self::$prefixCounter]; - self::$prefixCounter = (self::$prefixCounter + 1) % 4; - - /** @var $visit PiwikTracker */ - $visit->setUrl($prefix.'example.org/'.$path); - $visit->setForceVisitDateTime(Piwik_Date::factory(self::$dateTime)->addHour($timeOffset)->getDatetime()); - self::checkResponse($visit->doTrackPageView('page title')); - } - } + +Test_Piwik_Integration_Transitions::$fixture = new Test_Piwik_Fixture_SomeVisitsManyPageviewsWithTransitions(); + diff --git a/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDaysTest.php b/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDaysTest.php index 8d32b5d1fc..a9c89a6a8e 100755 --- a/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDaysTest.php +++ b/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDaysTest.php @@ -17,25 +17,7 @@ */ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays extends IntegrationTestCase { - protected static $idSite1 = 1; - protected static $idSite2 = 2; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - protected static $dateTime = '2010-01-03 11:22:33'; - protected static $allowConversions = false; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::setUpScheduledReports(self::$idSite1); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @group Integration @@ -71,6 +53,9 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays extends Integ public function getApiForTesting() { + $idSite1 = self::$fixture->idSite1; + $dateTime = self::$fixture->dateTime; + $apiToCall = $this->getApiToCall(); $singlePeriodApi = array('VisitsSummary.get', 'Goals.get'); @@ -79,20 +64,20 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays extends Integ $result = array( // Request data for the last 6 periods and idSite=all array($apiToCall, array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => $dateTime, 'periods' => $periods, 'setDateLastN' => true)), // Request data for the last 6 periods and idSite=1 - array($apiToCall, array('idSite' => self::$idSite1, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => $idSite1, + 'date' => $dateTime, 'periods' => $periods, 'setDateLastN' => true, 'testSuffix' => '_idSiteOne_')), // We also test a single period to check that this use case (Reports per idSite in the response) works array($singlePeriodApi, array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => $dateTime, 'periods' => array('day', 'month'), 'setDateLastN' => false, 'testSuffix' => '_NotLastNPeriods')), @@ -104,8 +89,8 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays extends Integ list($apiModule, $apiAction) = explode(".", $api); $result[] = array( - 'API.getProcessedReport', array('idSite' => self::$idSite1, - 'date' => self::$dateTime, + 'API.getProcessedReport', array('idSite' => $idSite1, + 'date' => $dateTime, 'periods' => array('day'), 'setDateLastN' => true, 'apiModule' => $apiModule, @@ -114,116 +99,15 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays extends Integ ); } - return array_merge($result, self::getApiForTestingScheduledReports(self::$dateTime, 'month')); + return array_merge($result, self::getApiForTestingScheduledReports($dateTime, 'month')); } public function getOutputPrefix() { return 'TwoVisitors_twoWebsites_differentDays'; } +} - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - $ecommerce = self::$allowConversions ? 1 : 0; - - self::createWebsite(self::$dateTime, $ecommerce, "Site 1"); - self::createWebsite(self::$dateTime, 0, "Site 2"); - - if (self::$allowConversions) { - Piwik_Goals_API::getInstance()->addGoal(self::$idSite1, 'all', 'url', 'http', 'contains', false, 5); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite2, 'all', 'url', 'http', 'contains'); - } - - Piwik_SitesManager_API::getInstance()->updateSite( - self::$idSite1, "Site 1", $urls = null, $ecommerce = null, $siteSearch = null, - $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, - $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, - $startDate = null, $excludedUserAgents = null, $keepURLFragments = 2); // KEEP_URL_FRAGMENT_NO No for idSite 1 - Piwik_SitesManager_API::getInstance()->updateSite( - self::$idSite2, "Site 2", $urls = null, $ecommerce = null, $siteSearch = null, - $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, - $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, - $startDate = null, $excludedUserAgents = null, $keepURLFragments = 1); // KEEP_URL_FRAGMENT_YES Yes for idSite 2 - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite1; - $idSite2 = self::$idSite2; - - // - - // First visitor on Idsite 1: two page views - $datetimeSpanOverTwoDays = '2010-01-03 23:55:00'; - $visitorA = self::getTracker($idSite, $datetimeSpanOverTwoDays, $defaultInit = true); - $visitorA->setUrlReferrer('http://referer.com/page.htm?param=valuewith some spaces'); - $visitorA->setUrl('http://example.org/index.htm#ignoredFragment'); - $visitorA->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($datetimeSpanOverTwoDays)->getTimestamp(); - self::checkResponse($visitorA->doTrackPageView('first page view')); - - $visitorA->setForceVisitDateTime(Piwik_Date::factory($datetimeSpanOverTwoDays)->addHour(0.1)->getDatetime()); - // testing with empty URL and empty page title - $visitorA->setUrl(' '); - self::checkResponse($visitorA->doTrackPageView(' ')); - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->enableBulkTracking(); - $visitorB->setTokenAuth(self::getTokenAuth()); - $visitorB->setIp('100.52.156.83'); - $visitorB->setResolution(800, 300); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setUrlReferrer(''); - $visitorB->setUserAgent('Opera/9.63 (Windows NT 5.1; U; en) Presto/2.1.1'); - $visitorB->setUrl('http://example.org/products'); - $visitorB->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($dateTime)->addHour(1)->getTimestamp(); - self::assertTrue($visitorB->doTrackPageView('first page view')); - - // - - // Second visitor again on Idsite 1: 2 page views 2 days later, 2010-01-05 - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->getDatetime()); - // visitor_returning is set to 1 only when visit count more than 1 - // Temporary, until we implement 1st party cookies in PiwikTracker - $visitorB->DEBUG_APPEND_URL .= '&_idvc=2&_viewts=' . Piwik_Date::factory($dateTime)->getTimestamp(); - - $visitorB->setUrlReferrer('http://referer.com/Other_Page.htm'); - $visitorB->setUrl('http://example.org/index.htm'); - self::assertTrue($visitorB->doTrackPageView('second visitor/two days later/a new visit')); - // Second page view 6 minutes later - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.1)->getDatetime()); - $visitorB->setUrl('http://example.org/thankyou'); - self::assertTrue($visitorB->doTrackPageView('second visitor/two days later/second page view')); - - // testing a strange combination causing an error in r3767 - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.2)->getDatetime()); - self::assertTrue($visitorB->doTrackAction('mailto:test@example.org', 'link')); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.25)->getDatetime()); - self::assertTrue($visitorB->doTrackAction('mailto:test@example.org/strangelink', 'link')); - - // Actions.getPageTitle tested with this title - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.25)->getDatetime()); - self::assertTrue($visitorB->doTrackPageView('Checkout / Purchasing...')); - self::checkResponse($visitorB->doBulkTrack()); - - // - - // First visitor on Idsite 2: one page view, with Website referer - $visitorAsite2 = self::getTracker($idSite2, Piwik_Date::factory($dateTime)->addHour(24)->getDatetime(), $defaultInit = true); - $visitorAsite2->setUserAgent('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)'); - $visitorAsite2->setUrlReferrer('http://only-homepage-referer.com/'); - $visitorAsite2->setUrl('http://example2.com/home#notIgnoredFragment#'); - $visitorAsite2->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($dateTime)->addHour(24)->getTimestamp(); - self::checkResponse($visitorAsite2->doTrackPageView('Website 2 page view')); - // test with invalid URL - $visitorAsite2->setUrl('this is invalid url'); - // and an empty title - self::checkResponse($visitorAsite2->doTrackPageView('')); +Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays::$fixture = + new Test_Piwik_Fixture_TwoSitesTwoVisitorsDifferentDays(); - // Returning visitor on Idsite 2 1 day later, one page view, with chinese referer -// $t2->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48 + 10)->getDatetime()); -// $t2->setUrlReferrer('http://www.baidu.com/s?wd=%D0%C2+%CE%C5&n=2'); -// $t2->setUrl('http://example2.com/home'); -// self::checkResponse($t2->doTrackPageView('I\'m a returning visitor...')); - } -} diff --git a/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDays_ArchivingDisabledTest.php b/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDays_ArchivingDisabledTest.php index 6f45a99cbe..4ec0475f66 100755 --- a/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDays_ArchivingDisabledTest.php +++ b/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDays_ArchivingDisabledTest.php @@ -7,28 +7,11 @@ */ /** - * TODO + * Tests IndexedBySite optimizations when archiving is disabled. */ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_ArchivingDisabled extends IntegrationTestCase { - protected static $idSite1 = 1; - protected static $idSite2 = 2; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - protected static $dateTime = '2010-01-03 11:22:33'; - protected static $allowConversions = true; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -42,26 +25,28 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_ArchivingDisa public function getApiForTesting() { + $dateTime = self::$fixture->dateTime; + $periods = array('day', 'week', 'month', 'year'); return array( // disable archiving & check that there is no archive data array('VisitsSummary.get', array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => $dateTime, 'periods' => $periods, 'disableArchiving' => true, 'testSuffix' => '_disabledBefore')), // re-enable archiving & check the output array('VisitsSummary.get', array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => $dateTime, 'periods' => $periods, 'disableArchiving' => false, 'testSuffix' => '_enabled')), // diable archiving again & check the output array('VisitsSummary.get', array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => $dateTime, 'periods' => $periods, 'disableArchiving' => true, 'testSuffix' => '_disabledAfter')), @@ -72,98 +57,9 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_ArchivingDisa { return 'TwoVisitors_twoWebsites_differentDays_ArchivingDisabled'; } +} - public static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - $ecommerce = self::$allowConversions ? 1 : 0; - - self::createWebsite(self::$dateTime, $ecommerce, "Site 1"); - self::createWebsite(self::$dateTime, 0, "Site 2"); - - if (self::$allowConversions) { - Piwik_Goals_API::getInstance()->addGoal(self::$idSite1, 'all', 'url', 'http', 'contains', false, 5); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite2, 'all', 'url', 'http', 'contains'); - } - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite1; - $idSite2 = self::$idSite2; - - // - - // First visitor on Idsite 1: two page views - $datetimeSpanOverTwoDays = '2010-01-03 23:55:00'; - $visitorA = self::getTracker($idSite, $datetimeSpanOverTwoDays, $defaultInit = true); - $visitorA->setUrlReferrer('http://referer.com/page.htm?param=valuewith some spaces'); - $visitorA->setUrl('http://example.org/index.htm'); - $visitorA->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($datetimeSpanOverTwoDays)->getTimestamp(); - self::checkResponse($visitorA->doTrackPageView('first page view')); - - $visitorA->setForceVisitDateTime(Piwik_Date::factory($datetimeSpanOverTwoDays)->addHour(0.1)->getDatetime()); - // testing with empty URL and empty page title - $visitorA->setUrl(' '); - self::checkResponse($visitorA->doTrackPageView(' ')); - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->enableBulkTracking(); - $visitorB->setTokenAuth(self::getTokenAuth()); - $visitorB->setIp('100.52.156.83'); - $visitorB->setResolution(800, 300); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setUrlReferrer(''); - $visitorB->setUserAgent('Opera/9.63 (Windows NT 5.1; U; en) Presto/2.1.1'); - $visitorB->setUrl('http://example.org/products'); - $visitorB->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($dateTime)->addHour(1)->getTimestamp(); - self::assertTrue($visitorB->doTrackPageView('first page view')); - - // - - // Second visitor again on Idsite 1: 2 page views 2 days later, 2010-01-05 - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->getDatetime()); - // visitor_returning is set to 1 only when visit count more than 1 - // Temporary, until we implement 1st party cookies in PiwikTracker - $visitorB->DEBUG_APPEND_URL .= '&_idvc=2&_viewts=' . Piwik_Date::factory($dateTime)->getTimestamp(); - - $visitorB->setUrlReferrer('http://referer.com/Other_Page.htm'); - $visitorB->setUrl('http://example.org/index.htm'); - self::assertTrue($visitorB->doTrackPageView('second visitor/two days later/a new visit')); - // Second page view 6 minutes later - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.1)->getDatetime()); - $visitorB->setUrl('http://example.org/thankyou'); - self::assertTrue($visitorB->doTrackPageView('second visitor/two days later/second page view')); - - // testing a strange combination causing an error in r3767 - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.2)->getDatetime()); - self::assertTrue($visitorB->doTrackAction('mailto:test@example.org', 'link')); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.25)->getDatetime()); - self::assertTrue($visitorB->doTrackAction('mailto:test@example.org/strangelink', 'link')); - - // Actions.getPageTitle tested with this title - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.25)->getDatetime()); - self::assertTrue($visitorB->doTrackPageView('Checkout / Purchasing...')); - self::checkResponse($visitorB->doBulkTrack()); - - // - - // First visitor on Idsite 2: one page view, with Website referer - $visitorAsite2 = self::getTracker($idSite2, Piwik_Date::factory($dateTime)->addHour(24)->getDatetime(), $defaultInit = true); - $visitorAsite2->setUserAgent('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)'); - $visitorAsite2->setUrlReferrer('http://only-homepage-referer.com/'); - $visitorAsite2->setUrl('http://example2.com/home'); - $visitorAsite2->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($dateTime)->addHour(24)->getTimestamp(); - self::checkResponse($visitorAsite2->doTrackPageView('Website 2 page view')); - // test with invalid URL - $visitorAsite2->setUrl('this is invalid url'); - // and an empty title - self::checkResponse($visitorAsite2->doTrackPageView('')); +Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_ArchivingDisabled::$fixture = + new Test_Piwik_Fixture_TwoSitesTwoVisitorsDifferentDays(); +Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_ArchivingDisabled::$fixture->allowConversions = true; - // Returning visitor on Idsite 2 1 day later, one page view, with chinese referer -// $t2->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48 + 10)->getDatetime()); -// $t2->setUrlReferrer('http://www.baidu.com/s?wd=%D0%C2+%CE%C5&n=2'); -// $t2->setUrl('http://example2.com/home'); -// self::checkResponse($t2->doTrackPageView('I\'m a returning visitor...')); - } -} diff --git a/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDays_ConversionsTest.php b/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDays_ConversionsTest.php index 89dc547841..f1d13db228 100755 --- a/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDays_ConversionsTest.php +++ b/tests/PHPUnit/Integration/TwoVisitors_TwoWebsites_DifferentDays_ConversionsTest.php @@ -14,24 +14,7 @@ require_once 'Goals/Goals.php'; */ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_Conversions extends IntegrationTestCase { - protected static $idSite1 = 1; - protected static $idSite2 = 2; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - protected static $dateTime = '2010-01-03 11:22:33'; - protected static $allowConversions = true; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -50,6 +33,9 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_Conversions e public function getApiForTesting() { + $dateTime = self::$fixture->dateTime; + $idSite1 = self::$fixture->idSite1; + // NOTE: copied from TwoVisitors_TwoWebsites_DifferentDays (including the test or inheriting means // the test will get run by phpunit, even when we only want to run this one. should be put into // non-test class later.) @@ -61,20 +47,20 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_Conversions e $result = array( // Request data for the last 6 periods and idSite=all array($apiToCall, array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => $dateTime, 'periods' => $periods, 'setDateLastN' => true)), // Request data for the last 6 periods and idSite=1 - array($apiToCall, array('idSite' => self::$idSite1, - 'date' => self::$dateTime, + array($apiToCall, array('idSite' => $idSite1, + 'date' => $dateTime, 'periods' => $periods, 'setDateLastN' => true, 'testSuffix' => '_idSiteOne_')), // We also test a single period to check that this use case (Reports per idSite in the response) works array($singlePeriodApi, array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => $dateTime, 'periods' => array('day', 'month'), 'setDateLastN' => false, 'testSuffix' => '_NotLastNPeriods')), @@ -86,8 +72,8 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_Conversions e list($apiModule, $apiAction) = explode(".", $api); $result[] = array( - 'API.getProcessedReport', array('idSite' => self::$idSite1, - 'date' => self::$dateTime, + 'API.getProcessedReport', array('idSite' => $idSite1, + 'date' => $dateTime, 'periods' => array('day'), 'setDateLastN' => true, 'apiModule' => $apiModule, @@ -114,98 +100,9 @@ class Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_Conversions e { return 'TwoVisitors_twoWebsites_differentDays_Conversions'; } +} - public static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - $ecommerce = self::$allowConversions ? 1 : 0; - - self::createWebsite(self::$dateTime, $ecommerce, "Site 1"); - self::createWebsite(self::$dateTime, 0, "Site 2"); - - if (self::$allowConversions) { - Piwik_Goals_API::getInstance()->addGoal(self::$idSite1, 'all', 'url', 'http', 'contains', false, 5); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite2, 'all', 'url', 'http', 'contains'); - } - } +Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_Conversions::$fixture = + new Test_Piwik_Fixture_TwoSitesTwoVisitorsDifferentDays(); +Test_Piwik_Integration_TwoVisitors_TwoWebsites_DifferentDays_Conversions::$fixture->allowConversions = true; - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite1; - $idSite2 = self::$idSite2; - - // - - // First visitor on Idsite 1: two page views - $datetimeSpanOverTwoDays = '2010-01-03 23:55:00'; - $visitorA = self::getTracker($idSite, $datetimeSpanOverTwoDays, $defaultInit = true); - $visitorA->setUrlReferrer('http://referer.com/page.htm?param=valuewith some spaces'); - $visitorA->setUrl('http://example.org/index.htm'); - $visitorA->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($datetimeSpanOverTwoDays)->getTimestamp(); - self::checkResponse($visitorA->doTrackPageView('first page view')); - - $visitorA->setForceVisitDateTime(Piwik_Date::factory($datetimeSpanOverTwoDays)->addHour(0.1)->getDatetime()); - // testing with empty URL and empty page title - $visitorA->setUrl(' '); - self::checkResponse($visitorA->doTrackPageView(' ')); - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->enableBulkTracking(); - $visitorB->setTokenAuth(self::getTokenAuth()); - $visitorB->setIp('100.52.156.83'); - $visitorB->setResolution(800, 300); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setUrlReferrer(''); - $visitorB->setUserAgent('Opera/9.63 (Windows NT 5.1; U; en) Presto/2.1.1'); - $visitorB->setUrl('http://example.org/products'); - $visitorB->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($dateTime)->addHour(1)->getTimestamp(); - self::assertTrue($visitorB->doTrackPageView('first page view')); - - // - - // Second visitor again on Idsite 1: 2 page views 2 days later, 2010-01-05 - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->getDatetime()); - // visitor_returning is set to 1 only when visit count more than 1 - // Temporary, until we implement 1st party cookies in PiwikTracker - $visitorB->DEBUG_APPEND_URL .= '&_idvc=2&_viewts=' . Piwik_Date::factory($dateTime)->getTimestamp(); - - $visitorB->setUrlReferrer('http://referer.com/Other_Page.htm'); - $visitorB->setUrl('http://example.org/index.htm'); - self::assertTrue($visitorB->doTrackPageView('second visitor/two days later/a new visit')); - // Second page view 6 minutes later - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.1)->getDatetime()); - $visitorB->setUrl('http://example.org/thankyou'); - self::assertTrue($visitorB->doTrackPageView('second visitor/two days later/second page view')); - - // testing a strange combination causing an error in r3767 - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.2)->getDatetime()); - self::assertTrue($visitorB->doTrackAction('mailto:test@example.org', 'link')); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.25)->getDatetime()); - self::assertTrue($visitorB->doTrackAction('mailto:test@example.org/strangelink', 'link')); - - // Actions.getPageTitle tested with this title - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48)->addHour(0.25)->getDatetime()); - self::assertTrue($visitorB->doTrackPageView('Checkout / Purchasing...')); - self::checkResponse($visitorB->doBulkTrack()); - - // - - // First visitor on Idsite 2: one page view, with Website referer - $visitorAsite2 = self::getTracker($idSite2, Piwik_Date::factory($dateTime)->addHour(24)->getDatetime(), $defaultInit = true); - $visitorAsite2->setUserAgent('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)'); - $visitorAsite2->setUrlReferrer('http://only-homepage-referer.com/'); - $visitorAsite2->setUrl('http://example2.com/home'); - $visitorAsite2->DEBUG_APPEND_URL = '&_idts=' . Piwik_Date::factory($dateTime)->addHour(24)->getTimestamp(); - self::checkResponse($visitorAsite2->doTrackPageView('Website 2 page view')); - // test with invalid URL - $visitorAsite2->setUrl('this is invalid url'); - // and an empty title - self::checkResponse($visitorAsite2->doTrackPageView('')); - - // Returning visitor on Idsite 2 1 day later, one page view, with chinese referer -// $t2->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(48 + 10)->getDatetime()); -// $t2->setUrlReferrer('http://www.baidu.com/s?wd=%D0%C2+%CE%C5&n=2'); -// $t2->setUrl('http://example2.com/home'); -// self::checkResponse($t2->doTrackPageView('I\'m a returning visitor...')); - } -} diff --git a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariablesTest.php b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariablesTest.php index 85f82ec8e0..188707de0a 100755 --- a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariablesTest.php +++ b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariablesTest.php @@ -11,43 +11,24 @@ */ class Test_Piwik_Integration_TwoVisitsWithCustomVariables extends IntegrationTestCase { - protected static $dateTime = '2010-01-03 11:22:33'; - protected static $width = 1111; - protected static $height = 222; - - protected static $idSite = 1; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - protected static $visitorId = '61e8cc2d51fea26d'; - - protected static $useEscapedQuotes = true; - protected static $doExtraQuoteTests = true; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $dateTime = self::$fixture->dateTime; + $apiToCall = array('VisitsSummary.get', 'CustomVariables.getCustomVariables'); $return = array( array($apiToCall, array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => $dateTime, 'periods' => array('day', 'week'), 'setDateLastN' => true)), // test getProcessedReport w/ custom variables subtable - array('API.getProcessedReport', array('idSite' => self::$idSite, - 'date' => self::$dateTime, + array('API.getProcessedReport', array('idSite' => $idSite, + 'date' => $dateTime, 'periods' => 'day', 'apiModule' => 'CustomVariables', 'apiAction' => 'getCustomVariablesValuesFromNameId', @@ -72,105 +53,7 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables extends IntegrationTes { return 'twoVisitsWithCustomVariables'; } +} - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js', 'manually', '', ''); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'second goal', 'manually', '', ''); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idGoal = self::$idGoal1; - $idGoal2 = self::$idGoal2; - - $visitorA = self::getTracker($idSite, $dateTime, $defaultInit = true); - // Used to test actual referer + keyword position in Live! - $visitorA->setUrlReferrer(urldecode('http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB4QFjAA&url=http%3A%2F%2Fpiwik.org%2F&rct=j&q=this%20keyword%20should%20be%20ranked&ei=V8WfTePkKKLfiALrpZWGAw&usg=AFQjCNF_MGJRqKPvaKuUokHtZ3VvNG9ALw&sig2=BvKAdCtNixsmfNWXjsNyMw')); - - // no campaign, but a search engine to attribute the goal conversion to - $attribution = array( - '', - '', - 1302306504, - 'http://www.google.com/search?q=piwik&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a' - ); - $visitorA->setAttributionInfo(json_encode($attribution)); - - $visitorA->setResolution(self::$width, self::$height); - - // At first, visitor custom var is set to LoggedOut - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitorA->setUrl('http://example.org/homepage'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - self::checkResponse($visitorA->doTrackPageView('Homepage')); - self::checkResponse($visitorA->doTrackGoal($idGoal2)); - - // After login, set to LoggedIn, should overwrite previous value - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $visitorA->setUrl('http://example.org/user/profile'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedIn'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = 'Loggedin', $scope = 'page'); - if (self::$useEscapedQuotes) { - $lookingAtProfile = 'looking at "profile page"'; - } else { - $lookingAtProfile = 'looking at profile page'; - } - $visitorA->setCustomVariable($id = 5, $name = 'Status user', $value = $lookingAtProfile, $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Profile page')); - - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE', $value = ''); - $visitorA->setCustomVariable($id = 1, $name = 'Language', $value = 'FR', $scope = 'page'); - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE PAGE SCOPE', $value = '', $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = "looking at \"profile page\"", $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'Value will be VERY long and truncated', $value = 'abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----'); - self::checkResponse($visitorA->doTrackPageView('Profile page for user *_)%')); - self::checkResponse($visitorA->doTrackGoal($idGoal)); - - if (self::$doExtraQuoteTests) { - $visitorA->setCustomVariable($id = 2, $name = 'var1', $value = 'looking at "profile page"', - $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'var2', $value = '\'looking at "\profile page"\'', - $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'var3', $value = '\\looking at "\profile page"\\', - $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Concurrent page views')); - } - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->setVisitorId(self::$visitorId); - $visitorB->setUrlReferrer(''); - - $attribution = array( - ' CAMPAIGN NAME -%20YEAH! ', - ' CAMPAIGN%20KEYWORD - RIGHT... ', - 1302306504, - 'http://www.example.org/test/really?q=yes' - ); - $visitorB->setAttributionInfo(json_encode($attribution)); - $visitorB->setResolution(self::$width, self::$height); - $visitorB->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6'); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - $visitorB->setCustomVariable($id = 2, $name = 'Othercustom value which should be truncated abcdefghijklmnopqrstuvwxyz', $value = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'); - $visitorB->setCustomVariable($id = -2, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = array('not tracked'), $value = 'not tracked'); - $visitorB->setUrl('http://example.org/homepage'); - self::checkResponse($visitorB->doTrackGoal($idGoal, 1000)); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.1)->getDatetime()); - self::checkResponse($visitorB->doTrackPageView('Homepage')); +Test_Piwik_Integration_TwoVisitsWithCustomVariables::$fixture = new Test_Piwik_Fixture_TwoVisitsWithCustomVariables(); - // DIFFERENT test - - // testing that starting the visit with an outlink works (doesn't trigger errors) - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - self::checkResponse($visitorB->doTrackAction('http://test.com', 'link')); - } -} diff --git a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentContainsTest.php b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentContainsTest.php index 724fadb81d..585c10bbdb 100755 --- a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentContainsTest.php +++ b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentContainsTest.php @@ -11,29 +11,7 @@ */ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentContains extends IntegrationTestCase { - protected static $dateTime = '2010-01-03 11:22:33'; - protected static $width = 1111; - protected static $height = 222; - - protected static $idSite = 1; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - protected static $visitorId = '61e8cc2d51fea26d'; - - protected static $useEscapedQuotes = true; - protected static $doExtraQuoteTests = false; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition public function getOutputPrefix() { @@ -52,6 +30,9 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentContains extend public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $dateTime = self::$fixture->dateTime; + $return = array(); $api = array('Actions.getPageUrls', 'Actions.getPageTitles', 'VisitsSummary.get'); @@ -67,7 +48,7 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentContains extend foreach ($segmentsToTest as $segment) { // Also test "Page URL / Page title CONTAINS string" feature $return[] = array($segment[2], - array('idSite' => self::$idSite, 'date' => self::$dateTime, 'periods' => array('day'), + array('idSite' => $idSite, 'date' => $dateTime, 'periods' => array('day'), 'setDateLastN' => false, 'segment' => $segment[0], 'testSuffix' => $segment[1]) @@ -75,106 +56,9 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentContains extend } return $return; } - - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js', 'manually', '', ''); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'second goal', 'manually', '', ''); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idGoal = self::$idGoal1; - $idGoal2 = self::$idGoal2; - - $visitorA = self::getTracker($idSite, $dateTime, $defaultInit = true); - // Used to test actual referer + keyword position in Live! - $visitorA->setUrlReferrer(urldecode('http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB4QFjAA&url=http%3A%2F%2Fpiwik.org%2F&rct=j&q=this%20keyword%20should%20be%20ranked&ei=V8WfTePkKKLfiALrpZWGAw&usg=AFQjCNF_MGJRqKPvaKuUokHtZ3VvNG9ALw&sig2=BvKAdCtNixsmfNWXjsNyMw')); - - // no campaign, but a search engine to attribute the goal conversion to - $attribution = array( - '', - '', - 1302306504, - 'http://www.google.com/search?q=piwik&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a' - ); - $visitorA->setAttributionInfo(json_encode($attribution)); - - $visitorA->setResolution(self::$width, self::$height); - - // At first, visitor custom var is set to LoggedOut - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitorA->setUrl('http://example.org/homepage'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - self::checkResponse($visitorA->doTrackPageView('Homepage')); - self::checkResponse($visitorA->doTrackGoal($idGoal2)); - - // After login, set to LoggedIn, should overwrite previous value - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $visitorA->setUrl('http://example.org/user/profile'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedIn'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = 'Loggedin', $scope = 'page'); - if (self::$useEscapedQuotes) { - $lookingAtProfile = 'looking at "profile page"'; - } else { - $lookingAtProfile = 'looking at profile page'; - } - $visitorA->setCustomVariable($id = 5, $name = 'Status user', $value = $lookingAtProfile, $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Profile page')); - - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE', $value = ''); - $visitorA->setCustomVariable($id = 1, $name = 'Language', $value = 'FR', $scope = 'page'); - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE PAGE SCOPE', $value = '', $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = "looking at \"profile page\"", $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'Value will be VERY long and truncated', $value = 'abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----'); - self::checkResponse($visitorA->doTrackPageView('Profile page for user *_)%')); - self::checkResponse($visitorA->doTrackGoal($idGoal)); - - if (self::$doExtraQuoteTests) { - $visitorA->setCustomVariable($id = 2, $name = 'var1', $value = 'looking at "profile page"', - $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'var2', $value = '\'looking at "\profile page"\'', - $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'var3', $value = '\\looking at "\profile page"\\', - $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Concurrent page views')); - } - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->setVisitorId(self::$visitorId); - $visitorB->setUrlReferrer(''); - - $attribution = array( - ' CAMPAIGN NAME -%20YEAH! ', - ' CAMPAIGN%20KEYWORD - RIGHT... ', - 1302306504, - 'http://www.example.org/test/really?q=yes' - ); - $visitorB->setAttributionInfo(json_encode($attribution)); - $visitorB->setResolution(self::$width, self::$height); - $visitorB->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6'); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - $visitorB->setCustomVariable($id = 2, $name = 'Othercustom value which should be truncated abcdefghijklmnopqrstuvwxyz', $value = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'); - $visitorB->setCustomVariable($id = -2, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = array('not tracked'), $value = 'not tracked'); - $visitorB->setUrl('http://example.org/homepage'); - self::checkResponse($visitorB->doTrackGoal($idGoal, 1000)); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.1)->getDatetime()); - self::checkResponse($visitorB->doTrackPageView('Homepage')); - - // DIFFERENT test - - // testing that starting the visit with an outlink works (doesn't trigger errors) - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - self::checkResponse($visitorB->doTrackAction('http://test.com', 'link')); - } } +Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentContains::$fixture + = new Test_Piwik_Fixture_TwoVisitsWithCustomVariables(); +Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentContains::$fixture->doExtraQuoteTests = false; + diff --git a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchALL_NoGoalDataTest.php b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchALL_NoGoalDataTest.php index b512ff6975..26b136dff7 100755 --- a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchALL_NoGoalDataTest.php +++ b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchALL_NoGoalDataTest.php @@ -8,29 +8,7 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchALL_NoGoalData extends IntegrationTestCase { - protected static $dateTime = '2010-01-03 11:22:33'; - protected static $width = 1111; - protected static $height = 222; - - protected static $idSite = 1; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - protected static $visitorId = '61e8cc2d51fea26d'; - - protected static $useEscapedQuotes = true; - protected static $doExtraQuoteTests = false; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -48,12 +26,12 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchALL_NoGoal // Segment matching ALL // + adding DOES NOT CONTAIN segment always matched, to test this particular operator - $resolution = self::$width . 'x' . self::$height; + $resolution = self::$fixture->resolutionWidthToUse . 'x' . self::$fixture->resolutionHeightToUse; $segment = 'resolution==' . $resolution . ';customVariableName1!@randomvalue does not exist'; return array( array($apiToCall, array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => self::$fixture->dateTime, 'periods' => array('day', 'week'), 'setDateLastN' => true, 'segment' => $segment)) @@ -64,106 +42,9 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchALL_NoGoal { return 'twoVisitsWithCustomVariables_segmentMatchALL_noGoalData'; } - - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js', 'manually', '', ''); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'second goal', 'manually', '', ''); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idGoal = self::$idGoal1; - $idGoal2 = self::$idGoal2; - - $visitorA = self::getTracker($idSite, $dateTime, $defaultInit = true); - // Used to test actual referer + keyword position in Live! - $visitorA->setUrlReferrer(urldecode('http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB4QFjAA&url=http%3A%2F%2Fpiwik.org%2F&rct=j&q=this%20keyword%20should%20be%20ranked&ei=V8WfTePkKKLfiALrpZWGAw&usg=AFQjCNF_MGJRqKPvaKuUokHtZ3VvNG9ALw&sig2=BvKAdCtNixsmfNWXjsNyMw')); - - // no campaign, but a search engine to attribute the goal conversion to - $attribution = array( - '', - '', - 1302306504, - 'http://www.google.com/search?q=piwik&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a' - ); - $visitorA->setAttributionInfo(json_encode($attribution)); - - $visitorA->setResolution(self::$width, self::$height); - - // At first, visitor custom var is set to LoggedOut - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitorA->setUrl('http://example.org/homepage'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - self::checkResponse($visitorA->doTrackPageView('Homepage')); - self::checkResponse($visitorA->doTrackGoal($idGoal2)); - - // After login, set to LoggedIn, should overwrite previous value - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $visitorA->setUrl('http://example.org/user/profile'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedIn'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = 'Loggedin', $scope = 'page'); - if (self::$useEscapedQuotes) { - $lookingAtProfile = 'looking at "profile page"'; - } else { - $lookingAtProfile = 'looking at profile page'; - } - $visitorA->setCustomVariable($id = 5, $name = 'Status user', $value = $lookingAtProfile, $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Profile page')); - - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE', $value = ''); - $visitorA->setCustomVariable($id = 1, $name = 'Language', $value = 'FR', $scope = 'page'); - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE PAGE SCOPE', $value = '', $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = "looking at \"profile page\"", $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'Value will be VERY long and truncated', $value = 'abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----'); - self::checkResponse($visitorA->doTrackPageView('Profile page for user *_)%')); - self::checkResponse($visitorA->doTrackGoal($idGoal)); - - if (self::$doExtraQuoteTests) { - $visitorA->setCustomVariable($id = 2, $name = 'var1', $value = 'looking at "profile page"', - $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'var2', $value = '\'looking at "\profile page"\'', - $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'var3', $value = '\\looking at "\profile page"\\', - $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Concurrent page views')); - } - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->setVisitorId(self::$visitorId); - $visitorB->setUrlReferrer(''); - - $attribution = array( - ' CAMPAIGN NAME -%20YEAH! ', - ' CAMPAIGN%20KEYWORD - RIGHT... ', - 1302306504, - 'http://www.example.org/test/really?q=yes' - ); - $visitorB->setAttributionInfo(json_encode($attribution)); - $visitorB->setResolution(self::$width, self::$height); - $visitorB->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6'); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - $visitorB->setCustomVariable($id = 2, $name = 'Othercustom value which should be truncated abcdefghijklmnopqrstuvwxyz', $value = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'); - $visitorB->setCustomVariable($id = -2, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = array('not tracked'), $value = 'not tracked'); - $visitorB->setUrl('http://example.org/homepage'); - self::checkResponse($visitorB->doTrackGoal($idGoal, 1000)); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.1)->getDatetime()); - self::checkResponse($visitorB->doTrackPageView('Homepage')); - - // DIFFERENT test - - // testing that starting the visit with an outlink works (doesn't trigger errors) - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - self::checkResponse($visitorB->doTrackAction('http://test.com', 'link')); - } } +Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchALL_NoGoalData::$fixture + = new Test_Piwik_Fixture_TwoVisitsWithCustomVariables(); +Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchALL_NoGoalData::$fixture->doExtraQuoteTests = false; + diff --git a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchNONETest.php b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchNONETest.php index d7fa597535..000ed8bc96 100755 --- a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchNONETest.php +++ b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchNONETest.php @@ -11,29 +11,7 @@ */ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchNONE extends IntegrationTestCase { - protected static $dateTime = '2010-01-03 11:22:33'; - protected static $width = 1111; - protected static $height = 222; - - protected static $idSite = 1; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - protected static $visitorId = '61e8cc2d51fea26d'; - - protected static $useEscapedQuotes = true; - protected static $doExtraQuoteTests = false; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -51,7 +29,7 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchNONE exten return array( array($apiToCall, array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => self::$fixture->dateTime, 'periods' => array('day', 'week'), 'setDateLastN' => true, 'segment' => $this->getSegmentToTest())) @@ -61,7 +39,7 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchNONE exten public function getSegmentToTest() { // Segment matching NONE - $segments = Piwik_API_API::getInstance()->getSegmentsMetadata(self::$idSite); + $segments = Piwik_API_API::getInstance()->getSegmentsMetadata(self::$fixture->idSite); $segmentExpression = array(); $seenVisitorId = false; @@ -90,106 +68,9 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchNONE exten { return 'twoVisitsWithCustomVariables_segmentMatchNONE'; } - - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js', 'manually', '', ''); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'second goal', 'manually', '', ''); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idGoal = self::$idGoal1; - $idGoal2 = self::$idGoal2; - - $visitorA = self::getTracker($idSite, $dateTime, $defaultInit = true); - // Used to test actual referer + keyword position in Live! - $visitorA->setUrlReferrer(urldecode('http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB4QFjAA&url=http%3A%2F%2Fpiwik.org%2F&rct=j&q=this%20keyword%20should%20be%20ranked&ei=V8WfTePkKKLfiALrpZWGAw&usg=AFQjCNF_MGJRqKPvaKuUokHtZ3VvNG9ALw&sig2=BvKAdCtNixsmfNWXjsNyMw')); - - // no campaign, but a search engine to attribute the goal conversion to - $attribution = array( - '', - '', - 1302306504, - 'http://www.google.com/search?q=piwik&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a' - ); - $visitorA->setAttributionInfo(json_encode($attribution)); - - $visitorA->setResolution(self::$width, self::$height); - - // At first, visitor custom var is set to LoggedOut - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitorA->setUrl('http://example.org/homepage'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - self::checkResponse($visitorA->doTrackPageView('Homepage')); - self::checkResponse($visitorA->doTrackGoal($idGoal2)); - - // After login, set to LoggedIn, should overwrite previous value - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $visitorA->setUrl('http://example.org/user/profile'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedIn'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = 'Loggedin', $scope = 'page'); - if (self::$useEscapedQuotes) { - $lookingAtProfile = 'looking at "profile page"'; - } else { - $lookingAtProfile = 'looking at profile page'; - } - $visitorA->setCustomVariable($id = 5, $name = 'Status user', $value = $lookingAtProfile, $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Profile page')); - - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE', $value = ''); - $visitorA->setCustomVariable($id = 1, $name = 'Language', $value = 'FR', $scope = 'page'); - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE PAGE SCOPE', $value = '', $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = "looking at \"profile page\"", $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'Value will be VERY long and truncated', $value = 'abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----'); - self::checkResponse($visitorA->doTrackPageView('Profile page for user *_)%')); - self::checkResponse($visitorA->doTrackGoal($idGoal)); - - if (self::$doExtraQuoteTests) { - $visitorA->setCustomVariable($id = 2, $name = 'var1', $value = 'looking at "profile page"', - $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'var2', $value = '\'looking at "\profile page"\'', - $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'var3', $value = '\\looking at "\profile page"\\', - $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Concurrent page views')); - } - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->setVisitorId(self::$visitorId); - $visitorB->setUrlReferrer(''); - - $attribution = array( - ' CAMPAIGN NAME -%20YEAH! ', - ' CAMPAIGN%20KEYWORD - RIGHT... ', - 1302306504, - 'http://www.example.org/test/really?q=yes' - ); - $visitorB->setAttributionInfo(json_encode($attribution)); - $visitorB->setResolution(self::$width, self::$height); - $visitorB->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6'); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - $visitorB->setCustomVariable($id = 2, $name = 'Othercustom value which should be truncated abcdefghijklmnopqrstuvwxyz', $value = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'); - $visitorB->setCustomVariable($id = -2, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = array('not tracked'), $value = 'not tracked'); - $visitorB->setUrl('http://example.org/homepage'); - self::checkResponse($visitorB->doTrackGoal($idGoal, 1000)); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.1)->getDatetime()); - self::checkResponse($visitorB->doTrackPageView('Homepage')); - - // DIFFERENT test - - // testing that starting the visit with an outlink works (doesn't trigger errors) - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - self::checkResponse($visitorB->doTrackAction('http://test.com', 'link')); - } } +Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchNONE::$fixture + = new Test_Piwik_Fixture_TwoVisitsWithCustomVariables(); +Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchNONE::$fixture->doExtraQuoteTests = false; + diff --git a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchVisitorTypeTest.php b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchVisitorTypeTest.php index ae1ef968c8..f9a26a3276 100755 --- a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchVisitorTypeTest.php +++ b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchVisitorTypeTest.php @@ -11,29 +11,7 @@ */ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchVisitorType extends IntegrationTestCase { - protected static $dateTime = '2010-01-03 11:22:33'; - protected static $width = 1111; - protected static $height = 222; - - protected static $idSite = 1; - protected static $idGoal1 = 1; - protected static $idGoal2 = 2; - protected static $visitorId = '61e8cc2d51fea26d'; - - protected static $useEscapedQuotes = true; - protected static $doExtraQuoteTests = false; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -61,7 +39,7 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchVisitorTyp foreach ($segments as $segment) { $result[] = array( $apiToCall, array('idSite' => 'all', - 'date' => self::$dateTime, + 'date' => self::$fixture->dateTime, 'periods' => $periods, 'setDateLastN' => true, 'segment' => $segment) @@ -117,105 +95,9 @@ class Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchVisitorTyp { return 'twoVisitsWithCustomVariables_segmentMatchVisitorType'; } +} - protected static function setUpWebsitesAndGoals() - { - // tests run in UTC, the Tracker in UTC - self::createWebsite(self::$dateTime); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'triggered js', 'manually', '', ''); - Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'second goal', 'manually', '', ''); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $idGoal = self::$idGoal1; - $idGoal2 = self::$idGoal2; - - $visitorA = self::getTracker($idSite, $dateTime, $defaultInit = true); - // Used to test actual referer + keyword position in Live! - $visitorA->setUrlReferrer(urldecode('http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB4QFjAA&url=http%3A%2F%2Fpiwik.org%2F&rct=j&q=this%20keyword%20should%20be%20ranked&ei=V8WfTePkKKLfiALrpZWGAw&usg=AFQjCNF_MGJRqKPvaKuUokHtZ3VvNG9ALw&sig2=BvKAdCtNixsmfNWXjsNyMw')); - - // no campaign, but a search engine to attribute the goal conversion to - $attribution = array( - '', - '', - 1302306504, - 'http://www.google.com/search?q=piwik&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a' - ); - $visitorA->setAttributionInfo(json_encode($attribution)); - - $visitorA->setResolution(self::$width, self::$height); - - // At first, visitor custom var is set to LoggedOut - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.1)->getDatetime()); - $visitorA->setUrl('http://example.org/homepage'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - self::checkResponse($visitorA->doTrackPageView('Homepage')); - self::checkResponse($visitorA->doTrackGoal($idGoal2)); - - // After login, set to LoggedIn, should overwrite previous value - $visitorA->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - $visitorA->setUrl('http://example.org/user/profile'); - $visitorA->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedIn'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = 'Loggedin', $scope = 'page'); - if (self::$useEscapedQuotes) { - $lookingAtProfile = 'looking at "profile page"'; - } else { - $lookingAtProfile = 'looking at profile page'; - } - $visitorA->setCustomVariable($id = 5, $name = 'Status user', $value = $lookingAtProfile, $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Profile page')); - - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE', $value = ''); - $visitorA->setCustomVariable($id = 1, $name = 'Language', $value = 'FR', $scope = 'page'); - $visitorA->setCustomVariable($id = 2, $name = 'SET WITH EMPTY VALUE PAGE SCOPE', $value = '', $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'Status user', $value = "looking at \"profile page\"", $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'Value will be VERY long and truncated', $value = 'abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----abcdefghijklmnopqrstuvwxyz----'); - self::checkResponse($visitorA->doTrackPageView('Profile page for user *_)%')); - self::checkResponse($visitorA->doTrackGoal($idGoal)); - - if (self::$doExtraQuoteTests) { - $visitorA->setCustomVariable($id = 2, $name = 'var1', $value = 'looking at "profile page"', - $scope = 'page'); - $visitorA->setCustomVariable($id = 3, $name = 'var2', $value = '\'looking at "\profile page"\'', - $scope = 'page'); - $visitorA->setCustomVariable($id = 4, $name = 'var3', $value = '\\looking at "\profile page"\\', - $scope = 'page'); - self::checkResponse($visitorA->doTrackPageView('Concurrent page views')); - } - - // - - // Second new visitor on Idsite 1: one page view - $visitorB = self::getTracker($idSite, $dateTime, $defaultInit = true); - $visitorB->setVisitorId(self::$visitorId); - $visitorB->setUrlReferrer(''); - - $attribution = array( - ' CAMPAIGN NAME -%20YEAH! ', - ' CAMPAIGN%20KEYWORD - RIGHT... ', - 1302306504, - 'http://www.example.org/test/really?q=yes' - ); - $visitorB->setAttributionInfo(json_encode($attribution)); - $visitorB->setResolution(self::$width, self::$height); - $visitorB->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6'); - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1)->getDatetime()); - $visitorB->setCustomVariable($id = 1, $name = 'VisitorType', $value = 'LoggedOut'); - $visitorB->setCustomVariable($id = 2, $name = 'Othercustom value which should be truncated abcdefghijklmnopqrstuvwxyz', $value = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'); - $visitorB->setCustomVariable($id = -2, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = 'not tracked', $value = 'not tracked'); - $visitorB->setCustomVariable($id = 6, $name = array('not tracked'), $value = 'not tracked'); - $visitorB->setUrl('http://example.org/homepage'); - self::checkResponse($visitorB->doTrackGoal($idGoal, 1000)); - - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(1.1)->getDatetime()); - self::checkResponse($visitorB->doTrackPageView('Homepage')); +Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchVisitorType::$fixture + = new Test_Piwik_Fixture_TwoVisitsWithCustomVariables(); +Test_Piwik_Integration_TwoVisitsWithCustomVariables_SegmentMatchVisitorType::$fixture->doExtraQuoteTests = false; - // DIFFERENT test - - // testing that starting the visit with an outlink works (doesn't trigger errors) - $visitorB->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(2)->getDatetime()); - self::checkResponse($visitorB->doTrackAction('http://test.com', 'link')); - } -} diff --git a/tests/PHPUnit/Integration/UrlNormalizationTest.php b/tests/PHPUnit/Integration/UrlNormalizationTest.php index 38f48e31b6..9a7678446f 100644 --- a/tests/PHPUnit/Integration/UrlNormalizationTest.php +++ b/tests/PHPUnit/Integration/UrlNormalizationTest.php @@ -4,20 +4,7 @@ */ class Test_Piwik_Integration_UrlNormalization extends IntegrationTestCase { - protected static $dateTime = '2010-03-06 11:22:33'; - protected static $idSite = 1; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -31,54 +18,57 @@ class Test_Piwik_Integration_UrlNormalization extends IntegrationTestCase public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $dateTime = self::$fixture->dateTime; + $return = array(); $return[] = array('Actions.getPageUrls', array( 'testSuffix' => '_urls', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, )); $return[] = array('Actions.getPageTitles', array( 'testSuffix' => '_titles', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, )); $return[] = array('Actions.getPageUrls', array( 'testSuffix' => '_pagesSegmented', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'segment' => 'pageUrl==https://WWw.example.org/foo/bar2.html', )); // Testing entryPageUrl with AND segment $return[] = array('Actions.getPageUrls', array( 'testSuffix' => '_pagesSegmented', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'segment' => 'entryPageUrl==http://example.org/foo/bar.html;pageUrl==https://WWw.example.org/foo/bar2.html', )); // Testing exitPageUrl with AND segment $return[] = array('Actions.getPageUrls', array( 'testSuffix' => '_pagesSegmented', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'segment' => 'exitPageUrl==example.org/foo/bar4.html;pageUrl==https://WWw.example.org/foo/bar2.html', )); $return[] = array('Actions.getPageUrls', array( 'testSuffix' => '_pagesSegmented', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'segment' => 'pageUrl==example.org/foo/bar2.html', )); $return[] = array('Actions.getPageUrls', array( 'testSuffix' => '_pagesSegmentedRef', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'segment' => 'referrerUrl==http://www.google.com/search?q=piwik', )); $return[] = array('Referers.getKeywordsForPageUrl', array( 'testSuffix' => '_keywords', - 'idSite' => self::$idSite, - 'date' => self::$dateTime, + 'idSite' => $idSite, + 'date' => $dateTime, 'otherRequestParameters' => array( 'url' => 'http://WWW.example.org/foo/bar.html' ) @@ -115,41 +105,7 @@ class Test_Piwik_Integration_UrlNormalization extends IntegrationTestCase { return 'UrlNormalization'; } - - protected static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTime); - } - - protected static function trackVisits() - { - $dateTime = self::$dateTime; - $idSite = self::$idSite; - $t = self::getTracker($idSite, $dateTime, $defaultInit = true, $useThirdPartyCookie = 1); - - $t->setUrlReferrer('http://www.google.com/search?q=piwik'); - $t->setUrl('http://example.org/foo/bar.html'); - self::checkResponse($t->doTrackPageView('http://incredible.title/')); - - $t->setUrl('https://example.org/foo/bar.html'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.2)->getDatetime()); - self::checkResponse($t->doTrackPageView('https://incredible.title/')); - - $t->setUrl('https://wWw.example.org/foo/bar2.html'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.3)->getDatetime()); - self::checkResponse($t->doTrackPageView('http://www.incredible.title/')); - - $t->setUrl('http://WwW.example.org/foo/bar2.html'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.4)->getDatetime()); - self::checkResponse($t->doTrackPageView('https://www.incredible.title/')); - - $t->setUrl('http://www.example.org/foo/bar3.html'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.5)->getDatetime()); - self::checkResponse($t->doTrackPageView('incredible.title/')); - - $t->setUrl('https://example.org/foo/bar4.html'); - $t->setForceVisitDateTime(Piwik_Date::factory($dateTime)->addHour(0.6)->getDatetime()); - self::checkResponse($t->doTrackPageView('incredible.title/')); - } } +Test_Piwik_Integration_UrlNormalization::$fixture = new Test_Piwik_Fixture_OneVisitWithAbnormalPageviewUrls(); + diff --git a/tests/PHPUnit/Integration/VisitsInPast_InvalidateOldReportsTest.php b/tests/PHPUnit/Integration/VisitsInPast_InvalidateOldReportsTest.php index b89d3aa87a..851137cbb3 100644 --- a/tests/PHPUnit/Integration/VisitsInPast_InvalidateOldReportsTest.php +++ b/tests/PHPUnit/Integration/VisitsInPast_InvalidateOldReportsTest.php @@ -7,29 +7,11 @@ */ /** - * + * Track visits before website creation date and test that Piwik handles them correctly. */ class Test_Piwik_Integration_VisitsInPast_InvalidateOldReports extends IntegrationTestCase { - protected static $dateTimeFirstDateWebsite1 = '2010-03-06 01:22:33'; - protected static $dateTimeDateInPastWebsite1 = '2010-01-06 01:22:33'; - - protected static $dateTimeFirstDateWebsite2 = '2010-01-03 20:22:33'; - protected static $dateTimeDateInPastWebsite2 = '2009-10-30 01:22:33'; - protected static $idSite = 1; - protected static $idSite2 = 2; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - try { - self::setUpWebsitesAndGoals(); - self::trackVisits(); - } catch(Exception $e) { - // Skip whole test suite if an error occurs while setup - throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()); - } - } + public static $fixture = null; // initialized below class definition /** * @dataProvider getApiForTesting @@ -46,6 +28,11 @@ class Test_Piwik_Integration_VisitsInPast_InvalidateOldReports extends Integrati */ public function getApiForTesting() { + $idSite = self::$fixture->idSite; + $idSite2 = self::$fixture->idSite2; + $dateTimeDateInPastWebsite1 = self::$fixture->dateTimeDateInPastWebsite1; + $dateTimeDateInPastWebsite2 = self::$fixture->dateTimeDateInPastWebsite2; + // We test a typical Numeric and a Recursive blob reports $apiToCall = array('VisitsSummary.get', 'Actions.getPageUrls'); @@ -54,15 +41,15 @@ class Test_Piwik_Integration_VisitsInPast_InvalidateOldReports extends Integrati // Build tests for the 2 websites return array( - array($apiToCall, array('idSite' => self::$idSite, - 'testSuffix' => 'Website' . self::$idSite . '_OldReportsShouldNotAppear', - 'date' => self::$dateTimeDateInPastWebsite1, + array($apiToCall, array('idSite' => $idSite, + 'testSuffix' => 'Website'.$idSite.'_OldReportsShouldNotAppear', + 'date' => $dateTimeDateInPastWebsite1, 'periods' => 'month', 'setDateLastN' => 4, // 4months ahead 'otherRequestParameters' => array('expanded' => 1))), - array($apiToCall, array('idSite' => self::$idSite2, - 'testSuffix' => 'Website' . self::$idSite2 . '_OldReportsShouldNotAppear', - 'date' => self::$dateTimeDateInPastWebsite2, + array($apiToCall, array('idSite' => $idSite2, + 'testSuffix' => 'Website'.$idSite2.'_OldReportsShouldNotAppear', + 'date' => $dateTimeDateInPastWebsite2, 'periods' => 'month', 'setDateLastN' => 4, // 4months ahead 'otherRequestParameters' => array('expanded' => 1))), @@ -77,18 +64,21 @@ class Test_Piwik_Integration_VisitsInPast_InvalidateOldReports extends Integrati */ public function testAnotherApi($api, $params) { + $idSite = self::$fixture->idSite; + $idSite2 = self::$fixture->idSite2; + // 1) Invalidate old reports for the 2 websites // Test invalidate 1 date only $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=4,5,6,55,-1,s',1&dates=2010-01-03"); ($r->process()); // Test invalidate comma separated dates - $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . self::$idSite . "," . self::$idSite2 . "&dates=2010-01-06,2009-10-30"); + $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . $idSite . "," . $idSite2 . "&dates=2010-01-06,2009-10-30"); ($r->process()); // test invalidate date in the past - $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . self::$idSite2 . "&dates=2009-06-29"); + $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . $idSite2 . "&dates=2009-06-29"); ($r->process()); // invalidate a date more recent to check the date is only updated when it's earlier than current - $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . self::$idSite2 . "&dates=2010-03-03"); + $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . $idSite2 . "&dates=2010-03-03"); ($r->process()); // 2) Call API again, with an older date, which should now return data @@ -101,18 +91,23 @@ class Test_Piwik_Integration_VisitsInPast_InvalidateOldReports extends Integrati */ public function getAnotherApiForTesting() { + $idSite = self::$fixture->idSite; + $idSite2 = self::$fixture->idSite2; + $dateTimeDateInPastWebsite1 = self::$fixture->dateTimeDateInPastWebsite1; + $dateTimeDateInPastWebsite2 = self::$fixture->dateTimeDateInPastWebsite2; + $apiToCall = array('VisitsSummary.get', 'Actions.getPageUrls'); return array( - array($apiToCall, array('idSite' => self::$idSite, - 'testSuffix' => 'Website' . self::$idSite . '_OldReportsShouldAppear', - 'date' => self::$dateTimeDateInPastWebsite1, + array($apiToCall, array('idSite' => $idSite, + 'testSuffix' => 'Website' . $idSite . '_OldReportsShouldAppear', + 'date' => $dateTimeDateInPastWebsite1, 'periods' => 'month', 'setDateLastN' => 4, // 4months ahead 'otherRequestParameters' => array('expanded' => 1))), - array($apiToCall, array('idSite' => self::$idSite2, - 'testSuffix' => 'Website' . self::$idSite2 . '_OldReportsShouldAppear', - 'date' => self::$dateTimeDateInPastWebsite2, + array($apiToCall, array('idSite' => $idSite2, + 'testSuffix' => 'Website' . $idSite2 . '_OldReportsShouldAppear', + 'date' => $dateTimeDateInPastWebsite2, 'periods' => 'month', 'setDateLastN' => 4, // 4months ahead 'otherRequestParameters' => array('expanded' => 1))), @@ -123,77 +118,7 @@ class Test_Piwik_Integration_VisitsInPast_InvalidateOldReports extends Integrati { return 'VisitsInPast_InvalidateOldReports'; } +} - public static function setUpWebsitesAndGoals() - { - self::createWebsite(self::$dateTimeFirstDateWebsite1); - self::createWebsite(self::$dateTimeFirstDateWebsite2); - } - - protected static function trackVisits() - { - /** - * Track Visits normal date for the 2 websites - */ - // WEBSITE 1 - $t = self::getTracker(self::$idSite, self::$dateTimeFirstDateWebsite1, $defaultInit = true); - $t->setUrl('http://example.org/category/Page1'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page2'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page3'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/Home'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/Contact'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/Contact/ThankYou'); - self::checkResponse($t->doTrackPageView('Hello')); - - // WEBSITE 2 - $t = self::getTracker(self::$idSite2, self::$dateTimeFirstDateWebsite2, $defaultInit = true); - $t->setIp('156.15.13.12'); - $t->setUrl('http://example.org/category/Page1'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page2'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page3'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/Home'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/Contact'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/Contact/ThankYou'); - self::checkResponse($t->doTrackPageView('Hello')); - - /** - * Track visits in the past (before website creation date) for the 2 websites - */ - // WEBSITE1 - $t = self::getTracker(self::$idSite, self::$dateTimeDateInPastWebsite1, $defaultInit = true); - $t->setIp('156.5.55.2'); - $t->setUrl('http://example.org/category/Page1'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page1'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page2'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Pagexx'); - self::checkResponse($t->doTrackPageView('Blabla')); +Test_Piwik_Integration_VisitsInPast_InvalidateOldReports::$fixture = new Test_Piwik_Fixture_TwoSitesVisitsInPast(); - // WEBSITE2 - $t = self::getTracker(self::$idSite2, self::$dateTimeDateInPastWebsite2, $defaultInit = true); - $t->setIp('156.52.3.22'); - $t->setUrl('http://example.org/category/Page1'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page1'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Page2'); - self::checkResponse($t->doTrackPageView('Hello')); - $t->setUrl('http://example.org/category/Pageyy'); - self::checkResponse($t->doTrackPageView('Blabla')); - $t->setForceVisitDateTime(Piwik_Date::factory(self::$dateTimeDateInPastWebsite2)->addHour(0.1)->getDatetime()); - $t->setUrl('http://example.org/category/Pageyy'); - self::checkResponse($t->doTrackPageView('Blabla')); - } -} diff --git a/tests/PHPUnit/IntegrationTestCase.php b/tests/PHPUnit/IntegrationTestCase.php index 48827f0017..3ee7c7f59c 100755 --- a/tests/PHPUnit/IntegrationTestCase.php +++ b/tests/PHPUnit/IntegrationTestCase.php @@ -48,9 +48,40 @@ abstract class IntegrationTestCase extends PHPUnit_Framework_TestCase public static function setUpBeforeClass() { self::_setUpBeforeClass(); + + if (isset(static::$fixture)) + { + self::setupFixture(static::$fixture); + } + } + + protected static function setupFixture( $fixture ) + { + try + { + $fixture->setUp(); + } + catch(Exception $e) + { + // Skip whole test suite if an error occurs while setup + throw new PHPUnit_Framework_SkippedTestSuiteError($e->getMessage()."\n".$e->getTraceAsString()); + } + } + + protected static function teardownFixture( $fixture ) + { + if (isset(static::$fixture)) + { + self::tearDownFixture(static::$fixture); + } + + $fixture->tearDown(); } - // this function + /** + * setupBeforeClass' implementation. Can be called by derived classes in case + * they need to do some custom setup procedure. + */ public static function _setUpBeforeClass( $dbName = false, $createEmptyDatabase = true, $createConfig = true ) { try { @@ -236,161 +267,9 @@ abstract class IntegrationTestCase extends PHPUnit_Framework_TestCase self::$apiNotToCall = $apiNotToCall; } - /** - * Returns a PiwikTracker object that you can then use to track pages or goals. - * - * @param $idSite - * @param $dateTime - * @param boolean $defaultInit If set to true, the tracker object will have default IP, user agent, time, resolution, etc. - * - * @return PiwikTracker - */ - public static function getTracker($idSite, $dateTime, $defaultInit = true, $useLocal = false ) - { - if ($useLocal) - { - require_once PIWIK_INCLUDE_PATH . '/tests/LocalTracker.php'; - $t = new Piwik_LocalTracker($idSite, self::getTrackerUrl()); - } - else - { - $t = new PiwikTracker( $idSite, self::getTrackerUrl()); - } - $t->setForceVisitDateTime($dateTime); - - if($defaultInit) - { - $t->setIp('156.5.3.2'); - - // Optional tracking - $t->setUserAgent( "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)"); - $t->setBrowserLanguage('fr'); - $t->setLocalTime( '12:34:06' ); - $t->setResolution( 1024, 768 ); - $t->setBrowserHasCookies(true); - $t->setPlugins($flash = true, $java = true, $director = false); - } - return $t; - } - - /** - * Creates a website, then sets its creation date to a day earlier than specified dateTime - * Useful to create a website now, but force data to be archived back in the past. - * - * @param string $dateTime eg '2010-01-01 12:34:56' - * @param int $ecommerce - * @param string $siteName - * - * @return int idSite of website created - */ - public static function createWebsite( $dateTime, $ecommerce = 0, $siteName = 'Piwik test', $siteUrl = false, $siteSearch = 1, $searchKeywordParameters = null, $searchCategoryParameters = null ) - { - $idSite = Piwik_SitesManager_API::getInstance()->addSite( - $siteName, - $siteUrl === false ? "http://piwik.net/" : $siteUrl, - $ecommerce, - $siteSearch , $searchKeywordParameters, $searchCategoryParameters, - $ips = null, - $excludedQueryParameters = null, - $timezone = null, - $currency = null - ); - - // Manually set the website creation date to a day earlier than the earliest day we record stats for - Zend_Registry::get('db')->update(Piwik_Common::prefixTable("site"), - array('ts_created' => Piwik_Date::factory($dateTime)->subDay(1)->getDatetime()), - "idsite = $idSite" - ); - - // Clear the memory Website cache - Piwik_Site::clearCache(); - - return $idSite; - } - - /** - * Create one MAIL and two MOBILE scheduled reports - * - * Reports sent by mail can contain PNG graphs when the user specifies it. - * Depending on the system under test, generated images differ slightly. - * Because of this discrepancy, PNG graphs are only tested if the system under test - * has the characteristics described in 'canImagesBeIncludedInScheduledReports' - * - * @see canImagesBeIncludedInScheduledReports - * @param int $idSite id of website created - */ - protected static function setUpScheduledReports($idSite) - { - // fake access is needed so API methods can call Piwik::getCurrentUserLogin(), e.g: 'PDFReports.addReport' - $pseudoMockAccess = new FakeAccess; - FakeAccess::$superUser = true; - Zend_Registry::set('access', $pseudoMockAccess); - - // retrieve available reports - $availableReportMetadata = Piwik_PDFReports_API::getReportMetadata($idSite, Piwik_PDFReports::EMAIL_TYPE); - - $availableReportIds = array(); - foreach($availableReportMetadata as $reportMetadata) - { - $availableReportIds[] = $reportMetadata['uniqueId']; - } - - //@review should we also test evolution graphs? - // set-up mail report - Piwik_PDFReports_API::getInstance()->addReport( - $idSite, - 'Mail Test report', - 'day', // overridden in getApiForTestingScheduledReports() - 0, - Piwik_PDFReports::EMAIL_TYPE, - Piwik_ReportRenderer::HTML_FORMAT, // overridden in getApiForTestingScheduledReports() - $availableReportIds, - array("displayFormat" => Piwik_PDFReports::DISPLAY_FORMAT_TABLES_ONLY) - ); - - // set-up sms report for one website - Piwik_PDFReports_API::getInstance()->addReport( - $idSite, - 'SMS Test report, one website', - 'day', // overridden in getApiForTestingScheduledReports() - 0, - Piwik_MobileMessaging::MOBILE_TYPE, - Piwik_MobileMessaging::SMS_FORMAT, - array("MultiSites_getOne"), - array("phoneNumbers"=>array()) - ); - - // set-up sms report for all websites - Piwik_PDFReports_API::getInstance()->addReport( - $idSite, - 'SMS Test report, all websites', - 'day', // overridden in getApiForTestingScheduledReports() - 0, - Piwik_MobileMessaging::MOBILE_TYPE, - Piwik_MobileMessaging::SMS_FORMAT, - array("MultiSites_getAll"), - array("phoneNumbers"=>array()) - ); - - if(self::canImagesBeIncludedInScheduledReports()) - { - // set-up mail report with images - Piwik_PDFReports_API::getInstance()->addReport( - $idSite, - 'Mail Test report', - 'day', // overridden in getApiForTestingScheduledReports() - 0, - Piwik_PDFReports::EMAIL_TYPE, - Piwik_ReportRenderer::HTML_FORMAT, // overridden in getApiForTestingScheduledReports() - $availableReportIds, - array("displayFormat" => Piwik_PDFReports::DISPLAY_FORMAT_TABLES_AND_GRAPHS) - ); - } - } - protected function alertWhenImagesExcludedFromTests() { - if(!self::canImagesBeIncludedInScheduledReports()) + if(!Test_Piwik_BaseFixture::canImagesBeIncludedInScheduledReports()) { $this->markTestSkipped( 'Do take note that scheduled reports are not being tested with images. ' . @@ -404,21 +283,6 @@ abstract class IntegrationTestCase extends PHPUnit_Framework_TestCase } /** - * Return true if system under test has the following characteristics : - * - php_uname() contains 'precise32' or 'ubuntu' - * - phpversion() contains '5.3.10' - * - 'GD Version' equals '2.0' - */ - private static function canImagesBeIncludedInScheduledReports() - { - $gdInfo = gd_info(); - return - (stristr(php_uname(), 'precise32') || stristr(php_uname(), 'ubuntu')) && - stristr(phpversion(), '5.3.10') && - $gdInfo['GD Version'] == '2.0'; - } - - /** * Return 4 Api Urls for testing scheduled reports : * - one in HTML format with all available reports * - one in PDF format with all available reports @@ -516,7 +380,7 @@ abstract class IntegrationTestCase extends PHPUnit_Framework_TestCase ) ); - if(self::canImagesBeIncludedInScheduledReports()) + if(Test_Piwik_BaseFixture::canImagesBeIncludedInScheduledReports()) { // HTML Scheduled Report with images array_push( @@ -542,71 +406,6 @@ abstract class IntegrationTestCase extends PHPUnit_Framework_TestCase return $apiCalls; } - /** - * Checks that the response is a GIF image as expected. - * Will fail the test if the response is not the expected GIF - * - * @param $response - */ - protected static function checkResponse($response) - { - $trans_gif_64 = "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; - $expectedResponse = base64_decode($trans_gif_64); - self::assertEquals($expectedResponse, $response, "Expected GIF beacon, got: <br/>\n" - . var_export($response, true) - . "\n If you are stuck, you can enable \$GLOBALS['PIWIK_TRACKER_DEBUG']=true; in piwik.php to get more debug info." -// .base64_encode($response) // uncomment to further debug when the GIF hides the error - ); - } - - /** - * Returns URL to Piwik root. - * - * @return string - */ - public static function getRootUrl() - { - $piwikUrl = Piwik_Url::getCurrentUrlWithoutFileName(); - - $pathBeforeRoot = 'tests'; - // Running from a plugin - if(strpos($piwikUrl, 'plugins/') !== false) - { - $pathBeforeRoot = 'plugins'; - } - - $testsInPath = strpos($piwikUrl, $pathBeforeRoot.'/'); - if($testsInPath !== false) { - $piwikUrl = substr($piwikUrl, 0, $testsInPath); - } - return $piwikUrl; - } - - /** - * Returns URL to the proxy script, used to ensure piwik.php - * uses the test environment, and allows variable overwriting - * - * @return string - */ - public static function getTrackerUrl() - { - return self::getRootUrl().'tests/PHPUnit/proxy/piwik.php'; - } - - /** - * Returns the super user token auth that can be used in tests. Can be used to - * do bulk tracking. - * - * @return string - */ - public static function getTokenAuth() - { - return Piwik_UsersManager_API::getInstance()->getTokenAuth( - Piwik_Config::getInstance()->superuser['login'], - Piwik_Config::getInstance()->superuser['password'] - ); - } - /** * Given a list of default parameters to set, returns the URLs of APIs to call * If any API was specified in setApiToCall() we ensure only these are tested. @@ -1321,58 +1120,4 @@ abstract class IntegrationTestCase extends PHPUnit_Framework_TestCase Piwik_TablePartitioning::$tablesAlreadyInstalled = Piwik::getTablesInstalled($forceReload = true); } - - public static $geoIpDbUrl = 'http://piwik-team.s3.amazonaws.com/GeoIP.dat.gz'; - public static $geoLiteCityDbUrl = 'http://piwik-team.s3.amazonaws.com/GeoLiteCity.dat.gz'; - - public static function downloadGeoIpDbs() - { - $geoIpOutputDir = PIWIK_INCLUDE_PATH.'/tests/lib/geoip-files'; - self::downloadAndUnzip(self::$geoIpDbUrl, $geoIpOutputDir, 'GeoIP.dat'); - self::downloadAndUnzip(self::$geoLiteCityDbUrl, $geoIpOutputDir, 'GeoIPCity.dat'); - } - - public static function downloadAndUnzip( $url, $outputDir, $filename ) - { - $bufferSize = 1024 * 1024; - - try - { - if (!is_dir($outputDir)) - { - mkdir($outputDir); - } - - $deflatedOut = $outputDir.'/'.$filename; - $outfileName = $deflatedOut.'.gz'; - - if (file_exists($deflatedOut)) - { - return; - } - - $dump = fopen($url, 'rb'); - $outfile = fopen($outfileName, 'wb'); - $bytesRead = 0; - while (!feof($dump)) - { - fwrite($outfile, fread($dump, $bufferSize), $bufferSize); - $bytesRead += $bufferSize; - } - fclose($dump); - fclose($outfile); - - // unzip the dump - exec("gunzip -c \"".$outfileName."\" > \"$deflatedOut\"", $output, $return); - if ($return !== 0) - { - throw new Exception("gunzip failed($return): ".implode("\n", $output)); - } - } - catch (Exception $ex) - { - self::markTestSkipped( - "Cannot download GeoIp DBs, skipping: ".$ex->getMessage()."\n".$ex->getTraceAsString()); - } - } } diff --git a/tests/PHPUnit/Plugins/PrivacyManagerTest.php b/tests/PHPUnit/Plugins/PrivacyManagerTest.php index 820dfeacf6..50aadf3f19 100755 --- a/tests/PHPUnit/Plugins/PrivacyManagerTest.php +++ b/tests/PHPUnit/Plugins/PrivacyManagerTest.php @@ -611,12 +611,12 @@ class PrivacyManagerTest extends IntegrationTestCase // - http://whatever.com/42/{$daysSinceLastVisit} $start = Piwik_Date::factory(self::$dateTime); - self::$idSite = self::createWebsite('2012-01-01', $ecommerce=1); + self::$idSite = Test_Piwik_BaseFixture::createWebsite('2012-01-01', $ecommerce=1); $idGoal = Piwik_Goals_API::getInstance()->addGoal(self::$idSite, 'match all', 'url', 'http', 'contains'); - $t = IntegrationTestCase::getTracker(self::$idSite, $start, $defaultInit = true); + $t = Test_Piwik_BaseFixture::getTracker(self::$idSite, $start, $defaultInit = true); $t->enableBulkTracking(); - $t->setTokenAuth(self::getTokenAuth()); + $t->setTokenAuth(Test_Piwik_BaseFixture::getTokenAuth()); for ($daysAgo = self::$daysAgoStart; $daysAgo >= 0; $daysAgo -= 5) // one visit every 5 days { @@ -638,7 +638,7 @@ class PrivacyManagerTest extends IntegrationTestCase $t->doTrackEcommerceOrder($orderId = '937nsjusu '.$dateTime, $grandTotal = 1111.11, $subTotal = 1000, $tax = 111, $shipping = 0.11, $discount = 666); } - self::checkResponse($t->doBulkTrack()); + Test_Piwik_BaseFixture::checkResponse($t->doBulkTrack()); } protected static function _addReportData() diff --git a/tests/PHPUnit/bootstrap.php b/tests/PHPUnit/bootstrap.php index ea4b862118..d7fce36cc5 100644 --- a/tests/PHPUnit/bootstrap.php +++ b/tests/PHPUnit/bootstrap.php @@ -37,6 +37,12 @@ require_once PIWIK_INCLUDE_PATH .'/tests/PHPUnit/MockEventDispatcher.php'; // required to build code coverage for uncovered files require_once PIWIK_INCLUDE_PATH .'/plugins/SecurityInfo/PhpSecInfo/PhpSecInfo.php'; +// require test fixtures +require_once PIWIK_INCLUDE_PATH.'/tests/PHPUnit/BaseFixture.php'; +foreach (glob(PIWIK_INCLUDE_PATH.'/tests/PHPUnit/Fixtures/*.php') as $file) +{ + require_once $file; +} // General requirement checks & help: a webserver must be running for tests to work! checkPiwikSetupForTests(); @@ -56,7 +62,7 @@ Try again and now the tests should run!"; } // Now testing if the webserver is running - $piwikServerUrl = IntegrationTestCase::getRootUrl(); + $piwikServerUrl = Test_Piwik_BaseFixture::getRootUrl(); try { $fetched = Piwik_Http::sendHttpRequest($piwikServerUrl, $timeout = 3); } catch(Exception $e) { |