diff options
Diffstat (limited to 'tests/PHPUnit/Core')
91 files changed, 0 insertions, 17172 deletions
diff --git a/tests/PHPUnit/Core/API/ApiRendererTest.php b/tests/PHPUnit/Core/API/ApiRendererTest.php deleted file mode 100644 index ebe1952a90..0000000000 --- a/tests/PHPUnit/Core/API/ApiRendererTest.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\API\ApiRenderer; - -/** - * @group Core - * @group Only2 - */ -class ApiRendererTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('API')); - } - - public function test_factory_shouldCreateAnInstance_IfValidFormatGiven() - { - $renderer = ApiRenderer::factory('php', array()); - $this->assertInstanceOf('\\Piwik\\Plugins\\API\\Renderer\\Php', $renderer); - - $renderer = ApiRenderer::factory('PHP', array()); - $this->assertInstanceOf('\\Piwik\\Plugins\\API\\Renderer\\Php', $renderer); - - $renderer = ApiRenderer::factory('pHp', array()); - $this->assertInstanceOf('\\Piwik\\Plugins\\API\\Renderer\\Php', $renderer); - - $renderer = ApiRenderer::factory('xmL', array()); - $this->assertInstanceOf('\\Piwik\\Plugins\\API\\Renderer\\Xml', $renderer); - - $renderer = ApiRenderer::factory('OriginAl', array()); - $this->assertInstanceOf('\\Piwik\\Plugins\\API\\Renderer\\Original', $renderer); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage General_ExceptionInvalidRendererFormat - */ - public function test_factory_shouldThrowAnException_IfInvalidFormatGiven() - { - ApiRenderer::factory('phpi', array()); - } -} diff --git a/tests/PHPUnit/Core/API/ResponseBuilderTest.php b/tests/PHPUnit/Core/API/ResponseBuilderTest.php deleted file mode 100644 index 9d6d0bc779..0000000000 --- a/tests/PHPUnit/Core/API/ResponseBuilderTest.php +++ /dev/null @@ -1,270 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\API\ResponseBuilder; -use Piwik\DataTable; - -/** - * @group Core - */ -class ResponseBuilderTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - \Piwik\Plugin\Manager::getInstance()->loadPlugins(array('API')); - } - - public function test_getResponseException_shouldFormatExceptionDependingOnFormatAndAddDebugHelp() - { - $builder = new ResponseBuilder('xml', array()); - $response = $builder->getResponseException(new Exception('My Message')); - - $this->assertEquals('<?xml version="1.0" encoding="utf-8" ?> -<result> - <error message="My Message - - --> To temporarily debug this error further, set const PIWIK_PRINT_ERROR_BACKTRACE=true; in index.php" /> -</result>', $response); - } - - public function test_getResponse_shouldTreatAsSuccessIfNoValue() - { - $builder = new ResponseBuilder('xml', array()); - $response = $builder->getResponse(null); - - $this->assertEquals('<?xml version="1.0" encoding="utf-8" ?> -<result> - <success message="ok" /> -</result>', $response); - } - - public function test_getResponse_shouldNotReturnAnythingIfContentWasOutput() - { - echo 5; - $builder = new ResponseBuilder('xml', array()); - $response = $builder->getResponse(null); - - $this->assertNull($response); - ob_clean(); - } - - public function test_getResponse_shouldHandleScalar() - { - $builder = new ResponseBuilder('xml', array()); - - $response = $builder->getResponse(true); - $this->assertEquals('<?xml version="1.0" encoding="utf-8" ?> -<result>1</result>', $response); - - $response = $builder->getResponse(5); - $this->assertEquals('<?xml version="1.0" encoding="utf-8" ?> -<result>5</result>', $response); - - $response = $builder->getResponse('string'); - $this->assertEquals('<?xml version="1.0" encoding="utf-8" ?> -<result>string</result>', $response); - } - - public function test_getResponse_shouldHandleDataTable() - { - $builder = new ResponseBuilder('xml', array()); - - $dataTable = new DataTable(); - $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10)); - - $response = $builder->getResponse($dataTable); - $this->assertEquals('<?xml version="1.0" encoding="utf-8" ?> -<result> - <row> - <nb_visits>5</nb_visits> - <nb_random>10</nb_random> - </row> -</result>', $response); - } - - public function test_getResponse_shouldHandleObject() - { - $object = new \stdClass(); - - $builder = new ResponseBuilder('xml', array()); - $response = $builder->getResponse($object); - $this->assertSame('<?xml version="1.0" encoding="utf-8" ?> -<result> - <error message="The API cannot handle this data structure." /> -</result>', $response); - - $builder = new ResponseBuilder('original', array()); - $response = $builder->getResponse($object); - $this->assertSame($object, $response); - } - - public function test_getResponse_shouldHandleResource() - { - $resource = curl_init(); - - $builder = new ResponseBuilder('xml', array()); - $response = $builder->getResponse($resource); - $this->assertSame('<?xml version="1.0" encoding="utf-8" ?> -<result> - <error message="The API cannot handle this data structure." /> -</result>', $response); - - $builder = new ResponseBuilder('original', array()); - $response = $builder->getResponse($resource); - $this->assertSame($resource, $response); - } - - public function test_getResponse_shouldHandleArray() - { - $builder = new ResponseBuilder('xml', array()); - $response = $builder->getResponse(array(1, 2, 3, 'string', 10)); - $this->assertSame('<?xml version="1.0" encoding="utf-8" ?> -<result> - <row>1</row> - <row>2</row> - <row>3</row> - <row>string</row> - <row>10</row> -</result>', $response); - } - - public function test_getResponse_shouldHandleAssociativeArray() - { - $builder = new ResponseBuilder('xml', array()); - $response = $builder->getResponse(array('test' => 'two', 'test2' => 'three')); - $this->assertSame('<?xml version="1.0" encoding="utf-8" ?> -<result> - <row> - <test>two</test> - <test2>three</test2> - </row> -</result>', $response); - } - - public function test_getResponse_shouldHandleIndexedAssociativeArray() - { - $builder = new ResponseBuilder('xml', array()); - $response = $builder->getResponse(array(array('test' => 'two', 'test2' => 'three'))); - $this->assertSame('<?xml version="1.0" encoding="utf-8" ?> -<result> - <row> - <test>two</test> - <test2>three</test2> - </row> -</result>', $response); - } - - public function test_getResponse_shouldBeAbleToApplyFilterOnIndexedAssociativeArray() - { - $input = array(); - for ($i = 0; $i < 10; $i++) { - $input[] = array('test' => 'two' . $i, 'test2' => 'three'); - } - - $builder = new ResponseBuilder('php', array('serialize' => 0)); - $response = $builder->getResponse($input); - - $this->assertEquals($input, $response); - $this->assertCount(10, $response); - - $builder = new ResponseBuilder('php', array('serialize' => 0, 'showColumns' => 'test')); - $response = $builder->getResponse($input); - - $this->assertEquals(array('test' => 'two0'), array_shift($response)); - } - - public function test_getResponse_shouldApplyFilterLimitOnIndexedArray() - { - $input = range(0, 100); - - $builder = new ResponseBuilder('php', array('serialize' => 0, 'filter_limit' => 15)); - $response = $builder->getResponse($input); - - $this->assertEquals(range(0, 14), $response); - } - - public function test_getResponse_shouldReturnEmptyArrayOnIndexedArray_IfOffsetIsTooHigh() - { - $input = range(0, 100); - - $builder = new ResponseBuilder('php', array('serialize' => 0, 'filter_limit' => 15, 'filter_offset' => 200)); - $response = $builder->getResponse($input); - - $this->assertEquals(array(), $response); - } - - public function test_getResponse_shouldReturnAllOnIndexedArray_IfLimitIsTooHigh() - { - $input = range(0, 100); - - $builder = new ResponseBuilder('php', array('serialize' => 0, 'filter_limit' => 200)); - $response = $builder->getResponse($input); - - $this->assertEquals($input, $response); - } - - public function test_getResponse_shouldNotApplyFilterLimitOnIndexedArrayIfParamNotSet() - { - $input = range(0, 100); - - $builder = new ResponseBuilder('php', array('serialize' => 0)); - $response = $builder->getResponse($input); - - $this->assertEquals($input, $response); - } - - public function test_getResponse_shouldApplyFilterOffsetOnIndexedArray_IfFilterLimitIsGiven() - { - $input = range(0, 100); - - $builder = new ResponseBuilder('php', array('serialize' => 0, 'filter_limit' => 15, 'filter_offset' => 30)); - $response = $builder->getResponse($input); - - $this->assertEquals(range(30, 44), $response); - } - - public function test_getResponse_shouldNotApplyFilterOffsetOnIndexedArray_IfNoFilterLimitIsSetButOffset() - { - $input = range(0, 100); - - $builder = new ResponseBuilder('php', array('serialize' => 0, 'filter_offset' => 30)); - $response = $builder->getResponse($input); - - $this->assertEquals($input, $response); - } - - public function test_getResponse_shouldReturnEmptyArrayOnIndexedArray_IfFilterLimitIsZero() - { - $input = range(0, 100); - - $builder = new ResponseBuilder('php', array('serialize' => 0, 'filter_limit' => 0, 'filter_offset' => 30)); - $response = $builder->getResponse($input); - - $this->assertEquals(array(), $response); - } - - public function test_getResponse_shouldIgnoreFilterOffsetOnIndexedArray_IfFilterLimitIsMinusOne() - { - $input = range(0, 100); - - $builder = new ResponseBuilder('php', array('serialize' => 0, 'filter_limit' => -1, 'filter_offset' => 30)); - $response = $builder->getResponse($input); - - $this->assertEquals($input, $response); - } - - public function test_getResponse_shouldReturnAllOnIndexedArray_IfFilterLimitIsMinusOne() - { - $input = range(0, 100); - - $builder = new ResponseBuilder('php', array('serialize' => 0, 'filter_limit' => -1)); - $response = $builder->getResponse($input); - - $this->assertEquals($input, $response); - } -} diff --git a/tests/PHPUnit/Core/AssetManager/PluginManagerMock.php b/tests/PHPUnit/Core/AssetManager/PluginManagerMock.php deleted file mode 100644 index 2dd91867f2..0000000000 --- a/tests/PHPUnit/Core/AssetManager/PluginManagerMock.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\Plugin\Manager; -use Piwik\Plugin; -use Piwik\Theme; - -class PluginManagerMock extends Manager -{ - - /** - * @var Plugin[] - */ - private $plugins = array(); - - /** - * @var Theme - */ - private $loadedTheme; - - /** - * @param Plugin[] $plugins - */ - public function setPlugins($plugins) - { - $this->plugins = $plugins; - } - - public function getLoadedPlugin($name) - { - foreach($this->plugins as $plugin) - if($plugin->getPluginName() == $name) - return $plugin; - - return null; - } - - public function getPluginsLoadedAndActivated() - { - return $this->getLoadedPlugins(); - } - - public function getLoadedPluginsName() - { - $pluginNames = array(); - - foreach($this->plugins as $plugin) - $pluginNames[] = $plugin->getPluginName(); - - return $pluginNames; - } - - public function getLoadedPlugins() - { - return $this->plugins; - } - - public function getTheme($themeName) - { - return $this->loadedTheme; - } - - /** - * @param Theme $loadedTheme - */ - public function setLoadedTheme($loadedTheme) - { - $this->loadedTheme = $loadedTheme; - } -} diff --git a/tests/PHPUnit/Core/AssetManager/PluginMock.php b/tests/PHPUnit/Core/AssetManager/PluginMock.php deleted file mode 100644 index 6b6e8919ab..0000000000 --- a/tests/PHPUnit/Core/AssetManager/PluginMock.php +++ /dev/null @@ -1,132 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\Plugin; - -class PluginMock extends Plugin -{ - /** - * @var string[] - */ - private $jsFiles = array(); - - /** - * @var string[] - */ - private $stylesheetFiles = array(); - - /** - * @var string - */ - private $jsCustomization = ''; - - /** - * @var string - */ - private $cssCustomization = ''; - - /** - * @var boolean - */ - private $isTheme = false; - - /** - * @param string $name - */ - function __construct($name) - { - $this->pluginName = $name; - } - - public function getListHooksRegistered() - { - return array( - 'AssetManager.getJavaScriptFiles' => 'getJsFiles', - 'AssetManager.getStylesheetFiles' => 'getStylesheetFiles', - 'AssetManager.filterMergedJavaScripts' => 'filterMergedJavaScriptsHook', - 'AssetManager.filterMergedStylesheets' => 'filterMergedStylesheetsHook', - ); - } - - /** - * @param string[] $jsFiles - */ - public function getJsFiles(&$jsFiles) - { - $jsFiles = array_merge($jsFiles, $this->jsFiles); - } - - /** - * @param string[] $stylesheetFiles - */ - public function getStylesheetFiles(&$stylesheetFiles) - { - $stylesheetFiles = array_merge($stylesheetFiles, $this->stylesheetFiles); - } - - /** - * @param string $mergedContent - */ - public function filterMergedJavaScriptsHook(&$mergedContent) - { - $mergedContent .= $this->jsCustomization; - } - - /** - * @param string $mergedContent - */ - public function filterMergedStylesheetsHook(&$mergedContent) - { - $mergedContent .= $this->cssCustomization; - } - - /** - * @param string $cssCustomization - */ - public function setCssCustomization($cssCustomization) - { - $this->cssCustomization = $cssCustomization; - } - - /** - * @param string $jsCustomization - */ - public function setJsCustomization($jsCustomization) - { - $this->jsCustomization = $jsCustomization; - } - - /** - * @param string[] $jsFiles - */ - public function setJsFiles($jsFiles) - { - $this->jsFiles = $jsFiles; - } - - /** - * @param string[] $stylesheetFiles - */ - public function setStylesheetFiles($stylesheetFiles) - { - $this->stylesheetFiles = $stylesheetFiles; - } - - /** - * @param boolean $isTheme - */ - public function setIsTheme($isTheme) - { - $this->isTheme = $isTheme; - } - - public function isTheme() - { - return $this->isTheme; - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/ThemeMock.php b/tests/PHPUnit/Core/AssetManager/ThemeMock.php deleted file mode 100644 index 213a14d737..0000000000 --- a/tests/PHPUnit/Core/AssetManager/ThemeMock.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\Plugin; -use Piwik\Theme; - -class ThemeMock extends Theme -{ - - /** - * @var string[] - */ - private $jsFiles = array(); - - /** - * @var string - */ - private $stylesheet; - - /** - * @var Plugin - */ - private $plugin; - - /** - * @param Plugin $plugin - */ - function __construct($plugin) - { - $this->plugin = $plugin; - } - - public function getStylesheet() - { - return $this->stylesheet; - } - - public function getJavaScriptFiles() - { - return $this->jsFiles; - } - - /** - * @param string[] $jsFiles - */ - public function setJsFiles($jsFiles) - { - $this->jsFiles = $jsFiles; - } - - /** - * @param string $stylesheet - */ - public function setStylesheet($stylesheet) - { - $this->stylesheet = $stylesheet; - } - - /** - * @return Plugin - */ - public function getPlugin() - { - return $this->plugin; - } - - public function getThemeName() - { - return $this->plugin->getPluginName(); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/UIAssetCacheBusterMock.php b/tests/PHPUnit/Core/AssetManager/UIAssetCacheBusterMock.php deleted file mode 100644 index c6d2205aae..0000000000 --- a/tests/PHPUnit/Core/AssetManager/UIAssetCacheBusterMock.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\AssetManager\UIAssetCacheBuster; - -class UIAssetCacheBusterMock extends UIAssetCacheBuster -{ - /** - * @var string - */ - private $piwikVersionBasedCacheBuster; - - /** - * @var string - */ - private $md5BasedCacheBuster; - - public function piwikVersionBasedCacheBuster($pluginNames = false) - { - return $this->piwikVersionBasedCacheBuster; - } - - public function md5BasedCacheBuster($content) - { - return $this->md5BasedCacheBuster; - } - - /** - * @param string $md5BasedCacheBuster - */ - public function setMd5BasedCacheBuster($md5BasedCacheBuster) - { - $this->md5BasedCacheBuster = $md5BasedCacheBuster; - } - - /** - * @param string $piwikVersionBasedCacheBuster - */ - public function setPiwikVersionBasedCacheBuster($piwikVersionBasedCacheBuster) - { - $this->piwikVersionBasedCacheBuster = $piwikVersionBasedCacheBuster; - } -} diff --git a/tests/PHPUnit/Core/AssetManager/UIAssetCacheBusterTest.php b/tests/PHPUnit/Core/AssetManager/UIAssetCacheBusterTest.php deleted file mode 100644 index 85c4b613b3..0000000000 --- a/tests/PHPUnit/Core/AssetManager/UIAssetCacheBusterTest.php +++ /dev/null @@ -1,31 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\AssetManager\UIAssetCacheBuster; - -class UIAssetCacheBusterTest extends PHPUnit_Framework_TestCase -{ - - /** - * @var UIAssetCacheBuster - */ - private $cacheBuster; - - public function setUp() - { - $this->cacheBuster = UIAssetCacheBuster::getInstance(); - } - - /** - * @group Core - */ - public function test_md5BasedCacheBuster() - { - $this->assertEquals('098f6bcd4621d373cade4e832627b4f6', $this->cacheBuster->md5BasedCacheBuster('test')); - } -} diff --git a/tests/PHPUnit/Core/AssetManager/UIAssetCatalogSorterTest.php b/tests/PHPUnit/Core/AssetManager/UIAssetCatalogSorterTest.php deleted file mode 100644 index 820d8161bf..0000000000 --- a/tests/PHPUnit/Core/AssetManager/UIAssetCatalogSorterTest.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\AssetManager\UIAsset\OnDiskUIAsset; -use Piwik\AssetManager\UIAssetCatalog; -use Piwik\AssetManager\UIAssetCatalogSorter; - -class UIAssetCatalogSorterTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testPrioritySort() - { - $baseDirectory = '/var/www/piwik/'; - - $priorityPatterns = array( - 'libs/base.css', - 'libs/', - 'plugins/', - ); - - $catalogSorter = new UIAssetCatalogSorter($priorityPatterns); - - $unsortedCatalog = new UIAssetCatalog($catalogSorter); - $unsortedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'new_dir/new_file')); - $unsortedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'plugins/xyz')); - $unsortedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'plugins/abc')); - $unsortedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'libs/xyz')); - $unsortedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'libs/base.css')); - $unsortedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'libs/abc')); - $unsortedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'plugins/xyz')); - $unsortedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'libs/base.css')); - $unsortedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'libs/xyz')); - - $expectedCatalog = new UIAssetCatalog($catalogSorter); - $expectedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'libs/base.css')); - $expectedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'libs/xyz')); - $expectedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'libs/abc')); - $expectedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'plugins/xyz')); - $expectedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'plugins/abc')); - $expectedCatalog->addUIAsset(new OnDiskUIAsset($baseDirectory, 'new_dir/new_file')); - - $sortedCatalog = $unsortedCatalog->getSortedCatalog(); - - $this->assertEquals($expectedCatalog, $sortedCatalog); - } -} diff --git a/tests/PHPUnit/Core/AssetManager/UIAssetMinifierTest.php b/tests/PHPUnit/Core/AssetManager/UIAssetMinifierTest.php deleted file mode 100644 index df62e5c86b..0000000000 --- a/tests/PHPUnit/Core/AssetManager/UIAssetMinifierTest.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\AssetManager\UIAsset\OnDiskUIAsset; -use Piwik\AssetManager\UIAssetMinifier; - -class UIAssetMinifierTest extends PHPUnit_Framework_TestCase -{ - - /** - * @var UIAssetMinifier - */ - private $assetMinifier; - - public function setUp() - { - $this->assetMinifier = UIAssetMinifier::getInstance(); - } - - public function provider_isMinifiedJs() - { - return array( - array('libs/jquery/jquery.js', true), - array('libs/jquery/jquery-ui.js', true), - array('libs/jquery/jquery.browser.js', true), - array('libs/jqplot/jqplot-custom.min.js', true), - array('plugins/TreemapVisualization/libs/Jit/jit-2.0.1-yc.js', true), - array('plugins/TreemapVisualization/javascripts/treemapViz.js', false), - array('plugins/UserCountryMap/javascripts/vendor/raphael.min.js', true), - array('plugins/UserCountryMap/javascripts/vendor/jquery.qtip.min.js', true), - array('plugins/UserCountryMap/javascripts/vendor/kartograph.min.js', true), - array('plugins/UserCountryMap/javascripts/vendor/jquery.qtip.min.js', true), - ); - } - - /** - * @group Core - * @dataProvider provider_isMinifiedJs - */ - public function test_isMinifiedJs($scriptFileName, $isMinified) - { - $scriptFile = new OnDiskUIAsset(PIWIK_USER_PATH, $scriptFileName); - - $this->assertEquals( - $isMinified, - $this->assetMinifier->isMinifiedJs($scriptFile->getContent()) - ); - } -} diff --git a/tests/PHPUnit/Core/AssetManager/configs/merged-assets-disabled.ini.php b/tests/PHPUnit/Core/AssetManager/configs/merged-assets-disabled.ini.php deleted file mode 100644 index 610d020da1..0000000000 --- a/tests/PHPUnit/Core/AssetManager/configs/merged-assets-disabled.ini.php +++ /dev/null @@ -1,2 +0,0 @@ -[Development] -disable_merged_assets = 1 diff --git a/tests/PHPUnit/Core/AssetManager/configs/merged-assets-enabled.ini.php b/tests/PHPUnit/Core/AssetManager/configs/merged-assets-enabled.ini.php deleted file mode 100644 index 69a1facd8a..0000000000 --- a/tests/PHPUnit/Core/AssetManager/configs/merged-assets-enabled.ini.php +++ /dev/null @@ -1,2 +0,0 @@ -[Development] -disable_merged_assets = 0 diff --git a/tests/PHPUnit/Core/AssetManager/configs/plugins.ini.php b/tests/PHPUnit/Core/AssetManager/configs/plugins.ini.php deleted file mode 100644 index 72834098e0..0000000000 --- a/tests/PHPUnit/Core/AssetManager/configs/plugins.ini.php +++ /dev/null @@ -1,3 +0,0 @@ -[Plugins] -Plugins[] = MockCorePlugin -Plugins[] = CoreThemePlugin
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/scripts/ExpectedMergeResultCore.js b/tests/PHPUnit/Core/AssetManager/scripts/ExpectedMergeResultCore.js deleted file mode 100644 index 823fc76cdb..0000000000 --- a/tests/PHPUnit/Core/AssetManager/scripts/ExpectedMergeResultCore.js +++ /dev/null @@ -1,6 +0,0 @@ -/* Piwik Javascript - cb={{{CACHE-BUSTER-JS}}}*/ - -if(typeof SimpleObject!=='object'){SimpleObject=(function(){var privateVar;function privateMethod(param){privateVar=param;} -return{publicMethod:function(){privateMethod('val');}}}());} -var simpleArray=['el1','el2']; -//This is a simple comment// customization via event
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/scripts/ExpectedMergeResultNonCore.js b/tests/PHPUnit/Core/AssetManager/scripts/ExpectedMergeResultNonCore.js deleted file mode 100644 index f004dcc501..0000000000 --- a/tests/PHPUnit/Core/AssetManager/scripts/ExpectedMergeResultNonCore.js +++ /dev/null @@ -1,3 +0,0 @@ -/* Piwik Javascript - cb={{{CACHE-BUSTER-JS}}}*/ - -alert('test');
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/scripts/SimpleAlert.js b/tests/PHPUnit/Core/AssetManager/scripts/SimpleAlert.js deleted file mode 100644 index 003d113a36..0000000000 --- a/tests/PHPUnit/Core/AssetManager/scripts/SimpleAlert.js +++ /dev/null @@ -1 +0,0 @@ -alert('test');
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/scripts/SimpleArray.js b/tests/PHPUnit/Core/AssetManager/scripts/SimpleArray.js deleted file mode 100644 index 3176f85cff..0000000000 --- a/tests/PHPUnit/Core/AssetManager/scripts/SimpleArray.js +++ /dev/null @@ -1 +0,0 @@ -var simpleArray = ['el1', 'el2']; diff --git a/tests/PHPUnit/Core/AssetManager/scripts/SimpleComments.js b/tests/PHPUnit/Core/AssetManager/scripts/SimpleComments.js deleted file mode 100644 index 5a7103256a..0000000000 --- a/tests/PHPUnit/Core/AssetManager/scripts/SimpleComments.js +++ /dev/null @@ -1 +0,0 @@ -//This is a simple comment
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/scripts/SimpleObject.js b/tests/PHPUnit/Core/AssetManager/scripts/SimpleObject.js deleted file mode 100644 index aacdf5069c..0000000000 --- a/tests/PHPUnit/Core/AssetManager/scripts/SimpleObject.js +++ /dev/null @@ -1,18 +0,0 @@ -if (typeof SimpleObject !== 'object') { - - SimpleObject = (function () { - - var privateVar; - - function privateMethod(param) { - privateVar = param; - } - - return { - - publicMethod: function () { - privateMethod('val'); - } - } - }()); -} diff --git a/tests/PHPUnit/Core/AssetManager/stylesheets/CssWithURLs.css b/tests/PHPUnit/Core/AssetManager/stylesheets/CssWithURLs.css deleted file mode 100644 index 75c919da98..0000000000 --- a/tests/PHPUnit/Core/AssetManager/stylesheets/CssWithURLs.css +++ /dev/null @@ -1,12 +0,0 @@ -h1 { - color: orange; - text-align: center; - /* url relative to root: must not be rewritten*/ - background: url(tests/PHPUnit/Core/AssetManager/stylesheets/images/test-image.png); -} - -p { - font-size: 20px; - /* url relative to file: must be rewritten*/ - background: url(images/test-image.png); -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/stylesheets/ExpectedMergeResult.css b/tests/PHPUnit/Core/AssetManager/stylesheets/ExpectedMergeResult.css deleted file mode 100644 index 3b86a91e52..0000000000 --- a/tests/PHPUnit/Core/AssetManager/stylesheets/ExpectedMergeResult.css +++ /dev/null @@ -1,30 +0,0 @@ -/* compile_me_once={{{CACHE-BUSTER-JS}}} */ -/* Piwik CSS file is compiled with Less. You may be interested in writing a custom Theme for Piwik! */ -#page #header { - color: white; -} -#footer { - color: red; -} -.box { - color: #fe33ac; - border-color: #fdcdea; -} -.box div { - -webkit-box-shadow: 0 0 5px rgba(0,0,0,0.3); - -moz-box-shadow: 0 0 5px rgba(0,0,0,0.3); - box-shadow: 0 0 5px rgba(0,0,0,0.3); -} -h1 { - color: orange; - text-align: center; - background: url(tests/PHPUnit/Core/AssetManager/stylesheets/images/test-image.png); -} -p { - font-size: 20px; - background: url(tests/PHPUnit/Core/AssetManager/stylesheets/images/test-image.png); -} -body { - background-color: #b0c4de; -} -/* customization via event */
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/stylesheets/ImportedLess.less b/tests/PHPUnit/Core/AssetManager/stylesheets/ImportedLess.less deleted file mode 100644 index db566317b6..0000000000 --- a/tests/PHPUnit/Core/AssetManager/stylesheets/ImportedLess.less +++ /dev/null @@ -1,12 +0,0 @@ -@var: red; - -#page { - @var: white; - #header { - color: @var; - } -} - -#footer { - color: @var; -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/stylesheets/SimpleBody.css b/tests/PHPUnit/Core/AssetManager/stylesheets/SimpleBody.css deleted file mode 100644 index 6e0e55777a..0000000000 --- a/tests/PHPUnit/Core/AssetManager/stylesheets/SimpleBody.css +++ /dev/null @@ -1,3 +0,0 @@ -body { - background-color:#b0c4de; -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/AssetManager/stylesheets/SimpleLess.less b/tests/PHPUnit/Core/AssetManager/stylesheets/SimpleLess.less deleted file mode 100644 index fd7b33af31..0000000000 --- a/tests/PHPUnit/Core/AssetManager/stylesheets/SimpleLess.less +++ /dev/null @@ -1,17 +0,0 @@ -@import "ImportedLess"; - -@base: #f938ab; - -.box-shadow(@style, @c) when (iscolor(@c)) { - -webkit-box-shadow: @style @c; - -moz-box-shadow: @style @c; - box-shadow: @style @c; -} -.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) { - .box-shadow(@style, rgba(0, 0, 0, @alpha)); -} -.box { - color: saturate(@base, 5%); - border-color: lighten(@base, 30%); - div { .box-shadow(0 0 5px, 30%) } -} diff --git a/tests/PHPUnit/Core/AssetManager/stylesheets/images/test-image.png b/tests/PHPUnit/Core/AssetManager/stylesheets/images/test-image.png Binary files differdeleted file mode 100644 index da6e1bbe89..0000000000 --- a/tests/PHPUnit/Core/AssetManager/stylesheets/images/test-image.png +++ /dev/null diff --git a/tests/PHPUnit/Core/AssetManagerTest.php b/tests/PHPUnit/Core/AssetManagerTest.php deleted file mode 100644 index 85fc6d9764..0000000000 --- a/tests/PHPUnit/Core/AssetManagerTest.php +++ /dev/null @@ -1,721 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\AssetManager\UIAsset\OnDiskUIAsset; -use Piwik\AssetManager\UIAsset; -use Piwik\AssetManager; -use Piwik\AssetManager\UIAssetFetcher\StaticUIAssetFetcher; -use Piwik\Config; -use Piwik\Plugin; -use Piwik\Plugin\Manager; -use Piwik\EventDispatcher; - -require_once PIWIK_INCLUDE_PATH . "/tests/PHPUnit/Core/AssetManager/UIAssetCacheBusterMock.php"; -require_once PIWIK_INCLUDE_PATH . "/tests/PHPUnit/Core/AssetManager/PluginManagerMock.php"; -require_once PIWIK_INCLUDE_PATH . "/tests/PHPUnit/Core/AssetManager/PluginMock.php"; -require_once PIWIK_INCLUDE_PATH . "/tests/PHPUnit/Core/AssetManager/ThemeMock.php"; - -/** - * @group AssetManagerTest - */ -class AssetManagerTest extends PHPUnit_Framework_TestCase -{ - // todo Theme->rewriteAssetPathIfOverridesFound is not tested - - const ASSET_MANAGER_TEST_DIR = 'tests/PHPUnit/Core/AssetManager/'; - - const FIRST_CACHE_BUSTER_JS = 'first-cache-buster-js'; - const SECOND_CACHE_BUSTER_JS = 'second-cache-buster-js'; - const FIRST_CACHE_BUSTER_SS = 'first-cache-buster-stylesheet'; - const SECOND_CACHE_BUSTER_SS = 'second-cache-buster-stylesheet'; - - const CORE_PLUGIN_NAME = 'MockCorePlugin'; - const CORE_PLUGIN_WITHOUT_ASSETS_NAME = 'MockCoreWithoutAssetPlugin'; - const NON_CORE_PLUGIN_NAME = 'MockNonCorePlugin'; - const CORE_THEME_PLUGIN_NAME = 'CoreThemePlugin'; - const NON_CORE_THEME_PLUGIN_NAME = 'NonCoreThemePlugin'; - - /** - * @var AssetManager - */ - private $assetManager; - - /** - * @var UIAsset - */ - private $mergedAsset; - - /** - * @var UIAssetCacheBusterMock - */ - private $cacheBuster; - - /** - * @var PluginManagerMock - */ - private $pluginManager; - - public function setUp() - { - $this->activateMergedAssets(); - - $this->setUpCacheBuster(); - - $this->setUpAssetManager(); - - $this->setUpPluginManager(); - - $this->setUpTheme(); - - $this->setUpPlugins(); - } - - public function tearDown() - { - $this->assetManager->removeMergedAssets(); - Manager::unsetInstance(); - } - - private function activateMergedAssets() - { - $this->setUpConfig('merged-assets-enabled.ini.php'); - } - - private function disableMergedAssets() - { - $this->setUpConfig('merged-assets-disabled.ini.php'); - } - - /** - * @param string $filename - */ - private function setUpConfig($filename) - { - $userFile = PIWIK_INCLUDE_PATH . '/' . self::ASSET_MANAGER_TEST_DIR . 'configs/' . $filename; - $globalFile = PIWIK_INCLUDE_PATH . '/' . self::ASSET_MANAGER_TEST_DIR . 'configs/plugins.ini.php'; - - $config = Config::getInstance(); - $config->setTestEnvironment($userFile, $globalFile); - $config->init(); - } - - private function setUpCacheBuster() - { - $this->cacheBuster = UIAssetCacheBusterMock::getInstance(); - } - - private function setUpAssetManager() - { - $this->assetManager = AssetManager::getInstance(); - - $this->assetManager->removeMergedAssets(); - - $this->assetManager->setCacheBuster($this->cacheBuster); - } - - private function setUpPluginManager() - { - $this->pluginManager = PluginManagerMock::getInstance(); - Manager::setSingletonInstance($this->pluginManager); - - EventDispatcher::unsetInstance(); // EventDispatcher stores a reference to Plugin Manager - } - - private function setUpPlugins() - { - $this->pluginManager->setPlugins( - array( - $this->getCoreTheme()->getPlugin(), - $this->getNonCoreTheme()->getPlugin(), - $this->getCorePlugin(), - $this->getCorePluginWithoutUIAssets(), - $this->getNonCorePlugin() - ) - ); - - $this->pluginManager->setLoadedTheme($this->getNonCoreTheme()); - } - - private function setUpCorePluginOnly() - { - $this->pluginManager->setPlugins( - array( - $this->getCorePlugin(), - ) - ); - } - - /** - * @return Plugin - */ - private function getCorePlugin() - { - $corePlugin = new PluginMock(self::CORE_PLUGIN_NAME); - - $corePlugin->setJsFiles( - array( - self::ASSET_MANAGER_TEST_DIR . 'scripts/SimpleObject.js', - self::ASSET_MANAGER_TEST_DIR . 'scripts/SimpleArray.js', - ) - ); - - $corePlugin->setStylesheetFiles($this->getCorePluginStylesheetFiles()); - $corePlugin->setJsCustomization('// customization via event'); - $corePlugin->setCssCustomization('/* customization via event */'); - - return $corePlugin; - } - - /** - * @return Plugin - */ - private function getCorePluginWithoutUIAssets() - { - return new PluginMock(self::CORE_PLUGIN_WITHOUT_ASSETS_NAME); - } - - /** - * @return Plugin - */ - private function getNonCorePlugin() - { - $nonCorePlugin = new PluginMock(self::NON_CORE_PLUGIN_NAME); - $nonCorePlugin->setJsFiles(array(self::ASSET_MANAGER_TEST_DIR . 'scripts/SimpleAlert.js')); - - return $nonCorePlugin; - } - - private function setUpTheme() - { - $this->assetManager->setTheme($this->getCoreTheme()); - } - - /** - * @return ThemeMock - */ - private function getCoreTheme() - { - return $this->createTheme(self::CORE_THEME_PLUGIN_NAME); - } - - /** - * @return ThemeMock - */ - private function getNonCoreTheme() - { - return $this->createTheme(self::NON_CORE_THEME_PLUGIN_NAME); - } - - /** - * @param string $themeName - * @return ThemeMock - */ - private function createTheme($themeName) - { - $coreThemePlugin = new PluginMock($themeName); - - $coreThemePlugin->setIsTheme(true); - - $coreTheme = new ThemeMock($coreThemePlugin); - - $coreTheme->setStylesheet($this->getCoreThemeStylesheet()); - $coreTheme->setJsFiles(array(self::ASSET_MANAGER_TEST_DIR . 'scripts/SimpleComments.js')); - - return $coreTheme; - } - - /** - * @return string[] - */ - public function getCorePluginStylesheetFiles() - { - return array( - self::ASSET_MANAGER_TEST_DIR . 'stylesheets/SimpleLess.less', - self::ASSET_MANAGER_TEST_DIR . 'stylesheets/CssWithURLs.css', - ); - } - - private function clearDateCache() - { - clearstatcache(); - } - - /** - * @return int - */ - private function waitAndGetModificationDate() - { - $this->clearDateCache(); - - sleep(1.5); - - $modificationDate = $this->mergedAsset->getModificationDate(); - - return $modificationDate; - } - - /** - * @param string $cacheBuster - */ - private function setJSCacheBuster($cacheBuster) - { - $this->cacheBuster->setPiwikVersionBasedCacheBuster($cacheBuster); - } - - /** - * @param string $cacheBuster - */ - private function setStylesheetCacheBuster($cacheBuster) - { - $this->cacheBuster->setMd5BasedCacheBuster($cacheBuster); - } - - private function triggerGetMergedCoreJavaScript() - { - $this->mergedAsset = $this->assetManager->getMergedCoreJavaScript(); - } - - private function triggerGetMergedNonCoreJavaScript() - { - $this->mergedAsset = $this->assetManager->getMergedNonCoreJavaScript(); - } - - private function triggerGetMergedStylesheet() - { - $this->mergedAsset = $this->assetManager->getMergedStylesheet(); - } - - private function validateMergedCoreJs() - { - $expectedContent = $this->getExpectedMergedCoreJs(); - - $this->validateExpectedContent($expectedContent); - } - - private function validateMergedNonCoreJs() - { - $expectedContent = $this->getExpectedMergedNonCoreJs(); - - $this->validateExpectedContent($expectedContent); - } - - private function validateMergedStylesheet() - { - $expectedContent = $this->getExpectedMergedStylesheet(); - - $this->validateExpectedContent($expectedContent); - } - - /** - * @param string $expectedContent - */ - private function validateExpectedContent($expectedContent) - { - $this->assertEquals($expectedContent, $this->mergedAsset->getContent()); - } - - /** - * @return string - */ - private function getExpectedMergedCoreJs() - { - return $this->getExpectedMergedJs('ExpectedMergeResultCore.js'); - } - - /** - * @return string - */ - private function getExpectedMergedNonCoreJs() - { - return $this->getExpectedMergedJs('ExpectedMergeResultNonCore.js'); - } - - /** - * @param string $filename - * @return string - */ - private function getExpectedMergedJs($filename) - { - $expectedMergeResult = new OnDiskUIAsset(PIWIK_USER_PATH, self::ASSET_MANAGER_TEST_DIR .'scripts/' . $filename); - - $expectedContent = $expectedMergeResult->getContent(); - - return $this->adjustExpectedJsContent($expectedContent); - } - - /** - * @param string $expectedJsContent - * @return string - */ - private function adjustExpectedJsContent($expectedJsContent) - { - $expectedJsContent = str_replace("\n", "\r\n", $expectedJsContent); - - $expectedJsContent = $this->specifyCacheBusterInExpectedContent($expectedJsContent, $this->cacheBuster->piwikVersionBasedCacheBuster()); - - return $expectedJsContent; - } - - /** - * @return string - */ - private function getExpectedMergedStylesheet() - { - $expectedMergeResult = new OnDiskUIAsset(PIWIK_USER_PATH, self::ASSET_MANAGER_TEST_DIR .'stylesheets/ExpectedMergeResult.css'); - - $expectedContent = $expectedMergeResult->getContent(); - - $expectedContent = $this->specifyCacheBusterInExpectedContent($expectedContent, $this->cacheBuster->md5BasedCacheBuster('')); - - return $expectedContent; - } - - /** - * @return string - */ - private function getCoreThemeStylesheet() - { - return self::ASSET_MANAGER_TEST_DIR . 'stylesheets/SimpleBody.css'; - } - - /** - * @param string $content - * @param string $cacheBuster - * @return string - */ - private function specifyCacheBusterInExpectedContent($content, $cacheBuster) - { - return str_replace('{{{CACHE-BUSTER-JS}}}', $cacheBuster, $content); - } - - /** - * @param int $previousDate - */ - private function validateDateDidNotChange($previousDate) - { - $this->clearDateCache(); - - $this->assertEquals($previousDate, $this->mergedAsset->getModificationDate()); - } - - /** - * @param int $previousDate - */ - private function validateDateIsMoreRecent($previousDate) - { - $this->clearDateCache(); - - $this->assertTrue($previousDate < $this->mergedAsset->getModificationDate()); - } - - /** - * @return string - */ - private function getJsTranslationScript() - { - return - '<script type="text/javascript">' . PHP_EOL . - 'var translations = [];' . PHP_EOL . - 'if (typeof(piwik_translations) == \'undefined\') { var piwik_translations = new Object; }for(var i in translations) { piwik_translations[i] = translations[i];} ' . PHP_EOL . - '</script>'; - } - - /** - * @return UIAsset[] - */ - private function generateAllMergedAssets() - { - $this->triggerGetMergedStylesheet(); - $stylesheetAsset = $this->mergedAsset; - - $this->triggerGetMergedCoreJavaScript(); - $coreJsAsset = $this->mergedAsset; - - $this->triggerGetMergedNonCoreJavaScript(); - $nonCoreJsAsset = $this->mergedAsset; - - $this->assertTrue($stylesheetAsset->exists()); - $this->assertTrue($coreJsAsset->exists()); - $this->assertTrue($nonCoreJsAsset->exists()); - - return array($stylesheetAsset, $coreJsAsset, $nonCoreJsAsset); - } - - /** - * @group Core - */ - public function test_getMergedCoreJavaScript_NotGenerated() - { - $this->setJSCacheBuster(self::FIRST_CACHE_BUSTER_JS); - - $this->triggerGetMergedCoreJavaScript(); - - $this->validateMergedCoreJs(); - } - - /** - * @group Core - */ - public function test_getMergedNonCoreJavaScript_NotGenerated() - { - $this->setJSCacheBuster(self::FIRST_CACHE_BUSTER_JS); - - $this->triggerGetMergedNonCoreJavaScript(); - - $this->validateMergedNonCoreJs(); - } - - /** - * @group Core - */ - public function test_getMergedNonCoreJavaScript_NotGenerated_NoNonCorePlugin() - { - $this->setUpCorePluginOnly(); - - $this->setJSCacheBuster(self::FIRST_CACHE_BUSTER_JS); - - $this->triggerGetMergedNonCoreJavaScript(); - - $expectedContent = $this->adjustExpectedJsContent('/* Piwik Javascript - cb={{{CACHE-BUSTER-JS}}}*/' . PHP_EOL); - - $this->validateExpectedContent($expectedContent); - } - - /** - * @group Core - */ - public function test_getMergedCoreJavaScript_AlreadyGenerated_MergedAssetsDisabled_UpToDate() - { - $this->disableMergedAssets(); - - $this->setJSCacheBuster(self::FIRST_CACHE_BUSTER_JS); - - $this->triggerGetMergedCoreJavaScript(); - - $modDateBeforeSecondRequest = $this->waitAndGetModificationDate(); - - $this->triggerGetMergedCoreJavaScript(); - - $this->validateDateDidNotChange($modDateBeforeSecondRequest); - } - - /** - * @group Core - */ - public function test_getMergedCoreJavaScript_AlreadyGenerated_MergedAssetsDeactivated_Stale() - { - $this->disableMergedAssets(); - - $this->setJSCacheBuster(self::FIRST_CACHE_BUSTER_JS); - - $this->triggerGetMergedCoreJavaScript(); - - $modDateBeforeSecondRequest = $this->waitAndGetModificationDate(); - - $this->setJSCacheBuster(self::SECOND_CACHE_BUSTER_JS); - - $this->triggerGetMergedCoreJavaScript(); - - $this->validateDateIsMoreRecent($modDateBeforeSecondRequest); - - $this->validateMergedCoreJs(); - } - - /** - * @group Core - */ - public function test_getMergedStylesheet_NotGenerated() - { - $this->setStylesheetCacheBuster(self::FIRST_CACHE_BUSTER_SS); - - $this->triggerGetMergedStylesheet(); - - $this->validateMergedStylesheet(); - } - - /** - * We always regenerate if cache buster changes - * @group Core - */ - public function test_getMergedStylesheet_Generated_MergedAssetsEnabled_Stale() - { - $this->activateMergedAssets(); - - $this->setStylesheetCacheBuster(self::FIRST_CACHE_BUSTER_SS); - - $this->triggerGetMergedStylesheet(); - - $modDateBeforeSecondRequest = $this->waitAndGetModificationDate(); - - $this->setStylesheetCacheBuster(self::SECOND_CACHE_BUSTER_SS); - - $this->triggerGetMergedStylesheet(); - - $this->validateDateIsMoreRecent($modDateBeforeSecondRequest); - - $this->validateMergedStylesheet(); - } - - /** - * We always regenerate if cache buster changes - * @group Core - */ - public function test_getMergedStylesheet_Generated_MergedAssetsDisabled_Stale() - { - $this->disableMergedAssets(); - - $this->setStylesheetCacheBuster(self::FIRST_CACHE_BUSTER_SS); - - $this->triggerGetMergedStylesheet(); - - $modDateBeforeSecondRequest = $this->waitAndGetModificationDate(); - - $this->setStylesheetCacheBuster(self::SECOND_CACHE_BUSTER_SS); - - $this->triggerGetMergedStylesheet(); - - $this->validateDateIsMoreRecent($modDateBeforeSecondRequest); - - $this->validateMergedStylesheet(); - } - - /** - * @group Core - */ - public function test_getMergedStylesheet_Generated_MergedAssetsDisabled_UpToDate() - { - $this->disableMergedAssets(); - - $this->setStylesheetCacheBuster(self::FIRST_CACHE_BUSTER_SS); - - $this->triggerGetMergedStylesheet(); - - $modDateBeforeSecondRequest = $this->waitAndGetModificationDate(); - - $this->triggerGetMergedStylesheet(); - - $this->validateDateDidNotChange($modDateBeforeSecondRequest); - } - - /** - * @group Core - */ - public function test_getCssInclusionDirective() - { - $expectedCssInclusionDirective = '<link rel="stylesheet" type="text/css" href="index.php?module=Proxy&action=getCss" />' . PHP_EOL; - - $this->assertEquals($expectedCssInclusionDirective, $this->assetManager->getCssInclusionDirective()); - } - - /** - * @group Core - */ - public function test_getJsInclusionDirective_MergedAssetsDisabled() - { - $this->disableMergedAssets(); - - $expectedJsInclusionDirective = - $this->getJsTranslationScript() . - '<script type="text/javascript" src="tests/PHPUnit/Core/AssetManager/scripts/SimpleObject.js"></script>' . PHP_EOL . - '<script type="text/javascript" src="tests/PHPUnit/Core/AssetManager/scripts/SimpleArray.js"></script>' . PHP_EOL . - '<script type="text/javascript" src="tests/PHPUnit/Core/AssetManager/scripts/SimpleComments.js"></script>' . PHP_EOL . - '<script type="text/javascript" src="tests/PHPUnit/Core/AssetManager/scripts/SimpleAlert.js"></script>' . PHP_EOL; - - $this->assertEquals($expectedJsInclusionDirective, $this->assetManager->getJsInclusionDirective()); - } - - /** - * @group Core - */ - public function test_getJsInclusionDirective_MergedAssetsEnabled() - { - $expectedJsInclusionDirective = - $this->getJsTranslationScript() . - '<script type="text/javascript" src="index.php?module=Proxy&action=getCoreJs"></script>' . PHP_EOL . - '<script type="text/javascript" src="index.php?module=Proxy&action=getNonCoreJs"></script>' . PHP_EOL; - - $this->assertEquals($expectedJsInclusionDirective, $this->assetManager->getJsInclusionDirective()); - } - - /** - * @group Core - */ - public function test_getCompiledBaseCss() - { - $this->setStylesheetCacheBuster(self::FIRST_CACHE_BUSTER_SS); - - $staticStylesheetList = array_merge($this->getCorePluginStylesheetFiles(), array($this->getCoreThemeStylesheet())); - - $minimalAssetFetcher = new StaticUIAssetFetcher( - array_reverse($staticStylesheetList), - $staticStylesheetList, - $this->getCoreTheme() - ); - - $this->assetManager->setMinimalStylesheetFetcher($minimalAssetFetcher); - - $this->mergedAsset = $this->assetManager->getCompiledBaseCss(); - - $this->validateMergedStylesheet(); - } - - /** - * @group Core - */ - public function test_removeMergedAssets() - { - list($stylesheetAsset, $coreJsAsset, $nonCoreJsAsset) = $this->generateAllMergedAssets(); - - $this->assetManager->removeMergedAssets(); - - $this->assertFalse($stylesheetAsset->exists()); - $this->assertFalse($coreJsAsset->exists()); - $this->assertFalse($nonCoreJsAsset->exists()); - } - - /** - * @group Core - */ - public function test_removeMergedAssets_PluginNameSpecified_PluginWithoutAssets() - { - list($stylesheetAsset, $coreJsAsset, $nonCoreJsAsset) = $this->generateAllMergedAssets(); - - $this->assetManager->removeMergedAssets(self::CORE_PLUGIN_WITHOUT_ASSETS_NAME); - - $this->assertFalse($stylesheetAsset->exists()); - $this->assertTrue($coreJsAsset->exists()); - $this->assertTrue($nonCoreJsAsset->exists()); - } - - /** - * @group Core - */ - public function test_removeMergedAssets_PluginNameSpecified_CorePlugin() - { - list($stylesheetAsset, $coreJsAsset, $nonCoreJsAsset) = $this->generateAllMergedAssets(); - - $this->assetManager->removeMergedAssets(self::CORE_PLUGIN_NAME); - - $this->assertFalse($stylesheetAsset->exists()); - $this->assertFalse($coreJsAsset->exists()); - $this->assertTrue($nonCoreJsAsset->exists()); - } - - /** - * @group Core - */ - public function test_removeMergedAssets_PluginNameSpecified_NonCoreThemeWithAssets() - { - list($stylesheetAsset, $coreJsAsset, $nonCoreJsAsset) = $this->generateAllMergedAssets(); - - $this->assetManager->removeMergedAssets(self::NON_CORE_THEME_PLUGIN_NAME); - - $this->assertFalse($stylesheetAsset->exists()); - $this->assertTrue($coreJsAsset->exists()); - $this->assertFalse($nonCoreJsAsset->exists()); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/CliMulti/OutputTest.php b/tests/PHPUnit/Core/CliMulti/OutputTest.php deleted file mode 100644 index 355fe2c4c7..0000000000 --- a/tests/PHPUnit/Core/CliMulti/OutputTest.php +++ /dev/null @@ -1,140 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\CliMulti\Output; - -/** - * Class OutputTest - * @group Core - */ -class OutputTest extends PHPUnit_Framework_TestCase -{ - - /** - * @var Output - */ - private $output; - - public function setUp() - { - \Piwik\Url::setHost(false); - $this->output = new Output('myid'); - } - - public function tearDown() - { - $this->output->destroy(); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage The given output id has an invalid format - */ - public function test_construct_shouldFail_IfInvalidOutputIdGiven() - { - new Output('../../'); - } - - public function test_exists_ShouldReturnsFalse_IfNothingWrittenYet() - { - $this->assertFalse($this->output->exists()); - } - - public function test_getPathToFile_shouldReturnFullPath() - { - $expectedEnd = '/tmp/climulti/myid.output'; - - $this->assertStringEndsWith($expectedEnd, $this->output->getPathToFile()); - $this->assertGreaterThan(strlen($expectedEnd), strlen($this->output->getPathToFile())); - } - - public function test_exists_ShouldReturnTrue_IfSomethingIsWritten() - { - $this->output->write('test'); - - $this->assertTrue($this->output->exists()); - - $this->output->destroy(); - - $this->assertFalse($this->output->exists()); - } - - public function test_get_shouldReturnNull_IfNothingWritten() - { - $this->assertFalse($this->output->get()); - } - - public function test_get_write_shouldReturnTheActualOutput_IfExists() - { - $anyContent = 'My Actual Content'; - $this->output->write($anyContent); - - $this->assertEquals($anyContent, $this->output->get()); - } - - public function test_write_shouldNotAppend_IfWriteIsCalledTwice() - { - $anyContent = 'My Actual Content'; - $this->output->write($anyContent); - $this->output->write($anyContent); - - $this->assertEquals($anyContent, $this->output->get()); - } - - public function test_write_shouldSaveAnEmptyString_IfContentIsNull() - { - $this->output->write(null); - - $this->assertTrue($this->output->exists()); - $this->assertEquals('', $this->output->get()); - } - - public function test_destroy_ShouldRemove_IfAnyOutputIsWritten() - { - $this->output->write('test'); - - $this->assertTrue($this->output->exists()); - - $this->output->destroy(); - - $this->assertFalse($this->output->exists()); - $this->assertFalse($this->output->get()); - } - - public function test_destroy_ShouldNotFail_IfNothingIsWritten() - { - $this->output->destroy(); - - $this->assertFalse($this->output->exists()); - $this->assertFalse($this->output->get()); - } - - public function test_twoDifferentOutputHandles_ShouldWriteInDifferentFiles() - { - $output1 = new Output('id1'); - $output2 = new Output('id2'); - - // cleanup possible earlier failed test runs - $output1->destroy(); - $output2->destroy(); - - $output1->write('test 1'); - $this->assertTrue($output1->exists()); - $this->assertFalse($output2->exists()); - $output2->write('test 2'); - - $this->assertEquals('test 1', $output1->get()); - $this->assertEquals('test 2', $output2->get()); - - $output1->destroy(); - $this->assertFalse($output1->exists()); - $this->assertTrue($output2->exists()); - $output2->destroy(); - - $this->assertFalse($output2->exists()); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/CliMulti/ProcessTest.php b/tests/PHPUnit/Core/CliMulti/ProcessTest.php deleted file mode 100644 index 12ec4c98e8..0000000000 --- a/tests/PHPUnit/Core/CliMulti/ProcessTest.php +++ /dev/null @@ -1,109 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\CliMulti\Process; - -/** - * Class ProcessTest - * @group Core - */ -class ProcessTest extends PHPUnit_Framework_TestCase -{ - /** - * @var Process - */ - private $process; - - public function setUp() - { - $this->process = new Process('testPid'); - } - - public function tearDown() - { - $this->process->finishProcess(); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage The given pid has an invalid format - */ - public function test_construct_shouldFailInCasePidIsInvalid() - { - new Process('../../htaccess'); - } - - public function test_construct_shouldBeNotStarted_IfPidJustCreated() - { - $this->assertFalse($this->process->hasStarted()); - } - - public function test_construct_shouldBeNotRunning_IfPidJustCreated() - { - $this->assertFalse($this->process->isRunning()); - } - - public function test_startProcess_finishProcess_ShouldMarkProcessAsStarted() - { - $this->assertFalse($this->process->isRunning()); - $this->assertFalse($this->process->hasStarted()); - $this->assertFalse($this->process->hasFinished()); - - $this->process->startProcess(); - - $this->assertTrue($this->process->isRunning()); - $this->assertTrue($this->process->hasStarted()); - $this->assertTrue($this->process->isRunning()); - $this->assertTrue($this->process->hasStarted()); - $this->assertFalse($this->process->hasFinished()); - - $this->process->startProcess(); - - $this->assertTrue($this->process->isRunning()); - $this->assertTrue($this->process->hasStarted()); - $this->assertFalse($this->process->hasFinished()); - - $this->process->finishProcess(); - - $this->assertFalse($this->process->isRunning()); - $this->assertTrue($this->process->hasStarted()); - $this->assertTrue($this->process->hasFinished()); - } - - public function test_finishProcess_ShouldNotThrowError_IfNotStartedBefore() - { - $this->process->finishProcess(); - - $this->assertFalse($this->process->isRunning()); - $this->assertTrue($this->process->hasStarted()); - $this->assertTrue($this->process->hasFinished()); - } - - public function test_hasStarted() - { - $this->assertTrue($this->process->hasStarted(false)); - $this->assertTrue($this->process->hasStarted('6341')); - - $this->assertFalse($this->process->hasStarted('')); - } - - public function test_isSupported() - { - $this->assertTrue(Process::isSupported(), 'This test does not work on windows or if the commands ps and awk are not available'); - } - - public function test_getSecondsSinceCreation() - { - sleep(3); - $seconds = $this->process->getSecondsSinceCreation(); - - $this->assertGreaterThanOrEqual(3, $seconds); - $this->assertLessThanOrEqual(4, $seconds); - } - -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/Columns/DimensionTest.php b/tests/PHPUnit/Core/Columns/DimensionTest.php deleted file mode 100644 index 6952b3880f..0000000000 --- a/tests/PHPUnit/Core/Columns/DimensionTest.php +++ /dev/null @@ -1,175 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -namespace Piwik\Plugins\Test\Columns -{ - // there is a test that requires the class to be defined in a plugin - - use Piwik\Columns\Dimension; - use Piwik\Plugin\Segment; - - class DimensionTest extends Dimension - { - protected $columnName = 'test_dimension'; - protected $columnType = 'INTEGER (10) DEFAULT 0'; - - public function set($param, $value) - { - $this->$param = $value; - } - - protected function configureSegments() - { - $segment = new Segment(); - $segment->setSegment('exitPageUrl'); - $segment->setName('Actions_ColumnExitPageURL'); - $segment->setCategory('General_Visit'); - $this->addSegment($segment); - - // custom type and sqlSegment - $segment = new Segment(); - $segment->setSegment('exitPageUrl'); - $segment->setSqlSegment('customValue'); - $segment->setType(Segment::TYPE_METRIC); - $segment->setName('Actions_ColumnExitPageURL'); - $segment->setCategory('General_Visit'); - $this->addSegment($segment); - } - } -} - -namespace Piwik\Tests\Core\Columns -{ - use Piwik\Columns\Dimension; - use Piwik\Config; - use Piwik\Plugin\Segment; - use Piwik\Plugin\Manager; - use Piwik\Plugins\Test\Columns\DimensionTest; - use Piwik\Plugins\Test\FakeActionDimension; - - /** - * @group Core - */ - class Core_DimensionTest extends \PHPUnit_Framework_TestCase - { - /** - * @var FakeActionDimension - */ - private $dimension; - - public function setUp() - { - Manager::getInstance()->unloadPlugins(); - Manager::getInstance()->doNotLoadAlwaysActivatedPlugins(); - Config::getInstance()->clear(); - Config::getInstance()->init(); - - $this->dimension = new DimensionTest(); - } - - public function tearDown() - { - Config::unsetInstance(); - Manager::unsetInstance(); - parent::tearDown(); - } - - public function test_hasImplementedEvent_shouldDetectWhetherAMethodWasOverwrittenInTheActualPluginClass() - { - $this->assertTrue($this->dimension->hasImplementedEvent('set')); - $this->assertTrue($this->dimension->hasImplementedEvent('configureSegments')); - - $this->assertFalse($this->dimension->hasImplementedEvent('getSegments')); - } - - public function test_getColumnName_shouldReturnTheNameOfTheColumn() - { - $this->assertSame('test_dimension', $this->dimension->getColumnName()); - } - - public function test_hasColumnType_shouldDetectWhetherAColumnTypeIsSet() - { - $this->assertTrue($this->dimension->hasColumnType()); - - $this->dimension->set('columnType', ''); - $this->assertFalse($this->dimension->hasColumnType()); - } - - public function test_getName_ShouldNotReturnANameByDefault() - { - $this->assertSame('', $this->dimension->getName()); - } - - public function test_getAllDimensions_shouldReturnActionVisitAndConversionDimensions() - { - Manager::getInstance()->loadPlugins(array('Actions', 'Events', 'DevicesDetector', 'Goals')); - - $dimensions = Dimension::getAllDimensions(); - - $this->assertGreaterThan(20, count($dimensions)); - - $foundConversion = false; - $foundVisit = false; - $foundAction = false; - - foreach ($dimensions as $dimension) { - if ($dimension instanceof \Piwik\Plugin\Dimension\ConversionDimension) { - $foundConversion = true; - } else if ($dimension instanceof \Piwik\Plugin\Dimension\ActionDimension) { - $foundAction = true; - } else if ($dimension instanceof \Piwik\Plugin\Dimension\VisitDimension) { - $foundVisit = true; - } else { - $this->fail('Unexpected dimension class found'); - } - - $this->assertRegExp('/Piwik.Plugins.(Actions|Events|DevicesDetector|Goals).Columns/', get_class($dimension)); - } - - $this->assertTrue($foundConversion); - $this->assertTrue($foundAction); - $this->assertTrue($foundVisit); - } - - public function test_getSegment_ShouldReturnConfiguredSegments() - { - $segments = $this->dimension->getSegments(); - - $this->assertCount(2, $segments); - $this->assertInstanceOf('\Piwik\Plugin\Segment', $segments[0]); - $this->assertInstanceOf('\Piwik\Plugin\Segment', $segments[1]); - } - - public function test_addSegment_ShouldPrefilSomeSegmentValuesIfNotDefinedYet() - { - $segments = $this->dimension->getSegments(); - - $this->assertEquals(Segment::TYPE_DIMENSION, $segments[0]->getType()); - } - - public function test_addSegment_ShouldNotOverwritePreAssignedValues() - { - $segments = $this->dimension->getSegments(); - - $this->assertEquals(Segment::TYPE_METRIC, $segments[1]->getType()); - } - - public function test_getId_ShouldCorrectlyGenerateIdFromDimensionsQualifiedClassName() - { - $this->assertEquals("Test.DimensionTest", $this->dimension->getId()); - } - - public function test_factory_ShouldCreateDimensionFromDimensionId() - { - Manager::getInstance()->loadPlugins(array('ExampleTracker')); - - $dimension = Dimension::factory("ExampleTracker.ExampleDimension"); - $this->assertInstanceOf("Piwik\\Plugins\\ExampleTracker\\Columns\\ExampleDimension", $dimension); - } - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/CommonTest.php b/tests/PHPUnit/Core/CommonTest.php deleted file mode 100644 index 86d03c4bdb..0000000000 --- a/tests/PHPUnit/Core/CommonTest.php +++ /dev/null @@ -1,458 +0,0 @@ -<?php -use Piwik\Common; -use Piwik\Filesystem; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class Core_CommonTest extends PHPUnit_Framework_TestCase -{ - /** - * Dataprovider for testSanitizeInputValues - */ - public function getInputValues() - { - return array( // input, output - // sanitize an array OK - array( - array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52), - array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52) - ), - array( - array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52, - array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52), - array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52), - array(array(array(array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52))) - )), - array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52, - array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52), - array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52), - array(array(array(array('test1' => 't1', 't45', "teatae", 4568, array('test'), 1.52))) - )) - ), - // sanitize an array with bad value level1 - array( - array('test1' => 't1', 't45', 'tea1"ta"e', 568, 1 => array('t<e"st'), 1.52), - array('test1' => 't1', 't45', 'tea1"ta"e', 568, 1 => array('t<e"st'), 1.52) - ), - // sanitize an array with bad value level2 - array( - array('tea1"ta"e' => array('t<e"st' => array('tgeag454554"t')), 1.52), - array('tea1"ta"e' => array('t<e"st' => array('tgeag454554"t')), 1.52) - ), - // sanitize a string unicode => no change - array( - " Поиск в Интернете Поgqegиск страниц на рgeqg8978усском", - " Поиск в Интернете Поgqegиск страниц на рgeqg8978усском" - ), - // sanitize a bad string - array( - '& " < > 123abc\'', - '& " < > 123abc'' - ), - // test filter - expect new line and null byte to be filtered out - array( - "New\nLine\rNull\0Byte", - 'NewLineNullByte' - ), - // double encoded - no change (document as user error) - array( - '%48%45%4C%00%4C%4F+%57%4F%52%4C%44', - '%48%45%4C%00%4C%4F+%57%4F%52%4C%44' - ), - // sanitize an integer - array('121564564', '121564564'), - array('121564564.0121', '121564564.0121'), - array(121564564.0121, 121564564.0121), - array(12121, 12121), - // sanitize HTML - array( - "<test toto='mama' piwik=\"cool\">Piwik!!!!!</test>", - "<test toto='mama' piwik="cool">Piwik!!!!!</test>" - ), - // sanitize a SQL query - array( - "SELECT piwik FROM piwik_tests where test= 'super\"value' AND cool=toto #comment here", - "SELECT piwik FROM piwik_tests where test= 'super"value' AND cool=toto #comment here" - ), - // sanitize php variables - array(true, true), - array(false, false), - array(null, null), - array("", ""), - ); - } - - /** - * @dataProvider getInputValues - * @group Core - */ - public function testSanitizeInputValues($input, $output) - { - if (version_compare(PHP_VERSION, '5.4') < 0) { - $this->assertTrue(@set_magic_quotes_runtime(1)); - $this->assertEquals(1, @get_magic_quotes_runtime()); - $this->assertEquals($output, Common::sanitizeInputValues($input)); - - $this->assertTrue(@set_magic_quotes_runtime(0)); - $this->assertEquals(0, @get_magic_quotes_runtime()); - $this->assertEquals($output, Common::sanitizeInputValues($input)); - } - } - - /** - * emptyvarname => exception - * @group Core - */ - public function testGetRequestVarEmptyVarName() - { - try { - $_GET[''] = 1; - Common::getRequestVar(''); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * nodefault Notype Novalue => exception - * @group Core - */ - public function testGetRequestVarNoDefaultNoTypeNoValue() - { - try { - Common::getRequestVar('test'); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * nodefault Notype WithValue => value - * @group Core - */ - public function testGetRequestVarNoDefaultNoTypeWithValue() - { - $_GET['test'] = 1413.431413; - $this->assertEquals($_GET['test'], Common::getRequestVar('test')); - - } - - /** - * nodefault Withtype WithValue => exception cos type not matching - * @group Core - */ - public function testGetRequestVarNoDefaultWithTypeWithValue() - { - try { - $_GET['test'] = 1413.431413; - Common::getRequestVar('test', null, 'string'); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * nodefault Withtype WithValue => exception cos type not matching - * @group Core - */ - public function testGetRequestVarNoDefaultWithTypeWithValue2() - { - try { - Common::getRequestVar('test', null, 'string'); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - - } - - /** - * Dataprovider for testGetRequestVar - */ - public function getRequestVarValues() - { - return array( // value of request var, default value, var type, expected - array(1413.431413, 2, 'int', 2), // withdefault Withtype WithValue => value casted as type - array(null, 'default', null, 'default'), // withdefault Notype NoValue => default value - array(null, 'default', 'string', 'default'), // withdefault Withtype NoValue =>default value casted as type - // integer as a default value / types - array('', 45, 'int', 45), - array(1413.431413, 45, 'int', 45), - array('', 45, 'integer', 45), - array('', 45.0, 'float', 45.0), - array('', 45.25, 'float', 45.25), - // string as a default value / types - array('1413.431413', 45, 'int', 45), - array('1413.431413', 45, 'string', '1413.431413'), - array('', 45, 'string', '45'), - array('', 'geaga', 'string', 'geaga'), - array('', ''}{}}{}{}'', 'string', ''}{}}{}{}''), - array('', 'http://url?arg1=val1&arg2=val2', 'string', 'http://url?arg1=val1&arg2=val2'), - array('http://url?arg1=val1&arg2=val2', 'http://url?arg1=val1&arg2=val4', 'string', 'http://url?arg1=val1&arg2=val2'), - array(array("test", 1345524, array("gaga")), array(), 'array', array("test", 1345524, array("gaga"))), // array as a default value / types - array(array("test", 1345524, array("gaga")), 45, 'string', "45"), - array(array("test", 1345524, array("gaga")), array(1), 'array', array("test", 1345524, array("gaga"))), - array(array("test", 1345524, array("gaga")), 4, 'int', 4), - array('', array(1), 'array', array(1)), - array('', array(), 'array', array()), - // we give a number in a string and request for a number => it should give the string casted as a number - array('45645646', 1, 'int', 45645646), - array('45645646', 45, 'integer', 45645646), - array('45645646', '45454', 'string', '45645646'), - array('45645646', array(), 'array', array()), - ); - } - - /** - * @dataProvider getRequestVarValues - * @group Core - */ - public function testGetRequestVar($varValue, $default, $type, $expected) - { - $_GET['test'] = $varValue; - $return = Common::getRequestVar('test', $default, $type); - $this->assertEquals($expected, $return); - // validate correct type - switch ($type) { - case 'int': - case 'integer': - $this->assertTrue(is_int($return)); - break; - case 'float': - $this->assertTrue(is_float($return)); - break; - case 'string': - $this->assertTrue(is_string($return)); - break; - case 'array': - $this->assertTrue(is_array($return)); - break; - } - } - - /** - * @group Core - */ - public function testIsValidFilenameValidValues() - { - $valid = array( - "test", - "test.txt", - "test.......", - "en-ZHsimplified", - '0', - ); - foreach ($valid as $toTest) { - $this->assertTrue(Filesystem::isValidFilename($toTest), $toTest . " not valid!"); - } - } - - /** - * @group Core - */ - public function testIsValidFilenameNotValidValues() - { - $notvalid = array( - "../test", - "/etc/htpasswd", - '$var', - ';test', - '[bizarre]', - '', - false, - ".htaccess", - "very long long eogaioge ageja geau ghaeihieg heiagie aiughaeui hfilename", - "WHITE SPACE", - ); - foreach ($notvalid as $toTest) { - $this->assertFalse(Filesystem::isValidFilename($toTest), $toTest . " valid but shouldn't!"); - } - } - - /** - * Dataprovider for testGetBrowserLanguage - */ - public function getBrowserLanguageData() - { - return array( // user agent, browser language - array("en-gb", "en-gb"), - - // filter quality attribute - array("en-us,en;q=0.5", "en-us,en"), - - // bad user agents - array("en-us,chrome://global/locale/intl.properties", "en-us"), - - // unregistered language tag - array("en,en-securid", "en"), - array("en-securid,en", "en"), - array("en-us,en-securid,en", "en-us,en"), - - // accept private sub tags - array("en-us,x-en-securid", "en-us,x-en-securid"), - array("en-us,en-x-securid", "en-us,en-x-securid"), - - // filter arbitrary white space - array("en-us, en", "en-us,en"), - array("en-ca, en-us ,en", "en-ca,en-us,en"), - - // handle comments - array(" ( comment ) en-us (another comment) ", "en-us"), - - // handle quoted pairs (embedded in comments) - array(" ( \( start ) en-us ( \) end ) ", "en-us"), - array(" ( \) en-ca, \( ) en-us ( \) ,en ) ", "en-us"), - ); - } - - /** - * @dataProvider getBrowserLanguageData - * @group Core - */ - public function testGetBrowserLanguage($useragent, $browserLanguage) - { - $res = Common::getBrowserLanguage($useragent); - $this->assertEquals($browserLanguage, $res); - } - - /** - * Dataprovider for testExtractCountryCodeFromBrowserLanguage - */ - public function getCountryCodeTestData() - { - - return array( // browser language, valid countries, expected result - array("", array(), "xx"), - array("", array("us" => 'amn'), "xx"), - array("en", array("us" => 'amn'), "xx"), - array("en-us", array("us" => 'amn'), "us"), - array("en-ca", array("us" => 'amn'), "xx"), - array("en-ca", array("us" => 'amn', "ca" => 'amn'), "ca"), - array("fr-fr,fr-ca", array("us" => 'amn', "ca" => 'amn'), "ca"), - array("fr-fr;q=1.0,fr-ca;q=0.9", array("us" => 'amn', "ca" => 'amn'), "ca"), - array("fr-ca,fr;q=0.1", array("us" => 'amn', "ca" => 'amn'), "ca"), - array("en-us,en;q=0.5", Common::getCountriesList(), "us"), - array("fr-ca,fr;q=0.1", array("fr" => 'eur', "us" => 'amn', "ca" => 'amn'), "ca"), - array("fr-fr,fr-ca", array("fr" => 'eur', "us" => 'amn', "ca" => 'amn'), "fr") - ); - } - - /** - * @dataProvider getCountryCodeTestData - * @group Core - */ - public function testExtractCountryCodeFromBrowserLanguage($browserLanguage, $validCountries, $expected) - { - include 'DataFiles/LanguageToCountry.php'; - - $this->assertEquals($expected, Common::extractCountryCodeFromBrowserLanguage($browserLanguage, $validCountries, true)); - $this->assertEquals($expected, Common::extractCountryCodeFromBrowserLanguage($browserLanguage, $validCountries, false)); - } - - /** - * Dataprovider for testExtractCountryCodeFromBrowserLanguageInfer - */ - public function getCountryCodeTestDataInfer() - { - - return array( // browser language, valid countries, expected result (non-guess vs guess) - array("fr,en-us", array("us" => 'amn', "ca" => 'amn'), "us", "fr"), - array("fr,en-us", array("fr" => 'eur', "us" => 'amn', "ca" => 'amn'), "us", "fr"), - array("fr,fr-fr,en-us", array("fr" => 'eur', "us" => 'amn', "ca" => 'amn'), "fr", "fr"), - array("fr-fr,fr,en-us", array("fr" => 'eur', "us" => 'amn', "ca" => 'amn'), "fr", "fr") - ); - } - - /** - * @dataProvider getCountryCodeTestDataInfer - * @group Core - */ - public function testExtractCountryCodeFromBrowserLanguageInfer($browserLanguage, $validCountries, $expected, $expectedInfer) - { - include "DataFiles/LanguageToCountry.php"; - - // do not infer country from language - $this->assertEquals($expected, Common::extractCountryCodeFromBrowserLanguage($browserLanguage, $validCountries, $enableLanguageToCountryGuess = false)); - - // infer country from language - $this->assertEquals($expectedInfer, Common::extractCountryCodeFromBrowserLanguage($browserLanguage, $validCountries, $enableLanguageToCountryGuess = true)); - } - - /** - * Dataprovider for testExtractLanguageCodeFromBrowserLanguage - */ - public function getLanguageDataToExtract() - { - return array( // browser language, valid languages, expected result - array("fr-ca", array("fr"), "fr"), - array("", array(), "xx"), - array("", array("en"), "xx"), - array("fr", array("en"), "xx"), - array("en", array("en"), "en"), - array("en-ca", array("en-ca"), "en-ca"), - array("en-ca", array("en"), "en"), - array("fr,en-us", array("fr", "en"), "fr"), - array("fr,en-us", array("en", "fr"), "fr"), - array("fr-fr,fr-ca", array("fr"), "fr"), - array("fr-fr,fr-ca", array("fr-ca"), "fr-ca"), - array("fr-fr;q=1.0,fr-ca;q=0.9", array("fr-ca"), "fr-ca"), - array("fr-ca,fr;q=0.1", array("fr-ca"), "fr-ca"), - array("r5,fr;q=1,de", array("fr", "de"), "fr"), - array("Zen§gq1", array("en"), "xx"), - ); - } - - /** - * @dataProvider getLanguageDataToExtract - * @group Core - */ - public function testExtractLanguageCodeFromBrowserLanguage($browserLanguage, $validLanguages, $expected) - { - $this->assertEquals($expected, Common::extractLanguageCodeFromBrowserLanguage($browserLanguage, $validLanguages), "test with {$browserLanguage} failed, expected {$expected}"); - } - - /** - * @group Core - */ - public function testSearchEnginesDefinedCorrectly() - { - include "DataFiles/SearchEngines.php"; - - $searchEngines = array(); - foreach ($GLOBALS['Piwik_SearchEngines'] as $host => $info) { - if (isset($info[2]) && $info[2] !== false) { - $this->assertTrue(strrpos($info[2], "{k}") !== false, $host . " search URL is not defined correctly, must contain the macro {k}"); - } - - if (!array_key_exists($info[0], $searchEngines)) { - $searchEngines[$info[0]] = true; - - $this->assertTrue(strpos($host, '{}') === false, $host . " search URL is the master record and should not contain {}"); - } - - if (isset($info[3]) && $info[3] !== false) { - $this->assertTrue(is_array($info[3]) || is_string($info[3]), $host . ' encoding must be either a string or an array'); - - if (is_string($info[3])) { - $this->assertTrue(trim($info[3]) !== '', $host . ' encoding cannot be an empty string'); - $this->assertTrue(strpos($info[3], ' ') === false, $host . ' encoding cannot contain spaces'); - - } - - if (is_array($info[3])) { - $this->assertTrue(count($info[3]) > 0, $host . ' encodings cannot be an empty array'); - $this->assertTrue(strpos(serialize($info[3]), '""') === false, $host . ' encodings in array cannot be empty stringss'); - $this->assertTrue(strpos(serialize($info[3]), ' ') === false, $host . ' encodings in array cannot contain spaces'); - } - } - } - } - -} diff --git a/tests/PHPUnit/Core/ConfigTest.php b/tests/PHPUnit/Core/ConfigTest.php deleted file mode 100644 index 128e198eeb..0000000000 --- a/tests/PHPUnit/Core/ConfigTest.php +++ /dev/null @@ -1,450 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\Config; - -/** - * @group Core - */ -class ConfigTest extends PHPUnit_Framework_TestCase -{ - public function testUserConfigOverwritesSectionGlobalConfigValue() - { - $userFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/config.ini.php'; - $globalFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/global.ini.php'; - $commonFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/common.ini.php'; - $config = Config::getInstance(); - $config->setTestEnvironment($userFile, $globalFile, $commonFile); - $config->init(); - - $this->assertEquals("value_overwritten", $config->Category['key1']); - $this->assertEquals("value2", $config->Category['key2']); - $this->assertEquals('tes"t', $config->GeneralSection['login']); - $this->assertEquals("value3", $config->CategoryOnlyInGlobalFile['key3']); - $this->assertEquals("value4", $config->CategoryOnlyInGlobalFile['key4']); - - $expectedArray = array('plugin"1', 'plugin2', 'plugin3'); - $array = $config->TestArray; - $this->assertEquals($expectedArray, $array['installed']); - - $expectedArray = array('value1', 'value2'); - $array = $config->TestArrayOnlyInGlobalFile; - $this->assertEquals($expectedArray, $array['my_array']); - - $expectedArray = array('value1', 'value2'); - $array = $config->TestArrayOnlyInGlobalFile; - $this->assertEquals($expectedArray, $array['my_array']); - - } - - public function test_CommonConfig_Overrides() - { - $userFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/config.ini.php'; - $globalFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/global.ini.php'; - $commonFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/common.config.ini.php'; - - $config = Config::getInstance(); - $config->setTestEnvironment($userFile, $globalFile, $commonFile); - $config->init(); - - $this->assertEquals("valueCommon", $config->Category['key2'], var_export($config->Category['key2'], true)); - $this->assertEquals("test", $config->GeneralSection['password']); - $this->assertEquals("commonValue", $config->TestOnlyInCommon['value']); - - } - - public function testWritingConfigWithSpecialCharacters() - { - $userFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/config.written.ini.php'; - $globalFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/global.ini.php'; - - $config = Config::getInstance(); - $config->setTestEnvironment($userFile, $globalFile); - $config->init(); - - $stringWritten = '&6^ geagea\'\'\'";;&'; - $config->Category = array('test' => $stringWritten); - $this->assertEquals($stringWritten, $config->Category['test']); - - // This will write the file - $config->forceSave(); - - $config = Config::getInstance(); - $config->setTestEnvironment($userFile, $globalFile); - $config->init(); - - $this->assertEquals($stringWritten, $config->Category['test']); - $config->Category = array( - 'test' => $config->Category['test'], - 'test2' => $stringWritten, - ); - $this->assertEquals($stringWritten, $config->Category['test']); - $this->assertEquals($stringWritten, $config->Category['test2']); - } - - public function testUserConfigOverwritesGlobalConfig() - { - $userFile = PIWIK_PATH_TEST_TO_ROOT . '/tests/resources/Config/config.ini.php'; - $globalFile = PIWIK_PATH_TEST_TO_ROOT . '/tests/resources/Config/global.ini.php'; - - $config = Config::getInstance(); - $config->setTestEnvironment($userFile, $globalFile); - - $this->assertEquals("value_overwritten", $config->Category['key1']); - $this->assertEquals("value2", $config->Category['key2']); - $this->assertEquals("tes\"t", $config->GeneralSection['login']); - $this->assertEquals("value3", $config->CategoryOnlyInGlobalFile['key3']); - $this->assertEquals("value4", $config->CategoryOnlyInGlobalFile['key4']); - - $expectedArray = array('plugin"1', 'plugin2', 'plugin3'); - $array = $config->TestArray; - $this->assertEquals($expectedArray, $array['installed']); - - $expectedArray = array('value1', 'value2'); - $array = $config->TestArrayOnlyInGlobalFile; - $this->assertEquals($expectedArray, $array['my_array']); - - Config::getInstance()->clear(); - } - - /** - * Dateprovider for testCompareElements - */ - public function getCompareElementsData() - { - return array( - array('string = string', array( - 'a', 'a', 0, - )), - array('string > string', array( - 'b', 'a', 1, - )), - array('string < string', array( - 'a', 'b', -1, - )), - array('string vs array', array( - 'a', array('a'), -1, - )), - array('array vs string', array( - array('a'), 'a', 1, - )), - array('array = array', array( - array('a'), array('a'), 0, - )), - array('array > array', array( - array('b'), array('a'), 1, - )), - array('array < array', array( - array('a'), array('b'), -1, - )), - ); - } - - /** - * @dataProvider getCompareElementsData - */ - public function testCompareElements($description, $test) - { - list($a, $b, $expected) = $test; - - $result = Config::compareElements($a, $b); - $this->assertEquals($expected, $result, $description); - } - - /** - * Dataprovider for testArrayUnmerge - * @return array - */ - public function getArrayUnmergeData() - { - return array( - array('description of test', array( - array(), - array(), - )), - array('override with empty', array( - array('login' => 'root', 'password' => 'b33r'), - array('password' => ''), - )), - array('override with non-empty', array( - array('login' => 'root', 'password' => ''), - array('password' => 'b33r'), - )), - array('add element', array( - array('login' => 'root', 'password' => ''), - array('auth' => 'Login'), - )), - array('override with empty array', array( - array('headers' => ''), - array('headers' => array()), - )), - array('override with array', array( - array('headers' => ''), - array('headers' => array('Content-Length', 'Content-Type')), - )), - array('override an array', array( - array('headers' => array()), - array('headers' => array('Content-Length', 'Content-Type')), - )), - array('override similar arrays', array( - array('headers' => array('Content-Length', 'Set-Cookie')), - array('headers' => array('Content-Length', 'Content-Type')), - )), - array('override dyslexic arrays', array( - array('headers' => array('Content-Type', 'Content-Length')), - array('headers' => array('Content-Length', 'Content-Type')), - )), - ); - } - - /** - * @dataProvider getArrayUnmergeData - */ - public function testArrayUnmerge($description, $test) - { - $configWriter = Config::getInstance(); - - list($a, $b) = $test; - - $combined = array_merge($a, $b); - - $diff = $configWriter->array_unmerge($a, $combined); - - // expect $b == $diff - $this->assertEquals(serialize($b), serialize($diff), $description); - } - - /** - * Dataprovider for testDumpConfig - */ - public function getDumpConfigData() - { - $header = "; <?php exit; ?> DO NOT REMOVE THIS LINE\n" . - "; file automatically generated or modified by Piwik; you can manually override the default values in global.ini.php by redefining them in this file.\n"; - - return array( - // Test name, array( - // LOCAL - // GLOBAL - // COMMON - // CACHE - // --> EXPECTED <-- - array('global only, not cached', array( - array(), // local - array('General' => array('debug' => '1')), // global - array(), // common - array(), - false, - )), - - array('global only, cached get', array( - array(), // local - array('General' => array('debug' => '1')), // global - array(), // common - array('General' => array('debug' => '1')), - false, - )), - - array('global only, cached set', array( - array(), // local - array('General' => array('debug' => '1')), // global - array(), // common - array('General' => array('debug' => '2')), - $header . "[General]\ndebug = 2\n\n", - )), - - array('local copy (same), not cached', array( - array('General' => array('debug' => '1')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array(), - false, - )), - - array('local copy (same), cached get', array( - array('General' => array('debug' => '1')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array('General' => array('debug' => '1')), - false, - )), - - array('local copy (same), cached set', array( - array('General' => array('debug' => '1')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array('General' => array('debug' => '2')), - $header . "[General]\ndebug = 2\n\n", - )), - - array('local copy (different), not cached', array( - array('General' => array('debug' => '2')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array(), - false, - )), - - array('local copy (different), cached get', array( - array('General' => array('debug' => '2')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array('General' => array('debug' => '2')), - false, - )), - - array('local copy (different), cached set', array( - array('General' => array('debug' => '2')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array('General' => array('debug' => '3')), - $header . "[General]\ndebug = 3\n\n", - )), - - array('local copy, not cached, new section', array( - array('Tracker' => array('anonymize' => '1')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array(), - false, - )), - - array('local copy, cached get, new section', array( - array('Tracker' => array('anonymize' => '1')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array('Tracker' => array('anonymize' => '1')), - false, - )), - - array('local copy, cached set local, new section', array( - array('Tracker' => array('anonymize' => '1')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array('Tracker' => array('anonymize' => '2')), - $header . "[Tracker]\nanonymize = 2\n\n", - )), - - array('local copy, cached set global, new section', array( - array('Tracker' => array('anonymize' => '1')), // local - array('General' => array('debug' => '1')), // global - array(), // common - array('General' => array('debug' => '2')), - $header . "[General]\ndebug = 2\n\n[Tracker]\nanonymize = 1\n\n", - )), - - array('sort, common sections', array( - array('Tracker' => array('anonymize' => '1'), // local - 'General' => array('debug' => '1')), - array('General' => array('debug' => '0'), // global - 'Tracker' => array('anonymize' => '0')), - array(), // common - array('Tracker' => array('anonymize' => '2')), - $header . "[General]\ndebug = 1\n\n[Tracker]\nanonymize = 2\n\n", - )), - - array('sort, common sections before new section', array( - array('Tracker' => array('anonymize' => '1'), // local - 'General' => array('debug' => '1')), - array('General' => array('debug' => '0'), // global - 'Tracker' => array('anonymize' => '0')), - array(), // common - array('Segment' => array('dimension' => 'foo')), - $header . "[General]\ndebug = 1\n\n[Tracker]\nanonymize = 1\n\n[Segment]\ndimension = \"foo\"\n\n", - )), - - array('change back to default', array( - array('Tracker' => array('anonymize' => '1')), // local - array('Tracker' => array('anonymize' => '0'), // global - 'General' => array('debug' => '1')), - array(), // common - array('Tracker' => array('anonymize' => '0')), - $header - )), - - array('[General] trusted_hosts has been updated and only this one is written', array( - array('General' => array('trusted_hosts' => 'someRandomHostToOverwrite')), // local - array('General' => array('settingGlobal' => 'global', // global - 'settingCommon' => 'global', - 'trusted_hosts' => 'none')), - array('General' => array('settingCommon' => 'common', // common - 'settingCommon2' => 'common')), - array('General' => array('trusted_hosts' => 'works')), - $header . "[General]\ntrusted_hosts = \"works\"\n\n", - )), - - // Same as above but without trusted_hosts default value in global.ini.php - // Also, settingCommon3 is the same in the local file as in common, so it is not written out - array('trusted_hosts and settingCommon3 changed ', array( - array('General' => array('trusted_hosts' => 'someRandomHostToOverwrite')), // local - array('General' => array('settingGlobal' => 'global', // global - 'settingCommon' => 'global')), - array('General' => array('settingCommon' => 'common', // common - 'settingCommon2' => 'common', - 'settingCommon3' => 'common3')), - array('General' => array('trusted_hosts' => 'works', // common - 'settingCommon2' => 'common', // will be cleared since it's same as in common - 'settingCommon3' => 'commonOverridenByLocal')), - $header . "[General]\ntrusted_hosts = \"works\"\nsettingCommon3 = \"commonOverridenByLocal\"\n\n", - )), - - // the value in [General]->key has changed - // the value in [CommonCategory]->newSetting has changed, - // but [CommonCategory]->settingCommon2 hasn't so it is not written - array('Common tests file', array( - array('General' => array('key' => 'value')), // local - array('General' => array('key' => 'global'), // global - 'CommonCategory' => array('settingGlobal' => 'valueGlobal')), - array('CommonCategory' => array('settingCommon' => 'common', // common - 'settingCommon2' => 'common2')), - array('CommonCategory' => array('settingCommon2' => 'common2', - 'newSetting' => 'newValue')), - $header . "[General]\nkey = \"value\"\n\n[CommonCategory]\nnewSetting = \"newValue\"\n\n", - )), - - array('Converts Dollar Sign To Dollar Entity', array( - array('General' => array('key' => '$value', 'key2' => '${value}')), // local - array('General' => array('key' => '$global'), // global - 'CommonCategory' => array('settingGlobal' => 'valueGlobal')), - array('CommonCategory' => array('settingCommon' => 'common', // common - 'settingCommon2' => 'common2')), - array('CommonCategory' => array('settingCommon2' => 'common2', - 'newSetting' => 'newValue')), - $header . "[General]\nkey = \"$value\"\nkey2 = \"${value}\"\n\n[CommonCategory]\nnewSetting = \"newValue\"\n\n", - )), - ); - - } - - /** - * @dataProvider getDumpConfigData - */ - public function testDumpConfig($description, $test) - { - $config = Config::getInstance(); - - list($configLocal, $configGlobal, $configCommon, $configCache, $expected) = $test; - - $output = $config->dumpConfig($configLocal, $configGlobal, $configCommon, $configCache); - $this->assertEquals($expected, $output, $description); - } - - public function testDollarEntityGetsConvertedToDollarSign() - { - $userFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/config.ini.php'; - $globalFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/global.ini.php'; - $commonFile = PIWIK_INCLUDE_PATH . '/tests/resources/Config/common.config.ini.php'; - - $config = Config::getInstance(); - $config->setTestEnvironment($userFile, $globalFile, $commonFile); - $config->init(); - - $this->assertEquals('${@piwik(crash))}', $config->Category['key3']); - } -} - diff --git a/tests/PHPUnit/Core/CookieTest.php b/tests/PHPUnit/Core/CookieTest.php deleted file mode 100644 index 9b77aeddaf..0000000000 --- a/tests/PHPUnit/Core/CookieTest.php +++ /dev/null @@ -1,157 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class CookieTest extends PHPUnit_Framework_TestCase -{ - /** - * Dataprovider for testJsonSerialize - */ - public function getJsonSerializeData() - { - return array( - array('null', null), - array('bool false', false), - array('bool true', true), - array('negative int', -42), - array('zero', 0), - array('positive int', 42), - array('float', 1.25), - array('empty string', ''), - array('nul in string', "\0"), - array('carriage return in string', "first line\r\nsecond line"), - array('utf7 in string', 'hello, world'), - array('utf8 in string', '是'), - array('empty array', array()), - array('single element array', array("test")), - array('associative array', array("alpha", 2 => "beta")), - array('mixed keys', array('first' => 'john', 'last' => 'doe', 10 => 'age')), - array('nested arrays', array('top' => array('middle' => 2, array('bottom'), 'last'), 'the end' => true)), - array('array confusion', array('"', "'", '}', ';', ':')), - ); - } - - /** - * @group Core - * - * @dataProvider getJsonSerializeData - */ - public function testJsonSerialize($testData, $id) - { - // @see http://bugs.php.net/38680 - if (PHP_VERSION >= '5.2.0' && PHP_VERSION < '5.2.1') { - $this->markTestSkipped('see http://bugs.php.net/38680'); - } - - $this->assertEquals($testData, json_decode(json_encode($testData), $assoc = true), $id); - } - - /** - * Dataprovider for testSafeSerialize - */ - public function getSafeSerializeData() - { - return array( - array('null', null), - array('bool false', false), - array('bool true', true), - array('negative int', -42), - array('zero', 0), - array('positive int', 42), - array('float', 1.25), - array('empty string', ''), - array('nul in string', "\0"), - array('carriage return in string', "first line\r\nsecond line"), - array('utf7 in string', 'hello, world'), - array('utf8 in string', '是'), - array('empty array', array()), - array('single element array', array("test")), - array('associative array', array("alpha", 2 => "beta")), - array('mixed keys', array('first' => 'john', 'last' => 'doe', 10 => 'age')), - array('nested arrays', array('top' => array('middle' => 2, array('bottom'), 'last'), 'the end' => true)), - array('array confusion', array('"', "'", '}', ';', ':')), - ); - } - - /** - * @group Core - * - * @dataProvider getSafeSerializeData - */ - public function testSafeSerialize($id, $testData) - { - $this->assertEquals(serialize($testData), safe_serialize($testData), $id); - $this->assertEquals($testData, unserialize(safe_serialize($testData)), $id); - $this->assertSame($testData, safe_unserialize(safe_serialize($testData)), $id); - $this->assertSame($testData, safe_unserialize(serialize($testData)), $id); - } - - /** - * @group Core - */ - public function testSafeUnserialize() - { - /* - * serialize() uses its internal maachine representation when floats expressed in E-notation, - * which may vary between php versions, OS, and hardware platforms - */ - $testData = -5.0E+142; - // intentionally disabled; this doesn't work -// $this->assertEquals( safe_serialize($testData), serialize($testData) ); - $this->assertEquals($testData, unserialize(safe_serialize($testData))); - $this->assertSame($testData, safe_unserialize(safe_serialize($testData))); - // workaround: cast floats into strings - $this->assertSame($testData, safe_unserialize(serialize($testData))); - - $unserialized = array( - 'announcement' => true, - 'source' => array( - array( - 'filename' => 'php-5.3.3.tar.bz2', - 'name' => 'PHP 5.3.3 (tar.bz2)', - 'md5' => '21ceeeb232813c10283a5ca1b4c87b48', - 'date' => '22 July 2010', - ), - array( - 'filename' => 'php-5.3.3.tar.gz', - 'name' => 'PHP 5.3.3 (tar.gz)', - 'md5' => '5adf1a537895c2ec933fddd48e78d8a2', - 'date' => '22 July 2010', - ), - ), - 'date' => '22 July 2010', - 'version' => '5.3.3', - ); - $serialized = 'a:4:{s:12:"announcement";b:1;s:6:"source";a:2:{i:0;a:4:{s:8:"filename";s:17:"php-5.3.3.tar.bz2";s:4:"name";s:19:"PHP 5.3.3 (tar.bz2)";s:3:"md5";s:32:"21ceeeb232813c10283a5ca1b4c87b48";s:4:"date";s:12:"22 July 2010";}i:1;a:4:{s:8:"filename";s:16:"php-5.3.3.tar.gz";s:4:"name";s:18:"PHP 5.3.3 (tar.gz)";s:3:"md5";s:32:"5adf1a537895c2ec933fddd48e78d8a2";s:4:"date";s:12:"22 July 2010";}}s:4:"date";s:12:"22 July 2010";s:7:"version";s:5:"5.3.3";}'; - - $this->assertSame($unserialized, unserialize($serialized)); - $this->assertEquals($serialized, serialize($unserialized)); - - $this->assertSame($unserialized, safe_unserialize($serialized)); - $this->assertEquals($serialized, safe_serialize($unserialized)); - $this->assertSame($unserialized, safe_unserialize(safe_serialize($unserialized))); - $this->assertEquals($serialized, safe_serialize(safe_unserialize($serialized))); - - $a = 'O:31:"Test_Piwik_Cookie_Phantom_Class":0:{}'; - $this->assertFalse(safe_unserialize($a), "test: unserializing an object where class not (yet) defined"); - - $a = 'O:28:"Test_Piwik_Cookie_Mock_Class":0:{}'; - $this->assertFalse(safe_unserialize($a), "test: unserializing an object where class is defined"); - - $a = 'a:1:{i:0;O:28:"Test_Piwik_Cookie_Mock_Class":0:{}}'; - $this->assertFalse(safe_unserialize($a), "test: unserializing nested object where class is defined"); - - $a = 'a:2:{i:0;s:4:"test";i:1;O:28:"Test_Piwik_Cookie_Mock_Class":0:{}}'; - $this->assertFalse(safe_unserialize($a), "test: unserializing another nested object where class is defined"); - - $a = 'O:28:"Test_Piwik_Cookie_Mock_Class":1:{s:34:"' . "\0" . 'Test_Piwik_Cookie_Mock_Class' . "\0" . 'name";s:4:"test";}'; - $this->assertFalse(safe_unserialize($a), "test: unserializing object with member where class is defined"); - - // arrays and objects cannot be used as keys, i.e., generates "Warning: Illegal offset type ..." - $a = 'a:2:{i:0;a:0:{}O:28:"Test_Piwik_Cookie_Mock_Class":0:{}s:4:"test";'; - $this->assertFalse(safe_unserialize($a), "test: unserializing with illegal key"); - } -} diff --git a/tests/PHPUnit/Core/DataTable/Filter/AddSummaryRowTest.php b/tests/PHPUnit/Core/DataTable/Filter/AddSummaryRowTest.php deleted file mode 100644 index 71b41bd429..0000000000 --- a/tests/PHPUnit/Core/DataTable/Filter/AddSummaryRowTest.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable; -use Piwik\DataTable\Row; - -class DataTable_Filter_AddSummaryRowTest extends PHPUnit_Framework_TestCase -{ - /** - * @group AddSummaryRow - * @group Core - */ - public function testAddSummaryRow() - { - $dataTable = $this->getDataTableCount5(); - $dataTable->filter('AddSummaryRow'); - $this->assertEquals(6, $dataTable->getRowsCount()); - $expectedColumns = array( - 'label' => '-1', - 'nb' => 11111 - ); - $this->assertEquals($expectedColumns, $dataTable->getLastRow()->getColumns()); - } - - /** - * Returns table used for the tests - * - * @return DataTable - */ - protected function getDataTableCount5() - { - $table = new DataTable; - $table->addRow($this->getRow0()); - $table->addRow($this->getRow1()); - $table->addRow($this->getRow2()); - $table->addRow($this->getRow3()); - $table->addRow($this->getRow4()); - return $table; - } - - protected function getRow0() - { - return new Row(array(Row::COLUMNS => array('nb' => 10000, 'label' => 'amazon'))); - } - - protected function getRow1() - { - return new Row(array(Row::COLUMNS => array('label' => 'yahoo', 'nb' => 1000))); - } - - protected function getRow2() - { - return new Row(array(Row::COLUMNS => array('label' => 'piwik', 'nb' => 100))); - } - - protected function getRow3() - { - return new Row(array(Row::COLUMNS => array('label' => 'ask', 'nb' => 10))); - } - - protected function getRow4() - { - return new Row(array(Row::COLUMNS => array('nb' => 1, 'label' => 'google'))); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/DataTable/Filter/ExcludeLowPopulationTest.php b/tests/PHPUnit/Core/DataTable/Filter/ExcludeLowPopulationTest.php deleted file mode 100644 index 469015a24c..0000000000 --- a/tests/PHPUnit/Core/DataTable/Filter/ExcludeLowPopulationTest.php +++ /dev/null @@ -1,116 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Filter\ExcludeLowPopulation; -use Piwik\DataTable; -use Piwik\DataTable\Row; - -class DataTable_Filter_ExcludeLowPopulationTest extends PHPUnit_Framework_TestCase -{ - protected function getTestDataTable() - { - $table = new DataTable; - $table->addRowsFromArray( - array( - array(Row::COLUMNS => array('label' => 'zero', 'count' => 0)), - array(Row::COLUMNS => array('label' => 'one', 'count' => 1)), - array(Row::COLUMNS => array('label' => 'onedotfive', 'count' => 1.5)), - array(Row::COLUMNS => array('label' => 'ten', 'count' => 10)), - array(Row::COLUMNS => array('label' => 'ninety', 'count' => 90)), - array(Row::COLUMNS => array('label' => 'hundred', 'count' => 100)), - ) - ); - return $table; - } - - /** - * @group Core - **/ - public function testStandardTable() - { - $table = $this->getTestDataTable(); - $filter = new ExcludeLowPopulation($table, 'count', 1.1); - $filter->filter($table); - $this->assertEquals(4, $table->getRowsCount()); - $this->assertEquals(array(1.5, 10, 90, 100), $table->getColumn('count')); - } - - /** - * @group Core - **/ - public function testFilterEqualOneDoesFilter() - { - $table = $this->getTestDataTable(); - $filter = new ExcludeLowPopulation($table, 'count', 1); - $filter->filter($table); - $this->assertEquals(5, $table->getRowsCount()); - } - - /** - * @group Core - **/ - public function testFilterEqualZeroDoesFilter() - { - $table = $this->getTestDataTable(); - $filter = new ExcludeLowPopulation($table, 'count', 0); - $filter->filter($table); - $this->assertEquals(3, $table->getRowsCount()); - $this->assertEquals(array(10, 90, 100), $table->getColumn('count')); - } - - /** - * @group Core - */ - public function testFilterSpecifyExcludeLowPopulationThresholdDoesFilter() - { - $table = $this->getTestDataTable(); - $filter = new ExcludeLowPopulation($table, 'count', 0, 0.4); //40% - $filter->filter($table); - $this->assertEquals(2, $table->getRowsCount()); - $this->assertEquals(array(90, 100), $table->getColumn('count')); - } - - /** - * Test to exclude low population filter - * - * @group Core - */ - public function testFilterLowpop1() - { - - $idcol = Row::COLUMNS; - - $table = new DataTable(); - $rows = array( - array($idcol => array('label' => 'google', 'nb_visits' => 897)), //0 - array($idcol => array('label' => 'ask', 'nb_visits' => -152)), //1 - array($idcol => array('label' => 'piwik', 'nb_visits' => 1.5)), //2 - array($idcol => array('label' => 'piwik2', 'nb_visits' => 1.4)), //2 - array($idcol => array('label' => 'yahoo', 'nb_visits' => 154)), //3 - array($idcol => array('label' => 'amazon', 'nb_visits' => 30)), //4 - array($idcol => array('label' => '238949', 'nb_visits' => 0)), //5 - array($idcol => array('label' => 'Q*(%&*', 'nb_visits' => 1)), //6 - array($idcol => array('label' => 'Q*(%&*2', 'nb_visits' => -1.5)), //6 - ); - $table->addRowsFromArray($rows); - - $expectedtable = new DataTable(); - $rows = array( - array($idcol => array('label' => 'google', 'nb_visits' => 897)), //0 - array($idcol => array('label' => 'piwik', 'nb_visits' => 1.5)), //2 - array($idcol => array('label' => 'piwik2', 'nb_visits' => 1.4)), //2 - array($idcol => array('label' => 'yahoo', 'nb_visits' => 154)), //3 - array($idcol => array('label' => 'amazon', 'nb_visits' => 30)), //4 - ); - $expectedtable->addRowsFromArray($rows); - - $filter = new ExcludeLowPopulation($table, 'nb_visits', 1.4); - $filter->filter($table); - - $this->assertTrue(DataTable::isEqual($table, $expectedtable)); - } -} diff --git a/tests/PHPUnit/Core/DataTable/Filter/LimitTest.php b/tests/PHPUnit/Core/DataTable/Filter/LimitTest.php deleted file mode 100644 index 14705926a5..0000000000 --- a/tests/PHPUnit/Core/DataTable/Filter/LimitTest.php +++ /dev/null @@ -1,322 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Filter\Limit; -use Piwik\DataTable; -use Piwik\DataTable\Row; - -class DataTable_Filter_LimitTest extends PHPUnit_Framework_TestCase -{ - /** - * Returns table used for the tests - * - * @return DataTable - */ - protected function getDataTableCount10() - { - $table = new DataTable; - $idcol = Row::COLUMNS; - $rows = array( - array($idcol => array('label' => 'google', 'idRow' => 0)), - array($idcol => array('label' => 'ask', 'idRow' => 1)), - array($idcol => array('label' => 'piwik', 'idRow' => 2)), - array($idcol => array('label' => 'yahoo', 'idRow' => 3)), - array($idcol => array('label' => 'amazon', 'idRow' => 4)), - array($idcol => array('label' => '238949', 'idRow' => 5)), - array($idcol => array('label' => 'test', 'idRow' => 6)), - array($idcol => array('label' => 'amazing', 'idRow' => 7)), - array($idcol => array('label' => 'great', 'idRow' => 8)), - DataTable::ID_SUMMARY_ROW => array($idcol => array('label' => 'summary row', 'idRow' => 9)), - ); - $table->addRowsFromArray($rows); - return $table; - } - - /** - * @group Core - */ - public function testNormal() - { - $offset = 2; - $limit = 3; - $table = $this->getDataTableCount10(); - $filter = new Limit($table, $offset, $limit); - $filter->filter($table); - $this->assertEquals(3, $table->getRowsCount()); - $this->assertEquals(2, $table->getFirstRow()->getColumn('idRow')); - $this->assertEquals(4, $table->getLastRow()->getColumn('idRow')); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * @group Core - */ - public function testLimitLessThanCountShouldReturnCountLimit() - { - $offset = 2; - $limit = 7; - $table = $this->getDataTableCount10(); - $filter = new Limit($table, $offset, $limit); - $filter->filter($table); - $this->assertEquals(7, $table->getRowsCount()); - $this->assertEquals(2, $table->getFirstRow()->getColumn('idRow')); - $this->assertEquals(8, $table->getLastRow()->getColumn('idRow')); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * @group Core - */ - public function testLimitIsCountShouldNotDeleteAnything() - { - $offset = 0; - $limit = 10; - $table = $this->getDataTableCount10(); - $this->assertEquals(10, $table->getRowsCount()); - $filter = new Limit($table, $offset, $limit); - $filter->filter($table); - $this->assertEquals(10, $table->getRowsCount()); - $this->assertEquals(0, $table->getFirstRow()->getColumn('idRow')); - $this->assertEquals(9, $table->getLastRow()->getColumn('idRow')); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * @group Core - */ - public function testLimitGreaterThanCountShouldReturnCountUntilCount() - { - $offset = 5; - $limit = 20; - $table = $this->getDataTableCount10(); - $this->assertEquals(10, $table->getRowsCount()); - $filter = new Limit($table, $offset, $limit); - $filter->filter($table); - $this->assertEquals(5, $table->getRowsCount()); - $this->assertEquals(5, $table->getFirstRow()->getColumn('idRow')); - $this->assertEquals(9, $table->getLastRow()->getColumn('idRow')); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * @group Core - */ - public function testLimitIsNullShouldReturnCountIsOffset() - { - $offset = 1; - $table = $this->getDataTableCount10(); - $filter = new Limit($table, $offset); - $filter->filter($table); - $this->assertEquals(9, $table->getRowsCount()); - $this->assertEquals(1, $table->getFirstRow()->getColumn('idRow')); - $this->assertEquals(9, $table->getLastRow()->getColumn('idRow')); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * @group Core - */ - public function testOffsetJustBeforeSummaryRowShouldJustReturnSummaryRow() - { - $offset = 9; - $limit = 1; - $table = $this->getDataTableCount10(); - $filter = new Limit($table, $offset, $limit); - $filter->filter($table); - $this->assertEquals(1, $table->getRowsCount()); - $this->assertEquals(9, $table->getFirstRow()->getColumn('idRow')); - $this->assertEquals(9, $table->getLastRow()->getColumn('idRow')); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * @group Core - */ - public function testOffsetJustBeforeSummaryRowWithBigLimitShouldJustReturnSummaryRow() - { - $offset = 9; - $limit = 100; - $table = $this->getDataTableCount10(); - $filter = new Limit($table, $offset, $limit); - $filter->filter($table); - $this->assertEquals(1, $table->getRowsCount()); - $this->assertEquals(9, $table->getFirstRow()->getColumn('idRow')); - $this->assertEquals(9, $table->getLastRow()->getColumn('idRow')); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * @group Core - */ - public function testOffsetBeforeSummaryRowShouldJustReturnRowAndSummaryRow() - { - $offset = 8; - $limit = 3; - $table = $this->getDataTableCount10(); - $filter = new Limit($table, $offset, $limit); - $filter->filter($table); - $this->assertEquals(2, $table->getRowsCount()); - $this->assertEquals(8, $table->getFirstRow()->getColumn('idRow')); - $this->assertEquals(9, $table->getLastRow()->getColumn('idRow')); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * @group Core - */ - public function testOffsetGreaterThanCountShouldReturnEmptyTable() - { - $offset = 10; - $limit = 10; - $table = $this->getDataTableCount10(); - $filter = new Limit($table, $offset, $limit); - $filter->filter($table); - $this->assertEquals(0, $table->getRowsCount()); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * @group Core - */ - public function testLimitIsZeroShouldReturnEmptyTable() - { - $offset = 0; - $limit = 0; - $table = $this->getDataTableCount10(); - $filter = new Limit($table, $offset, $limit); - $filter->filter($table); - $this->assertEquals(0, $table->getRowsCount()); - $this->assertEquals(10, $table->getMetadata(DataTable::TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME)); - } - - /** - * Test to filter a table with a offset, limit - * - * @group Core - */ - public function testFilterOffsetLimit() - { - $table = new DataTable; - - $idcol = Row::COLUMNS; - - $rows = array( - array($idcol => array('label' => 'google')), //0 - array($idcol => array('label' => 'ask')), //1 - array($idcol => array('label' => 'piwik')), //2 - array($idcol => array('label' => 'yahoo')), //3 - array($idcol => array('label' => 'amazon')), //4 - array($idcol => array('label' => '238975247578949')), //5 - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))')) //6 - ); - - $table->addRowsFromArray($rows); - - $expectedtable = clone $table; - $expectedtable->deleteRows(array(0, 1, 6)); - - $filter = new Limit($table, 2, 4); - $filter->filter($table); - - $this->assertEquals(array_values($expectedtable->getRows()), array_values($table->getRows())); - } - - /** - * Test to filter a column with a offset, limit off bound - * - * @group Core - */ - public function testFilterOffsetLimitOffbound() - { - $table = new DataTable; - - $idcol = Row::COLUMNS; - - $rows = array( - array($idcol => array('label' => 'google')), //0 - array($idcol => array('label' => 'ask')), //1 - array($idcol => array('label' => 'piwik')), //2 - array($idcol => array('label' => 'yahoo')), //3 - array($idcol => array('label' => 'amazon')), //4 - array($idcol => array('label' => '238975247578949')), //5 - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))')) //6 - ); - - $table->addRowsFromArray($rows); - - $expectedtable = clone $table; - $expectedtable->deleteRows(array(0, 1, 3, 4, 5, 6)); - - $filter = new Limit($table, 2, 1); - $filter->filter($table); - - $this->assertEquals(array_values($expectedtable->getRows()), array_values($table->getRows())); - } - - /** - * Test to filter a column with a offset, limit 2 - * - * @group Core - */ - public function testFilterOffsetLimit2() - { - $table = new DataTable; - - $idcol = Row::COLUMNS; - - $rows = array( - array($idcol => array('label' => 'google')), //0 - array($idcol => array('label' => 'ask')), //1 - array($idcol => array('label' => 'piwik')), //2 - array($idcol => array('label' => 'yahoo')), //3 - array($idcol => array('label' => 'amazon')), //4 - array($idcol => array('label' => '238975247578949')), //5 - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))')) //6 - ); - - $table->addRowsFromArray($rows); - - $expectedtable = clone $table; - - $filter = new Limit($table, 0, 15); - $filter->filter($table); - - $this->assertEquals(array_values($expectedtable->getRows()), array_values($table->getRows())); - } - - /** - * Test to filter a column with a offset, limit 3 - * - * @group Core - */ - public function testFilterOffsetLimit3() - { - $table = new DataTable; - - $idcol = Row::COLUMNS; - - $rows = array( - array($idcol => array('label' => 'google')), //0 - array($idcol => array('label' => 'ask')), //1 - array($idcol => array('label' => 'piwik')), //2 - array($idcol => array('label' => 'yahoo')), //3 - array($idcol => array('label' => 'amazon')), //4 - array($idcol => array('label' => '238975247578949')), //5 - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))')) //6 - ); - - $table->addRowsFromArray($rows); - - $expectedtable = new DataTable; - - $filter = new Limit($table, 8, 15); - $filter->filter($table); - - $this->assertEquals(array_values($expectedtable->getRows()), array_values($table->getRows())); - } - -} diff --git a/tests/PHPUnit/Core/DataTable/Filter/PatternRecursiveTest.php b/tests/PHPUnit/Core/DataTable/Filter/PatternRecursiveTest.php deleted file mode 100644 index 7ab59d8c4a..0000000000 --- a/tests/PHPUnit/Core/DataTable/Filter/PatternRecursiveTest.php +++ /dev/null @@ -1,78 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable; -use Piwik\DataTable\Row; - -class DataTable_Filter_PatternRecursiveTest extends PHPUnit_Framework_TestCase -{ - /** - * Returns a data table for testing - * @return DataTable - */ - protected function getTable() - { - $subtableAskPath1 = new DataTable(); - $subtableAskPath1->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'path1-index-page.html')), - array(Row::COLUMNS => array('label' => 'another-page')), - )); - - $subtableAsk = new DataTable(); - $subtableAsk->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'path1'), - Row::DATATABLE_ASSOCIATED => $subtableAskPath1), - array(Row::COLUMNS => array('label' => 'index.html')), - )); - - $table = new DataTable; - $rows = array( - array(Row::COLUMNS => array('label' => 'http://www.ask.com'), - Row::DATATABLE_ASSOCIATED => $subtableAsk), - array(Row::COLUMNS => array('label' => 'yahoo')), - ); - $table->addRowsFromArray($rows); - return $table; - } - - /** - * Dataprovider for testFilterPattern - */ - public function getTestData() - { - return array( - // level 0 - array(array('hoo', array(1))), - // level 1 - array(array('path1', array(0))), - // level 2 - array(array('path1-index-page', array(0))), - // not found - array(array('not found', array())), - ); - } - - /** - * Test to filter a column with a pattern - * - * @group Core - * @dataProvider getTestData - */ - public function testFilterPattern($test) - { - $table = $this->getTable(); - $rowIds = array_keys($table->getRows()); - $pattern = $test[0]; - $expectedRows = $test[1]; - $rowToDelete = array_diff($rowIds, $expectedRows); - $expectedtable = clone $table; - $expectedtable->deleteRows($rowToDelete); - $filteredTable = clone $table; - $filteredTable->filter('PatternRecursive', array('label', $pattern)); - $this->assertEquals($expectedtable->getRows(), $filteredTable->getRows()); - } -} diff --git a/tests/PHPUnit/Core/DataTable/Filter/PatternTest.php b/tests/PHPUnit/Core/DataTable/Filter/PatternTest.php deleted file mode 100644 index 1f1c25bc61..0000000000 --- a/tests/PHPUnit/Core/DataTable/Filter/PatternTest.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable; -use Piwik\DataTable\Row; - -class DataTable_Filter_PatternTest extends PHPUnit_Framework_TestCase -{ - /** - * Dataprovider for testFilterPattern - */ - public function getTestData() - { - return array( - array(array('ask', array(1))), - array(array('oo', array(0, 3))), - array(array('^yah', array(3))), - array(array('\*', array(6))), - array(array('2/4', array(5))), - array(array('amazon|yahoo', array(3, 4))), - ); - } - - /** - * Test to filter a column with a pattern - * - * @group Core - * _Pattern - * @dataProvider getTestData - */ - public function testFilterPattern($test) - { - $table = new DataTable; - - $idcol = Row::COLUMNS; - - $rows = array( - array($idcol => array('label' => 'google')), - array($idcol => array('label' => 'ask')), - array($idcol => array('label' => 'piwik')), - array($idcol => array('label' => 'yahoo')), - array(Row::METADATA => array('label' => 'amazon')), - array($idcol => array('label' => '2389752/47578949')), - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))')) - ); - $table->addRowsFromArray($rows); - $rowIds = array_keys($rows); - - $pattern = $test[0]; - $expectedRows = $test[1]; - $rowToDelete = array_diff($rowIds, $expectedRows); - $expectedtable = clone $table; - $expectedtable->deleteRows($rowToDelete); - $filteredTable = clone $table; - $filteredTable->filter('Pattern', array('label', $pattern)); - $this->assertEquals($expectedtable->getRows(), $filteredTable->getRows()); - } -} diff --git a/tests/PHPUnit/Core/DataTable/Filter/PivotByDimensionTest.php b/tests/PHPUnit/Core/DataTable/Filter/PivotByDimensionTest.php deleted file mode 100644 index 80162b362f..0000000000 --- a/tests/PHPUnit/Core/DataTable/Filter/PivotByDimensionTest.php +++ /dev/null @@ -1,389 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -namespace Piwik\Tests\Core\DataTable\Filter; - -use Piwik\API\Proxy; -use Piwik\Config; -use Piwik\DataTable; -use Piwik\DataTable\Filter\PivotByDimension; -use Piwik\DataTable\Row; -use Piwik\Plugin\Manager as PluginManager; -use PHPUnit_Framework_TestCase; -use Exception; - -/** - * @group Core - */ -class PivotByDimensionTest extends PHPUnit_Framework_TestCase -{ - /** - * The number of segment tables that have been created. Used when injecting API results to make sure each - * segment table is different. - * - * @var int - */ - private $segmentTableCount; - - /** - * Segment query params used to fetch intersected tables in PivotByDimension filter. Captured by mock - * API\Proxy class. - * - * @var array - */ - public $segmentUsedToGetIntersected = array(); - - public function setUp() - { - $self = $this; - - $proxyMock = $this->getMock('stdClass', array('call')); - $proxyMock->expects($this->any())->method('call')->willReturnCallback(function ($className, $methodName, $parameters) use ($self) { - if ($className == "\\Piwik\\Plugins\\UserCountry\\API" - && $methodName == 'getCity' - ) { - $self->segmentUsedToGetIntersected[] = $parameters['segment']; - - return $self->getSegmentTable(); - } else { - throw new Exception("Unknown API request: $className::$methodName."); - } - }); - Proxy::setSingletonInstance($proxyMock); - - $this->segmentTableCount = 0; - - Config::getInstance()->setTestEnvironment(); - } - - public function tearDown() - { - PluginManager::unsetInstance(); - Proxy::unsetInstance(); - } - - /** - * @expectedException Exception - * @expectedExceptionMessage Unsupported pivot: report 'ExampleReport.ExampleReportName' has no subtable dimension. - */ - public function test_construction_ShouldFail_WhenReportHasNoSubtableAndSegmentFetchingIsDisabled() - { - $this->loadPlugins('ExampleReport', 'UserCountry'); - - new PivotByDimension(new DataTable(), "ExampleReport.GetExampleReport", "UserCountry.City", 'nb_visits', $columnLimit = -1, $enableFetchBySegment = false); - } - - /** - * @expectedException Exception - * @expectedExceptionMessage Unsupported pivot: the subtable dimension for 'Referrers.Referrers_Keywords' does not match the requested pivotBy dimension. - */ - public function test_construction_ShouldFail_WhenDimensionIsNotSubtableAndSegmentFetchingIsDisabled() - { - $this->loadPlugins('Referrers', 'UserCountry'); - - new PivotByDimension(new DataTable(), "Referrers.getKeywords", "UserCountry.City", "nb_visits", $columnLimit = -1, $enableFetchBySegment = false); - } - - /** - * @expectedException Exception - * @expectedExceptionMessage Unsupported pivot: No segment for dimension of report 'UserSettings.UserSettings_WidgetBrowserFamilies' - */ - public function test_construction_ShouldFail_WhenDimensionIsNotSubtableAndSegmentFetchingIsEnabledButThereIsNoSegment() - { - $this->loadPlugins('Referrers', 'UserSettings'); - - new PivotByDimension(new DataTable(), "UserSettings.getBrowserType", "Referrers.Keyword", "nb_visits"); - } - - /** - * @expectedException Exception - * @expectedExceptionMessage Invalid dimension 'ExampleTracker.InvalidDimension' - */ - public function test_construction_ShouldFail_WhenDimensionDoesNotExist() - { - $this->loadPlugins('ExampleReport', 'ExampleTracker'); - - new PivotByDimension(new DataTable(), "ExampleReport.GetExampleReport", "ExampleTracker.InvalidDimension", 'nb_visits'); - } - - /** - * @expectedException Exception - * @expectedExceptionMessage Unsupported pivot: No report for pivot dimension 'ExampleTracker.ExampleDimension' - */ - public function test_construction_ShouldFail_WhenThereIsNoReportForADimension() - { - $this->loadPlugins('ExampleReport', 'ExampleTracker'); - - new PivotByDimension(new DataTable(), "ExampleReport.GetExampleReport", "ExampleTracker.ExampleDimension", "nb_visits"); - } - - /** - * @expectedException Exception - * @expectedExceptionMessage Unable to find report 'ExampleReport.InvalidReport' - */ - public function test_construction_ShouldFail_WhenSpecifiedReportIsNotValid() - { - $this->loadPlugins('ExampleReport', 'Referrers'); - - new PivotByDimension(new DataTable(), "ExampleReport.InvalidReport", "Referrers.Keyword", "nb_visits"); - } - - public function test_filter_ReturnsEmptyResult_WhenTableToFilterIsEmpty() - { - $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); - - $table = new DataTable(); - - $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", 'nb_visits'); - $pivotFilter->filter($table); - - $this->assertEquals(array(), $table->getRows()); - } - - public function test_filter_CorrectlyCreatesPivotTable_WhenUsingSubtableReport() - { - $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); - - $table = $this->getTableToFilter(true); - - $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", 'nb_actions', $columnLimit = -1, $fetchBySegment = false); - $pivotFilter->filter($table); - - $expectedRows = array( - array('label' => 'row 1', 'col 1' => 2, 'col 2' => false, 'col 3' => false, 'col 4' => false), - array('label' => 'row 2', 'col 1' => 4, 'col 2' => 6, 'col 3' => false, 'col 4' => false), - array('label' => 'row 3', 'col 1' => false, 'col 2' => 8, 'col 3' => 31, 'col 4' => 33) - ); - $this->assertTableRowsEquals($expectedRows, $table); - } - - public function test_filter_CorrectlyCreatesPivotTable_WhenUsingSegment() - { - $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); - - $table = $this->getTableToFilter(true); - - $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "UserCountry.City", 'nb_visits'); - $pivotFilter->filter($table); - - $expectedSegmentParams = array('referrerKeyword==row+1', 'referrerKeyword==row+2', 'referrerKeyword==row+3'); - $this->assertEquals($expectedSegmentParams, $this->segmentUsedToGetIntersected); - - $expectedRows = array( - array('label' => 'row 1', 'col 0' => 2, 'col 1' => false, 'col 2' => false), - array('label' => 'row 2', 'col 0' => 2, 'col 1' => 4, 'col 2' => false), - array('label' => 'row 3', 'col 0' => 2, 'col 1' => 4, 'col 2' => 6) - ); - $this->assertTableRowsEquals($expectedRows, $table); - } - - public function test_filter_UsesCorrectSegment_WhenPivotingSegmentedReport() - { - $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); - - $table = $this->getTableToFilter(true); - - $_GET['segment'] = 'asegment==value'; - - $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "UserCountry.City", 'nb_visits'); - $pivotFilter->filter($table); - - $expectedSegmentParams = array( - 'asegment==value;referrerKeyword==row+1', - 'asegment==value;referrerKeyword==row+2', - 'asegment==value;referrerKeyword==row+3' - ); - $this->assertEquals($expectedSegmentParams, $this->segmentUsedToGetIntersected); - } - - public function test_filter_CorrectlyCreatesPivotTable_WhenPivotMetricDoesNotExistInTable() - { - $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); - - $table = $this->getTableToFilter(true); - - $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", 'invalid_metric'); - $pivotFilter->filter($table); - - $expectedRows = array( - array('label' => 'row 1', 'col 1' => false, 'col 2' => false, 'col 3' => false, 'col 4' => false), - array('label' => 'row 2', 'col 1' => false, 'col 2' => false, 'col 3' => false, 'col 4' => false), - array('label' => 'row 3', 'col 1' => false, 'col 2' => false, 'col 3' => false, 'col 4' => false) - ); - $this->assertTableRowsEquals($expectedRows, $table); - } - - public function test_filter_CorrectlyCreatesPivotTable_WhenSubtablesHaveNoRows() - { - $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); - - $table = $this->getTableToFilter(false); - - $pivotFilter = new PivotByDimension($table, "CustomVariables.getCustomVariables", "CustomVariables.CustomVariableValue", - 'nb_visits', $fetchBySegment = false); - $pivotFilter->filter($table); - - $expectedRows = array( - array('label' => 'row 1'), - array('label' => 'row 2'), - array('label' => 'row 3') - ); - $this->assertTableRowsEquals($expectedRows, $table); - } - - public function test_filter_CorrectlyDefaultsPivotByColumn_WhenNoneProvided() - { - $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); - - $table = $this->getTableToFilter(true); - - $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", $column = false, $columnLimit = -1, $fetchBySegment = false); - $pivotFilter->filter($table); - - $expectedRows = array( - array('label' => 'row 1', 'col 1' => 1, 'col 2' => false, 'col 3' => false, 'col 4' => false), - array('label' => 'row 2', 'col 1' => 3, 'col 2' => 5, 'col 3' => false, 'col 4' => false), - array('label' => 'row 3', 'col 1' => false, 'col 2' => 7, 'col 3' => 9, 'col 4' => 32) - ); - $this->assertTableRowsEquals($expectedRows, $table); - } - - public function test_filter_CorrectlyLimitsTheColumnNumber_WhenColumnLimitProvided() - { - $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); - - $table = $this->getTableToFilter(true); - - $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", $column = 'nb_visits', $columnLimit = 3, $fetchBySegment = false); - $pivotFilter->filter($table); - - $expectedRows = array( - array('label' => 'row 1', 'col 2' => false, 'col 4' => false, 'General_Others' => 1), - array('label' => 'row 2', 'col 2' => 5, 'col 4' => false, 'General_Others' => 3), - array('label' => 'row 3', 'col 2' => 7, 'col 4' => 32, 'General_Others' => 9) - ); - $this->assertTableRowsEquals($expectedRows, $table); - } - - private function getTableToFilter($addSubtables = false) - { - $row1 = new Row(array(Row::COLUMNS => array( - 'label' => 'row 1', - 'nb_visits' => 10, - 'nb_actions' => 15 - ))); - if ($addSubtables) { - $row1->setSubtable($this->getRow1Subtable()); - } - - $row2 = new Row(array(Row::COLUMNS => array( - 'label' => 'row 2', - 'nb_visits' => 13, - 'nb_actions' => 18 - ))); - if ($addSubtables) { - $row2->setSubtable($this->getRow2Subtable()); - } - - $row3 = new Row(array(Row::COLUMNS => array( - 'label' => 'row 3', - 'nb_visits' => 20, - 'nb_actions' => 25 - ))); - if ($addSubtables) { - $row3->setSubtable($this->getRow3Subtable()); - } - - $table = new DataTable(); - $table->addRowsFromArray(array($row1, $row2, $row3)); - return $table; - } - - private function getRow1Subtable() - { - $table = new DataTable(); - $table->addRowsFromArray(array( - new Row(array(Row::COLUMNS => array( - 'label' => 'col 1', - 'nb_visits' => 1, - 'nb_actions' => 2 - ))) - )); - return $table; - } - - private function getRow2Subtable() - { - $table = new DataTable(); - $table->addRowsFromArray(array( - new Row(array(Row::COLUMNS => array( - 'label' => 'col 1', - 'nb_visits' => 3, - 'nb_actions' => 4 - ))), - new Row(array(Row::COLUMNS => array( - 'label' => 'col 2', - 'nb_visits' => 5, - 'nb_actions' => 6 - ))) - )); - return $table; - } - - private function getRow3Subtable() - { - $table = new DataTable(); - $table->addRowsFromArray(array( - new Row(array(Row::COLUMNS => array( - 'label' => 'col 2', - 'nb_visits' => 7, - 'nb_actions' => 8 - ))), - new Row(array(Row::COLUMNS => array( - 'label' => 'col 3', - 'nb_visits' => 9, - 'nb_actions' => 31 - ))), - new Row(array(Row::COLUMNS => array( - 'label' => 'col 4', - 'nb_visits' => 32, - 'nb_actions' => 33 - ))) - )); - return $table; - } - - public function getSegmentTable() - { - ++$this->segmentTableCount; - - $table = new DataTable(); - for ($i = 0; $i != $this->segmentTableCount; ++$i) { - $row = new Row(array(Row::COLUMNS => array( - 'label' => 'col ' . $i, - 'nb_visits' => ($i + 1) * 2, - 'nb_actions' => ($i + 1) * 3 - ))); - $table->addRow($row); - } - return $table; - } - - private function assertTableRowsEquals($expectedRows, $table) - { - $renderer = new DataTable\Renderer\Php(); - $renderer->setSerialize(false); - $actualRows = $renderer->render($table); - - $this->assertEquals($expectedRows, $actualRows); - } - - private function loadPlugins() - { - PluginManager::getInstance()->loadPlugins(func_get_args()); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/DataTable/Filter/RangeCheckTest.php b/tests/PHPUnit/Core/DataTable/Filter/RangeCheckTest.php deleted file mode 100644 index e9140c3aed..0000000000 --- a/tests/PHPUnit/Core/DataTable/Filter/RangeCheckTest.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Filter\RangeCheck; -use Piwik\DataTable; -use Piwik\DataTable\Row; - -class DataTable_Filter_RangeCheckTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testRangeCheckNormalDataTable() - { - $table = new DataTable(); - $table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'ask', 'count' => 3)), // --> 5 - array(Row::COLUMNS => array('label' => 'nintendo', 'count' => 5)), // --> 5 - array(Row::COLUMNS => array('label' => 'test', 'count' => 7.5)), // --> 7.5 - array(Row::COLUMNS => array('label' => 'google', 'count' => 9)), // --> 9 - array(Row::COLUMNS => array('label' => 'yahoo', 'count' => 10.1) // --> 10 - ))); - $filter = new RangeCheck($table, 'count', 5, 10); - $filter->filter($table); - $expectedOrder = array(5, 5, 7.5, 9, 10); - - $this->assertEquals($expectedOrder, $table->getColumn('count')); - } - - /** - * @group Core - */ - public function testRangeCheckNormalDataTableNonIntegerValues() - { - $table = new DataTable(); - $table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'ask', 'count' => '3')), // 3 is below minimum - array(Row::COLUMNS => array('label' => 'nintendo', 'count' => 'test')), // no number is below minimum - array(Row::COLUMNS => array('label' => 'test', 'count' => 0x1232)), // number is over maximum - array(Row::COLUMNS => array('label' => 'piwik', 'count' => 0x005)), // converted to 5 is ok - array(Row::COLUMNS => array('label' => 'google', 'count' => '9test')), // converted to 9 is ok, so string will be kept - array(Row::COLUMNS => array('label' => 'yahoo', 'count' => 'test4') // can't be converted to number - ))); - $filter = new RangeCheck($table, 'count', 3.97, 10); - $filter->filter($table); - $expectedOrder = array(3.97, 3.97, 10, 5, '9test', 3.97); - - $this->assertEquals($expectedOrder, $table->getColumn('count')); - } -} diff --git a/tests/PHPUnit/Core/DataTable/Filter/SortTest.php b/tests/PHPUnit/Core/DataTable/Filter/SortTest.php deleted file mode 100644 index bf23dbd7dc..0000000000 --- a/tests/PHPUnit/Core/DataTable/Filter/SortTest.php +++ /dev/null @@ -1,169 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Filter\Sort; -use Piwik\DataTable; -use Piwik\DataTable\Row; - -class DataTable_Filter_SortTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testNormalSortDescending() - { - $table = new DataTable(); - $table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'ask', 'count' => 100)), - array(Row::COLUMNS => array('label' => 'nintendo', 'count' => 0)), - array(Row::COLUMNS => array('label' => 'yahoo', 'count' => 10) - ))); - $filter = new Sort($table, 'count', 'desc'); - $filter->filter($table); - $expectedOrder = array('ask', 'yahoo', 'nintendo'); - $this->assertEquals($expectedOrder, $table->getColumn('label')); - } - - /** - * @group Core - */ - public function testNormalSortAscending() - { - $table = new DataTable(); - $table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'ask', 'count' => 100.5)), - array(Row::COLUMNS => array('label' => 'nintendo', 'count' => 0.5)), - array(Row::COLUMNS => array('label' => 'yahoo', 'count' => 10.5) - ))); - $filter = new Sort($table, 'count', 'asc'); - $filter->filter($table); - $expectedOrder = array('nintendo', 'yahoo', 'ask'); - $this->assertEquals($expectedOrder, $table->getColumn('label')); - } - - /** - * @group Core - */ - public function testMissingColumnValuesShouldAppearLastAfterSortAsc() - { - $table = new DataTable(); - $table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'nintendo', 'count' => 1)), - array(Row::COLUMNS => array('label' => 'nocolumn')), - array(Row::COLUMNS => array('label' => 'nocolumnbis')), - array(Row::COLUMNS => array('label' => 'ask', 'count' => 2)), - array(Row::COLUMNS => array('label' => 'amazing')), - DataTable::ID_SUMMARY_ROW => array(Row::COLUMNS => array('label' => 'summary', 'count' => 10) - ))); - $filter = new Sort($table, 'count', 'asc'); - $filter->filter($table); - $expectedOrder = array('nintendo', 'ask', 'amazing', 'nocolumnbis', 'nocolumn', 'summary'); - $this->assertEquals($expectedOrder, $table->getColumn('label')); - } - - /** - * @group Core - */ - public function testMissingColumnValuesShouldAppearLastAfterSortDesc() - { - $table = new DataTable(); - $table->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'nintendo', 'count' => 1)), - array(Row::COLUMNS => array('label' => 'ask', 'count' => 2)), - array(Row::COLUMNS => array('label' => 'amazing')), - DataTable::ID_SUMMARY_ROW => array(Row::COLUMNS => array('label' => 'summary', 'count' => 10) - ))); - $filter = new Sort($table, 'count', 'desc'); - $filter->filter($table); - $expectedOrder = array('ask', 'nintendo', 'amazing', 'summary'); - $this->assertEquals($expectedOrder, $table->getColumn('label')); - } - - /** - * Test to sort by label - * - * @group Core - */ - public function testFilterSortString() - { - $idcol = Row::COLUMNS; - $table = new DataTable(); - $rows = array( - array($idcol => array('label' => 'google')), //0 - array($idcol => array('label' => 'ask')), //1 - array($idcol => array('label' => 'piwik')), //2 - array($idcol => array('label' => 'yahoo')), //3 - array($idcol => array('label' => 'amazon')), //4 - array($idcol => array('label' => '238975247578949')), //5 - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))')) //6 - ); - $table->addRowsFromArray($rows); - $expectedtable = new DataTable(); - $rows = array( - array($idcol => array('label' => '238975247578949')), //5 - array($idcol => array('label' => 'amazon')), //4 - array($idcol => array('label' => 'ask')), //1 - array($idcol => array('label' => 'google')), //0 - array($idcol => array('label' => 'piwik')), //2 - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))')), //6 - array($idcol => array('label' => 'yahoo')) //3 - ); - $expectedtable->addRowsFromArray($rows); - $expectedtableReverse = new DataTable(); - $expectedtableReverse->addRowsFromArray(array_reverse($rows)); - - $filter = new Sort($table, 'label', 'asc'); - $filter->filter($table); - $this->assertTrue(DataTable::isEqual($expectedtable, $table)); - - $filter = new Sort($table, 'label', 'desc'); - $filter->filter($table); - $this->assertTrue(DataTable::isEqual($table, $expectedtableReverse)); - } - - /** - * Test to sort by visit - * - * @group Core - */ - public function testFilterSortNumeric() - { - $idcol = Row::COLUMNS; - $table = new DataTable(); - $rows = array( - array($idcol => array('label' => 'google', 'nb_visits' => 897)), //0 - array($idcol => array('label' => 'ask', 'nb_visits' => -152)), //1 - array($idcol => array('label' => 'piwik', 'nb_visits' => 1.5)), //2 - array($idcol => array('label' => 'yahoo', 'nb_visits' => 154)), //3 - array($idcol => array('label' => 'amazon', 'nb_visits' => 30)), //4 - array($idcol => array('label' => '238949', 'nb_visits' => 0)), //5 - array($idcol => array('label' => 'Q*(%&*', 'nb_visits' => 1)) //6 - ); - $table->addRowsFromArray($rows); - $expectedtable = new DataTable(); - $rows = array( - array($idcol => array('label' => 'ask', 'nb_visits' => -152)), //1 - array($idcol => array('label' => '238949', 'nb_visits' => 0)), //5 - array($idcol => array('label' => 'Q*(%&*', 'nb_visits' => 1)), //6 - array($idcol => array('label' => 'piwik', 'nb_visits' => 1.5)), //2 - array($idcol => array('label' => 'amazon', 'nb_visits' => 30)), //4 - array($idcol => array('label' => 'yahoo', 'nb_visits' => 154)), //3 - array($idcol => array('label' => 'google', 'nb_visits' => 897)) //0 - ); - $expectedtable->addRowsFromArray($rows); - $expectedtableReverse = new DataTable(); - $expectedtableReverse->addRowsFromArray(array_reverse($rows)); - - $filter = new Sort($table, 'nb_visits', 'asc'); - $filter->filter($table); - $this->assertTrue(DataTable::isEqual($table, $expectedtable)); - - $filter = new Sort($table, 'nb_visits', 'desc'); - $filter->filter($table); - $this->assertTrue(DataTable::isEqual($table, $expectedtableReverse)); - } -} diff --git a/tests/PHPUnit/Core/DataTable/Filter/TruncateTest.php b/tests/PHPUnit/Core/DataTable/Filter/TruncateTest.php deleted file mode 100644 index 2cb53e701f..0000000000 --- a/tests/PHPUnit/Core/DataTable/Filter/TruncateTest.php +++ /dev/null @@ -1,228 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Filter\Truncate; -use Piwik\DataTable; -use Piwik\DataTable\Row; - -class DataTable_Filter_TruncateTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testUnrelatedDataTableNotFiltered() - { - // remark: this unit test would become invalid and would need to be rewritten if - // Truncate filter stops calling getRowsCount() on the DataTable being filtered. - $mockedDataTable = $this->getMock('\Piwik\DataTable', array('getRowsCount')); - $mockedDataTable->expects($this->never())->method('getRowsCount'); - - $dataTableBeingFiltered = new DataTable(); - $rowBeingFiltered = new Row(); - $dataTableBeingFiltered->addRow($rowBeingFiltered); - - // we simulate the fact that the value of Row::DATATABLE_ASSOCIATED retrieved - // from the database is in conflict with one of the Manager managed table identifiers. - // This is a rare but legitimate case as identifiers are not thoroughly synchronized - // when the expanded parameter is false. - $rowBeingFiltered->c[Row::DATATABLE_ASSOCIATED] = $mockedDataTable->getId(); - - $filter = new Truncate($dataTableBeingFiltered, 1); - $filter->filter($dataTableBeingFiltered); - } - - /** - * @group Core - */ - public function testForInfiniteRecursion() - { - $dataTableBeingFiltered = new DataTable(); - - // remark: this unit test would become invalid and would need to be rewritten if - // Truncate filter stops calling getIdSubDataTable() on rows associated with a SubDataTable - $rowBeingFiltered = $this->getMock('\Piwik\DataTable\Row', array('getIdSubDataTable')); - $rowBeingFiltered->expects($this->never())->method('getIdSubDataTable'); - - $dataTableBeingFiltered->addRow($rowBeingFiltered); - - // we simulate a legitimate but rare circular reference between a Row and its - // enclosing DataTable. - // This can happen because identifiers are not thoroughly synchronized when the expanded parameter - // is false. - $rowBeingFiltered->c[Row::DATATABLE_ASSOCIATED] = $dataTableBeingFiltered->getId(); - - $filter = new Truncate($dataTableBeingFiltered, 1); - $filter->filter($dataTableBeingFiltered); - } - - /** - * @group Core - */ - public function testOffsetIsCountSummaryRowShouldBeTheRow() - { - $table = $this->getDataTableCount5(); - $filter = new Truncate($table, 5); - $filter->filter($table); - $this->assertEquals(5, $table->getRowsCount()); - $this->assertTrue(Row::isEqual($table->getLastRow(), $this->getRow4())); - } - - /** - * @group Core - */ - public function testOffsetIsLessThanCountSummaryRowShouldBeTheSum() - { - $table = $this->getDataTableCount5(); - $filter = new Truncate($table, 2); - $filter->filter($table); - $this->assertEquals(3, $table->getRowsCount()); - $expectedRow = new Row(array(Row::COLUMNS => array('label' => DataTable::LABEL_SUMMARY_ROW, 'nb' => 111))); - $this->assertTrue(Row::isEqual($table->getLastRow(), $expectedRow)); - // check that column 'label' is forced to be first in summary row - $this->assertEquals(array_keys($table->getLastRow()->getColumns()), array_keys($expectedRow->getColumns())); - } - - /** - * @group Core - */ - public function testOffsetIsMoreThanCountShouldNotTruncate() - { - $table = $this->getDataTableCount5(); - $filter = new Truncate($table, 6); - $filter->filter($table); - $this->assertEquals(5, $table->getRowsCount()); - $this->assertTrue(Row::isEqual($table->getLastRow(), $this->getRow4())); - } - - /** - * @group Core - */ - public function testWhenThereIsAlreadyASummaryRowShouldReplaceTheSummaryRow() - { - $table = $this->getDataTableCount5(); - $filter1 = new Truncate($table, 3); - $filter1->filter($table); - $filter2 = new Truncate($table, 2); - $filter2->filter($table); - $this->assertEquals(3, $table->getRowsCount()); - $expectedRow = new Row(array(Row::COLUMNS => array('label' => DataTable::LABEL_SUMMARY_ROW, 'nb' => 111))); - $this->assertTrue(Row::isEqual($table->getLastRow(), $expectedRow)); - } - - /** - * @group Core - */ - public function testSumTablesWithSummaryRowShouldSumTheSummaryRow() - { - // row0, row1, row2, rowSummary1 - $table1 = $this->getDataTableCount5(); - $filter = new Truncate($table1, 3); - $filter->filter($table1); - - // row0, row1, rowSummary2 - $table2 = $this->getDataTableCount5(); - $filter = new Truncate($table2, 2); - $filter->filter($table2); - - // we expect row0+row0, row1+row1, row2, rowSummary1+rowSummary2 - $expectedTable = new DataTable; - $expectedTable->addRow(new Row(array(Row::COLUMNS => array('label' => 'amazon', 'nb' => 20000)))); - $expectedTable->addRow(new Row(array(Row::COLUMNS => array('label' => 'yahoo', 'nb' => 2000)))); - $expectedTable->addRow(new Row(array(Row::COLUMNS => array('label' => 'piwik', 'nb' => 100)))); - $expectedTable->addRow(new Row(array(Row::COLUMNS => array('label' => DataTable::LABEL_SUMMARY_ROW, 'nb' => 122)))); - - $table1->addDataTable($table2); - $this->assertTrue(DataTable::isEqual($expectedTable, $table1)); - } - - /** - * @group Core - */ - public function testAddOneTableWithSummaryRow() - { - // row0, row1, row2, rowSummary1 - $table1 = $this->getDataTableCount5(); - $filter = new Truncate($table1, 3); - $filter->filter($table1); - - // row0, row1, row2, row3, row4 - $table2 = $this->getDataTableCount5(); - - // we expect row0+row0, row1+row1, row2+row2, row3, row4, rowSummary1 - $expectedTable = new DataTable; - $expectedTable->addRow(new Row(array(Row::COLUMNS => array('label' => 'amazon', 'nb' => 20000)))); - $expectedTable->addRow(new Row(array(Row::COLUMNS => array('label' => 'yahoo', 'nb' => 2000)))); - $expectedTable->addRow(new Row(array(Row::COLUMNS => array('label' => 'piwik', 'nb' => 200)))); - $expectedTable->addRow($this->getRow3()); - $expectedTable->addRow($this->getRow4()); - $expectedTable->addRow(new Row(array(Row::COLUMNS => array('label' => DataTable::LABEL_SUMMARY_ROW, 'nb' => 11)))); - - $table1->addDataTable($table2); - $this->assertTrue(DataTable::isEqual($expectedTable, $table1)); - - } - - /** - * @group Core - */ - public function testWhenRowsInRandomOrderButSortSpecifiedShouldComputeSummaryRowAfterSort() - { - $table = new DataTable; - $table->addRow($this->getRow3()); - $table->addRow($this->getRow2()); - $table->addRow($this->getRow4()); - $table->addRow($this->getRow1()); - $table->addRow($this->getRow0()); - - $filter = new Truncate($table, 2, DataTable::LABEL_SUMMARY_ROW, $columnToSortBy = 'nb'); - $filter->filter($table); - $this->assertEquals(3, $table->getRowsCount()); - $expectedRow = new Row(array(Row::COLUMNS => array('label' => DataTable::LABEL_SUMMARY_ROW, 'nb' => 111))); - $this->assertTrue(Row::isEqual($table->getLastRow(), $expectedRow)); - } - - /** - * Returns table used for the tests - * - * @return DataTable - */ - protected function getDataTableCount5() - { - $table = new DataTable; - $table->addRow($this->getRow0()); - $table->addRow($this->getRow1()); - $table->addRow($this->getRow2()); - $table->addRow($this->getRow3()); - $table->addRow($this->getRow4()); - return $table; - } - - protected function getRow0() - { - return new Row(array(Row::COLUMNS => array('nb' => 10000, 'label' => 'amazon'))); - } - - protected function getRow1() - { - return new Row(array(Row::COLUMNS => array('label' => 'yahoo', 'nb' => 1000))); - } - - protected function getRow2() - { - return new Row(array(Row::COLUMNS => array('label' => 'piwik', 'nb' => 100))); - } - - protected function getRow3() - { - return new Row(array(Row::COLUMNS => array('label' => 'ask', 'nb' => 10))); - } - - protected function getRow4() - { - return new Row(array(Row::COLUMNS => array('nb' => 1, 'label' => 'google'))); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/DataTable/MapTest.php b/tests/PHPUnit/Core/DataTable/MapTest.php deleted file mode 100644 index de08a14787..0000000000 --- a/tests/PHPUnit/Core/DataTable/MapTest.php +++ /dev/null @@ -1,123 +0,0 @@ -<?php -use Piwik\Config; -use Piwik\DataTable\Manager; -use Piwik\DataTable; -use Piwik\DataTable\Row; - -class Test_DataTable_Map extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - parent::setUp(); - Config::getInstance()->setTestEnvironment(); - Manager::getInstance()->deleteAll(); - } - - private function createTestDataTable() - { - $result = new DataTable(); - - $result->addRowsFromArray(array( - array(Row::COLUMNS => array('label' => 'row1', 'col1' => 1)), - array(Row::COLUMNS => array('label' => 'row2', 'col1' => 2)) - )); - - return $result; - } - - private function createInstanceWithDataTables() - { - $dataTable = new DataTable\Map(); - - $subDataTable1 = $this->createTestDataTable(); - $dataTable->addTable($subDataTable1, 'subDataTable1'); - - $subDataTable2 = $this->createTestDataTable(); - $dataTable->addTable($subDataTable2, 'subDataTable2'); - - return $dataTable; - } - - private function createInstanceWithDataTableMaps() - { - $dataTable = new DataTable\Map(); - - $subDataTableMap1 = $this->createInstanceWithDataTables(); - $dataTable->addTable($subDataTableMap1, 'subArray1'); - - $subDataTableMap2 = $this->createInstanceWithDataTables(); - $dataTable->addTable($subDataTableMap2, 'subArray2'); - - return $dataTable; - } - - /** - * Tests that Set::mergeChildren works when the DataTable\Map contains DataTables. - * @group Core - */ - public function test_MergeChildrenDataTable() - { - $dataTable = $this->createInstanceWithDataTables(); - - $result = $dataTable->mergeChildren(); - - // check that the result is a DataTable w/ 4 rows - $this->assertInstanceOf('\Piwik\DataTable', $result); - $this->assertEquals(4, $result->getRowsCount()); - - // check that the first two rows have 'subDataTable1' as the label - $this->mergeChildren_checkRow($result->getRowFromId(0), 'subDataTable1', 1); - $this->mergeChildren_checkRow($result->getRowFromId(1), 'subDataTable1', 2); - - // check that the last two rows have 'subDataTable2' as the label - $this->mergeChildren_checkRow($result->getRowFromId(2), 'subDataTable2', 1); - $this->mergeChildren_checkRow($result->getRowFromId(3), 'subDataTable2', 2); - } - - private function mergeChildren_checkRow($row, $expectedLabel, $expectedColumnValue) - { - $this->assertEquals($expectedLabel, $row->getColumn('label')); - $this->assertEquals($expectedColumnValue, $row->getColumn('col1')); - } - - /** - * Tests that Set::mergeChildren works when the DataTable\Map contains DataTable\Maps. - * @group Core - */ - public function testMergeChildrenDataTableMap() - { - $dataTable = $this->createInstanceWithDataTableMaps(); - - $result = $dataTable->mergeChildren(); - - // check that the result is a DataTable\Map w/ two DataTable children - $this->assertInstanceOf('\Piwik\DataTable\Map', $result); - $this->assertEquals(2, $result->getRowsCount()); - - // check that the first sub-DataTable is a DataTable with 4 rows - $subDataTable1 = $result->getTable('subDataTable1'); - $this->assertTrue($subDataTable1 instanceof DataTable); - $this->assertEquals(4, $subDataTable1->getRowsCount()); - - // check that the first two rows of the first sub-table have 'subArray1' as the label - $this->mergeChildren_checkRow($subDataTable1->getRowFromId(0), 'subArray1', 1); - $this->mergeChildren_checkRow($subDataTable1->getRowFromId(1), 'subArray1', 2); - - // check that the last two rows of the first sub-table have 'subArray2' as the label - $this->mergeChildren_checkRow($subDataTable1->getRowFromId(2), 'subArray2', 1); - $this->mergeChildren_checkRow($subDataTable1->getRowFromId(3), 'subArray2', 2); - - // check that the second sub-DataTable is a DataTable with 4 rows - $subDataTable2 = $result->getTable('subDataTable2'); - $this->assertTrue($subDataTable2 instanceof DataTable); - $this->assertEquals(4, $subDataTable2->getRowsCount()); - - // check that the first two rows of the second sub-table have 'subArray1' as the label - $this->mergeChildren_checkRow($subDataTable2->getRowFromId(0), 'subArray1', 1); - $this->mergeChildren_checkRow($subDataTable2->getRowFromId(1), 'subArray1', 2); - - // check that the last two rows of the second sub-table have 'subArray2' as the label - $this->mergeChildren_checkRow($subDataTable2->getRowFromId(2), 'subArray2', 1); - $this->mergeChildren_checkRow($subDataTable2->getRowFromId(3), 'subArray2', 2); - } -} diff --git a/tests/PHPUnit/Core/DataTable/Renderer/CSVTest.php b/tests/PHPUnit/Core/DataTable/Renderer/CSVTest.php deleted file mode 100644 index 64ffcf6a06..0000000000 --- a/tests/PHPUnit/Core/DataTable/Renderer/CSVTest.php +++ /dev/null @@ -1,468 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Manager; -use Piwik\DataTable; -use Piwik\DataTable\Renderer\Csv; -use Piwik\DataTable\Row; -use Piwik\DataTable\Simple; - -class DataTable_Renderer_CSVTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - parent::setUp(); - Manager::getInstance()->deleteAll(); - } - - /** - * DATA TESTS - * ----------------------- - * for each renderer we test the case - * - datatableSimple - * - normal datatable with 2 row (including columns and metadata) - */ - protected function _getDataTableTest() - { - $dataTable = new DataTable(); - - $arraySubTableForRow2 = array( - array(Row::COLUMNS => array('label' => 'sub1', 'count' => 1, 'bool' => false)), - array(Row::COLUMNS => array('label' => 'sub2', 'count' => 2, 'bool' => true)), - ); - $subDataTableForRow2 = new DataTable(); - $subDataTableForRow2->addRowsFromArray($arraySubTableForRow2); - - $array = array( - array(Row::COLUMNS => array('label' => 'Google©', 'bool' => false, 'goals' => array('idgoal=1' => array('revenue' => 5.5, 'nb_conversions' => 10)), 'nb_uniq_visitors' => 11, 'nb_visits' => 11, 'nb_actions' => 17, 'max_actions' => '5', 'sum_visit_length' => 517, 'bounce_count' => 9), - Row::METADATA => array('url' => 'http://www.google.com/display"and,properly', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!', 'nb_uniq_visitors' => 15, 'bool' => true, 'nb_visits' => 151, 'nb_actions' => 147, 'max_actions' => '50', 'sum_visit_length' => 517, 'bounce_count' => 90), - Row::METADATA => array('url' => 'http://www.yahoo.com', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png'), - Row::DATATABLE_ASSOCIATED => $subDataTableForRow2, - ) - ); - $dataTable->addRowsFromArray($array); - return $dataTable; - } - - protected function _getDataTableSimpleTest() - { - $array = array('max_actions' => 14.0, 'nb_uniq_visitors' => 57.0, 'nb_visits' => 66.0, 'nb_actions' => 151.0, 'sum_visit_length' => 5118.0, 'bounce_count' => 44.0,); - - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableSimpleOneRowTest() - { - $array = array('nb_visits' => 14.0); - - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableEmpty() - { - $table = new DataTable; - return $table; - } - - protected function _getDataTableSimpleOneZeroRowTest() - { - $array = array('nb_visits' => 0); - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableSimpleOneFalseRowTest() - { - $array = array('is_excluded' => false); - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - /** - * @group Core - */ - public function testCSVTest1() - { - $dataTable = $this->_getDataTableTest(); - - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "label,bool,goals_idgoal=1_revenue,goals_idgoal=1_nb_conversions,nb_uniq_visitors,nb_visits,nb_actions,max_actions,sum_visit_length,bounce_count,metadata_url,metadata_logo\n" . - "Google©,0,5.5,10,11,11,17,5,517,9,\"http://www.google.com/display\"\"and,properly\",./plugins/Referrers/images/searchEngines/www.google.com.png\n" . - "Yahoo!,1,,,15,151,147,50,517,90,http://www.yahoo.com,./plugins/Referrers/images/searchEngines/www.yahoo.com.png"; - - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVTest2() - { - $dataTable = $this->_getDataTableSimpleTest(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "max_actions,nb_uniq_visitors,nb_visits,nb_actions,sum_visit_length,bounce_count\n14,57,66,151,5118,44"; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testCSVTest3() - { - $dataTable = $this->_getDataTableSimpleOneRowTest(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "value\n14"; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVTest5() - { - $dataTable = $this->_getDataTableSimpleOneZeroRowTest(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "value\n0"; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVTest4() - { - $dataTable = $this->_getDataTableEmpty(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = 'No data available'; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVTest6() - { - $dataTable = $this->_getDataTableSimpleOneFalseRowTest(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "value\n0"; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVRendererCorrectlyEscapesHeadersAndValues() - { - $dataTable = $this->_getDataTableSimpleWithCommasInCells(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - - $expected = '"col,1","col,2" -"val""1","val"",2"'; - $actual = $render->render(); - $this->assertEquals($expected, $actual); - } - - /** - * DATA OF DATATABLE_ARRAY - * ------------------------- - */ - protected function _getDataTableMapTest() - { - $array1 = array( - array(Row::COLUMNS => array('label' => 'Google', 'nb_uniq_visitors' => 11, 'nb_visits' => 11,), - Row::METADATA => array('url' => 'http://www.google.com', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!', 'nb_uniq_visitors' => 15, 'nb_visits' => 151,), - Row::METADATA => array('url' => 'http://www.yahoo.com', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png'), - ) - ); - $table1 = new DataTable(); - $table1->addRowsFromArray($array1); - - $array2 = array( - array(Row::COLUMNS => array('label' => 'Google1©', 'nb_uniq_visitors' => 110, 'nb_visits' => 110,), - Row::METADATA => array('url' => 'http://www.google.com1', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png1'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!1', 'nb_uniq_visitors' => 150, 'nb_visits' => 1510,), - Row::METADATA => array('url' => 'http://www.yahoo.com1', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png1'), - ) - ); - $table2 = new DataTable(); - $table2->addRowsFromArray($array2); - - $table3 = new DataTable(); - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'date1'); - $table->addTable($table2, 'date2'); - $table->addTable($table3, 'date3'); - - return $table; - } - - protected function _getDataTableSimpleMapTest() - { - $array1 = array('max_actions' => 14.0, 'nb_uniq_visitors' => 57.0,); - $table1 = new Simple; - $table1->addRowsFromArray($array1); - - $array2 = array('max_actions' => 140.0, 'nb_uniq_visitors' => 570.0,); - $table2 = new Simple; - $table2->addRowsFromArray($array2); - - $table3 = new Simple; - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'row1'); - $table->addTable($table2, 'row2'); - $table->addTable($table3, 'row3'); - - return $table; - } - - protected function _getDataTableSimpleOneRowMapTest() - { - $array1 = array('nb_visits' => 14.0); - $table1 = new Simple; - $table1->addRowsFromArray($array1); - $array2 = array('nb_visits' => 15.0); - $table2 = new Simple; - $table2->addRowsFromArray($array2); - - $table3 = new Simple; - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'row1'); - $table->addTable($table2, 'row2'); - $table->addTable($table3, 'row3'); - - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_normal() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableMapTest(), 'idSite'); - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_simple() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableSimpleMapTest(), 'idSite'); - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_simpleOneRow() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableSimpleOneRowMapTest(), 'idSite'); - return $table; - } - - /** - * @group Core - */ - public function testCSVMapTest1() - { - $dataTable = $this->_getDataTableMapTest(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "testKey,label,nb_uniq_visitors,nb_visits,metadata_url,metadata_logo\n" . - "date1,Google,11,11,http://www.google.com,./plugins/Referrers/images/searchEngines/www.google.com.png\n" . - "date1,Yahoo!,15,151,http://www.yahoo.com,./plugins/Referrers/images/searchEngines/www.yahoo.com.png\n" . - "date2,Google1©,110,110,http://www.google.com1,./plugins/Referrers/images/searchEngines/www.google.com.png1\n" . - "date2,Yahoo!1,150,1510,http://www.yahoo.com1,./plugins/Referrers/images/searchEngines/www.yahoo.com.png1"; - - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVMapTest2() - { - $dataTable = $this->_getDataTableSimpleMapTest(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "testKey,max_actions,nb_uniq_visitors\nrow1,14,57\nrow2,140,570"; - - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVMapTest3() - { - $dataTable = $this->_getDataTableSimpleOneRowMapTest(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "testKey,value\nrow1,14\nrow2,15"; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVMapisMadeOfMapTest1() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_normal(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "parentArrayKey,testKey,label,nb_uniq_visitors,nb_visits,metadata_url,metadata_logo\n" . - "idSite,date1,Google,11,11,http://www.google.com,./plugins/Referrers/images/searchEngines/www.google.com.png\n" . - "idSite,date1,Yahoo!,15,151,http://www.yahoo.com,./plugins/Referrers/images/searchEngines/www.yahoo.com.png\n" . - "idSite,date2,Google1©,110,110,http://www.google.com1,./plugins/Referrers/images/searchEngines/www.google.com.png1\n" . - "idSite,date2,Yahoo!1,150,1510,http://www.yahoo.com1,./plugins/Referrers/images/searchEngines/www.yahoo.com.png1"; - - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVMapIsMadeOfMapTest2() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_simple(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "parentArrayKey,testKey,max_actions,nb_uniq_visitors\nidSite,row1,14,57\nidSite,row2,140,570"; - - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testCSVMapIsMadeOfMapTest3() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_simpleOneRow(); - $render = new Csv(); - $render->setTable($dataTable); - $render->convertToUnicode = false; - $expected = "parentArrayKey,testKey,value\nidSite,row1,14\nidSite,row2,15"; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testRenderArray1() - { - $data = array(); - - $render = new Csv(); - $render->setTable($data); - $render->convertToUnicode = false; - $expected = 'No data available'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray2() - { - $data = array('a', 'b', 'c'); - - $render = new Csv(); - $render->setTable($data); - $render->convertToUnicode = false; - $expected = 'a -b -c'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray3() - { - $data = array('a' => 'b', 'c' => 'd', 'e' => 'f', 5 => 'g'); - - $render = new Csv(); - $render->setTable($data); - $render->convertToUnicode = false; - $expected = 'a,c,e,5 -b,d,f,g'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray4() - { - $data = array('a' => 'b'); - - $render = new Csv(); - $render->setTable($data); - $render->convertToUnicode = false; - $expected = 'b'; - - $this->assertEquals($expected, $render->render()); - } - - private function _getDataTableSimpleWithCommasInCells() - { - $table = new DataTable(); - $table->addRowsFromSimpleArray(array( - array("col,1" => "val\"1", "col,2" => "val\",2") - )); - return $table; - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/DataTable/Renderer/ConsoleTest.php b/tests/PHPUnit/Core/DataTable/Renderer/ConsoleTest.php deleted file mode 100644 index 7da7dedb53..0000000000 --- a/tests/PHPUnit/Core/DataTable/Renderer/ConsoleTest.php +++ /dev/null @@ -1,150 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Manager; -use Piwik\DataTable; -use Piwik\DataTable\Renderer\Console; -use Piwik\DataTable\Row; - -class DataTable_Renderer_ConsoleTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - parent::setUp(); - Manager::getInstance()->deleteAll(); - } - - /** - * test with a row without child - * a row with a child that has a child - * a row with w child - * - * @group Core - */ - public function testConsole2SubLevelAnd2Different() - { - $table = new DataTable; - $table->addRowFromArray(array(Row::COLUMNS => array('visits' => 245, 'visitors' => 245), - Row::METADATA => array('logo' => 'test.png'),) - - ); - - $subsubtable = new DataTable; - $idsubsubtable = $subsubtable->getId(); - $subsubtable->addRowFromArray(array(Row::COLUMNS => array('visits' => 2))); - - $subtable = new DataTable; - $idsubtable1 = $subtable->getId(); - $subtable->addRowFromArray(array(Row::COLUMNS => array('visits' => 1), - Row::DATATABLE_ASSOCIATED => $subsubtable)); - - $table->addRowFromArray(array(Row::COLUMNS => array('visits' => 3), - Row::DATATABLE_ASSOCIATED => $subtable) - ); - - $subtable2 = new DataTable; - $idsubtable2 = $subtable2->getId(); - $subtable2->addRowFromArray(array(Row::COLUMNS => array('visits' => 5),)); - - $table->addRowFromArray(array(Row::COLUMNS => array('visits' => 9), - Row::DATATABLE_ASSOCIATED => $subtable2) - ); - - $expected = "- 1 ['visits' => 245, 'visitors' => 245] ['logo' => 'test.png'] [idsubtable = ]<br />\n- 2 ['visits' => 3] [] [idsubtable = $idsubtable1]<br />\n*- 1 ['visits' => 1] [] [idsubtable = $idsubsubtable]<br />\n**- 1 ['visits' => 2] [] [idsubtable = ]<br />\n- 3 ['visits' => 9] [] [idsubtable = $idsubtable2]<br />\n*- 1 ['visits' => 5] [] [idsubtable = ]<br />\n"; - - $render = new Console(); - $render->setTable($table); - $render->setPrefixRow('*'); - $rendered = $render->render(); - - $this->assertEquals($expected, $rendered); - } - - /** - * test with a row without child - * - * @group Core - */ - public function testConsoleSimple() - { - $table = new DataTable; - $table->addRowFromArray(array(Row::COLUMNS => array('visits' => 245, 'visitors' => 245), - Row::METADATA => array('logo' => 'test.png'),) - - ); - - $expected = "- 1 ['visits' => 245, 'visitors' => 245] ['logo' => 'test.png'] [idsubtable = ]<br />\n"; - - $render = new Console(); - $render->setTable($table); - $rendered = $render->render(); - - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testRenderArray1() - { - $data = array(); - - $render = new Console(); - $render->setTable($data); - $expected = 'Empty table<br /> -'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray2() - { - $data = array('a', 'b', 'c'); - - $render = new Console(); - $render->setTable($data); - $expected = "- 1 ['0' => 'a'] [] [idsubtable = ]<br /> -- 2 ['0' => 'b'] [] [idsubtable = ]<br /> -- 3 ['0' => 'c'] [] [idsubtable = ]<br /> -"; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray3() - { - $data = array('a' => 'b', 'c' => 'd', 'e' => 'f', 5 => 'g'); - - $render = new Console(); - $render->setTable($data); - $expected = "- 1 ['a' => 'b', 'c' => 'd', 'e' => 'f', '5' => 'g'] [] [idsubtable = ]<br /> -"; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray4() - { - $data = array('a' => 'b'); - - $render = new Console(); - $render->setTable($data); - $expected = "- 1 ['0' => 'b'] [] [idsubtable = ]<br /> -"; - - $this->assertEquals($expected, $render->render()); - } -} diff --git a/tests/PHPUnit/Core/DataTable/Renderer/JSONTest.php b/tests/PHPUnit/Core/DataTable/Renderer/JSONTest.php deleted file mode 100644 index c18ee12e60..0000000000 --- a/tests/PHPUnit/Core/DataTable/Renderer/JSONTest.php +++ /dev/null @@ -1,429 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Manager; -use Piwik\DataTable; -use Piwik\DataTable\Renderer\Json; -use Piwik\DataTable\Row; -use Piwik\DataTable\Simple; - -class DataTable_Renderer_JSONTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - parent::setUp(); - Manager::getInstance()->deleteAll(); - } - - /** - * DATA TESTS - * ----------------------- - * for each renderer we test the case - * - datatableSimple - * - normal datatable with 2 row (including columns and metadata) - */ - protected function _getDataTableTest() - { - $dataTable = new DataTable(); - - $arraySubTableForRow2 = array( - array(Row::COLUMNS => array('label' => 'sub1', 'count' => 1, 'bool' => false)), - array(Row::COLUMNS => array('label' => 'sub2', 'count' => 2, 'bool' => true)), - ); - $subDataTableForRow2 = new DataTable(); - $subDataTableForRow2->addRowsFromArray($arraySubTableForRow2); - - $array = array( - array(Row::COLUMNS => array('label' => 'Google©', 'bool' => false, 'goals' => array('idgoal=1' => array('revenue' => 5.5, 'nb_conversions' => 10)), 'nb_uniq_visitors' => 11, 'nb_visits' => 11, 'nb_actions' => 17, 'max_actions' => '5', 'sum_visit_length' => 517, 'bounce_count' => 9), - Row::METADATA => array('url' => 'http://www.google.com/display"and,properly', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!', 'nb_uniq_visitors' => 15, 'bool' => true, 'nb_visits' => 151, 'nb_actions' => 147, 'max_actions' => '50', 'sum_visit_length' => 517, 'bounce_count' => 90), - Row::METADATA => array('url' => 'http://www.yahoo.com', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png'), - Row::DATATABLE_ASSOCIATED => $subDataTableForRow2, - ) - ); - $dataTable->addRowsFromArray($array); - return $dataTable; - } - - protected function _getDataTableSimpleTest() - { - $array = array('max_actions' => 14.0, 'nb_uniq_visitors' => 57.0, 'nb_visits' => 66.0, 'nb_actions' => 151.0, 'sum_visit_length' => 5118.0, 'bounce_count' => 44.0,); - - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableSimpleOneRowTest() - { - $array = array('nb_visits' => 14.0); - - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableEmpty() - { - $table = new DataTable; - return $table; - } - - protected function _getDataTableSimpleOneZeroRowTest() - { - $array = array('nb_visits' => 0); - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableSimpleOneFalseRowTest() - { - $array = array('is_excluded' => false); - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - /** - * @group Core - */ - public function testJSONTest1() - { - $dataTable = $this->_getDataTableTest(); - $render = new Json(); - $render->setTable($dataTable); - $render->setRenderSubTables(true); - $expected = '[{"label":"Google\u00a9","bool":false,"goals":{"idgoal=1":{"revenue":5.5,"nb_conversions":10}},"nb_uniq_visitors":11,"nb_visits":11,"nb_actions":17,"max_actions":"5","sum_visit_length":517,"bounce_count":9,"url":"http:\/\/www.google.com\/display\"and,properly","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.google.com.png"},{"label":"Yahoo!","nb_uniq_visitors":15,"bool":true,"nb_visits":151,"nb_actions":147,"max_actions":"50","sum_visit_length":517,"bounce_count":90,"url":"http:\/\/www.yahoo.com","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.yahoo.com.png","idsubdatatable":2,"subtable":[{"label":"sub1","count":1,"bool":false},{"label":"sub2","count":2,"bool":true}]}]'; - $rendered = $render->render(); - - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testJSONTest2() - { - $dataTable = $this->_getDataTableSimpleTest(); - $render = new Json(); - $render->setTable($dataTable); - $expected = '{"max_actions":14,"nb_uniq_visitors":57,"nb_visits":66,"nb_actions":151,"sum_visit_length":5118,"bounce_count":44}'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testJSONTest3() - { - $dataTable = $this->_getDataTableSimpleOneRowTest(); - $render = new Json(); - $render->setTable($dataTable); - $expected = '{"value":14}'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testJSONTest4() - { - $dataTable = $this->_getDataTableEmpty(); - $render = new Json(); - $render->setTable($dataTable); - $expected = '[]'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testJSONTest5() - { - $dataTable = $this->_getDataTableSimpleOneZeroRowTest(); - $render = new Json(); - $render->setTable($dataTable); - $expected = '{"value":0}'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testJSONTest6() - { - $dataTable = $this->_getDataTableSimpleOneFalseRowTest(); - $render = new Json(); - $render->setTable($dataTable); - $expected = '{"value":false}'; - $this->assertEquals($expected, $render->render()); - } - - /** - * DATA OF DATATABLE_ARRAY - * ------------------------- - */ - - protected function _getDataTableMapTest() - { - $array1 = array( - array(Row::COLUMNS => array('label' => 'Google', 'nb_uniq_visitors' => 11, 'nb_visits' => 11,), - Row::METADATA => array('url' => 'http://www.google.com', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!', 'nb_uniq_visitors' => 15, 'nb_visits' => 151,), - Row::METADATA => array('url' => 'http://www.yahoo.com', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png'), - ) - ); - $table1 = new DataTable(); - $table1->addRowsFromArray($array1); - - $array2 = array( - array(Row::COLUMNS => array('label' => 'Google1©', 'nb_uniq_visitors' => 110, 'nb_visits' => 110,), - Row::METADATA => array('url' => 'http://www.google.com1', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png1'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!1', 'nb_uniq_visitors' => 150, 'nb_visits' => 1510,), - Row::METADATA => array('url' => 'http://www.yahoo.com1', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png1'), - ) - ); - $table2 = new DataTable(); - $table2->addRowsFromArray($array2); - - $table3 = new DataTable(); - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'date1'); - $table->addTable($table2, 'date2'); - $table->addTable($table3, 'date3'); - - return $table; - } - - protected function _getDataTableSimpleMapTest() - { - $array1 = array('max_actions' => 14.0, 'nb_uniq_visitors' => 57.0,); - $table1 = new Simple; - $table1->addRowsFromArray($array1); - - $array2 = array('max_actions' => 140.0, 'nb_uniq_visitors' => 570.0,); - $table2 = new Simple; - $table2->addRowsFromArray($array2); - - $table3 = new Simple; - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'row1'); - $table->addTable($table2, 'row2'); - $table->addTable($table3, 'row3'); - - return $table; - } - - protected function _getDataTableSimpleOneRowMapTest() - { - $array1 = array('nb_visits' => 14.0); - $table1 = new Simple; - $table1->addRowsFromArray($array1); - $array2 = array('nb_visits' => 15.0); - $table2 = new Simple; - $table2->addRowsFromArray($array2); - - $table3 = new Simple; - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'row1'); - $table->addTable($table2, 'row2'); - $table->addTable($table3, 'row3'); - - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_normal() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableMapTest(), 'idSite'); - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_simple() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableSimpleMapTest(), 'idSite'); - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_simpleOneRow() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableSimpleOneRowMapTest(), 'idSite'); - return $table; - } - - /** - * @group Core - */ - public function testJSONArrayTest1() - { - $dataTable = $this->_getDataTableMapTest(); - $render = new Json(); - $render->setTable($dataTable); - $rendered = $render->render(); - $expected = '{"date1":[{"label":"Google","nb_uniq_visitors":11,"nb_visits":11,"url":"http:\/\/www.google.com","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.google.com.png"},{"label":"Yahoo!","nb_uniq_visitors":15,"nb_visits":151,"url":"http:\/\/www.yahoo.com","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.yahoo.com.png"}],"date2":[{"label":"Google1\u00a9","nb_uniq_visitors":110,"nb_visits":110,"url":"http:\/\/www.google.com1","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.google.com.png1"},{"label":"Yahoo!1","nb_uniq_visitors":150,"nb_visits":1510,"url":"http:\/\/www.yahoo.com1","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.yahoo.com.png1"}],"date3":[]}'; - - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testJSONMapTest2() - { - $dataTable = $this->_getDataTableSimpleMapTest(); - $render = new Json(); - $render->setTable($dataTable); - $rendered = $render->render(); - - $expected = '{"row1":{"max_actions":14,"nb_uniq_visitors":57},"row2":{"max_actions":140,"nb_uniq_visitors":570},"row3":[]}'; - - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testJSONMapTest3() - { - $dataTable = $this->_getDataTableSimpleOneRowMapTest(); - $render = new Json(); - $render->setTable($dataTable); - $rendered = $render->render(); - - $expected = '{"row1":14,"row2":15,"row3":[]}'; - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testJSONMapIsMadeOfMapTest1() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_normal(); - $render = new Json(); - $render->setTable($dataTable); - $rendered = $render->render(); - $expected = '{"idSite":{"date1":[{"label":"Google","nb_uniq_visitors":11,"nb_visits":11,"url":"http:\/\/www.google.com","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.google.com.png"},{"label":"Yahoo!","nb_uniq_visitors":15,"nb_visits":151,"url":"http:\/\/www.yahoo.com","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.yahoo.com.png"}],"date2":[{"label":"Google1\u00a9","nb_uniq_visitors":110,"nb_visits":110,"url":"http:\/\/www.google.com1","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.google.com.png1"},{"label":"Yahoo!1","nb_uniq_visitors":150,"nb_visits":1510,"url":"http:\/\/www.yahoo.com1","logo":".\/plugins\/Referrers\/images\/searchEngines\/www.yahoo.com.png1"}],"date3":[]}}'; - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testJSONMapIsMadeOfMapTest2() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_simple(); - $render = new Json(); - $render->setTable($dataTable); - $rendered = $render->render(); - - $expected = '{"idSite":{"row1":{"max_actions":14,"nb_uniq_visitors":57},"row2":{"max_actions":140,"nb_uniq_visitors":570},"row3":[]}}'; - - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testJSONMapIsMadeOfMapTest3() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_simpleOneRow(); - $render = new Json(); - $render->setTable($dataTable); - - $expected = '{"idSite":{"row1":14,"row2":15,"row3":[]}}'; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testRenderArray1() - { - $data = array(); - - $render = new Json(); - $render->setTable($data); - $expected = '[]'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray2() - { - $data = array('a', 'b', 'c', array('a' => 'b'), array(1, 2)); - - $render = new Json(); - $render->setTable($data); - $expected = '["a","b","c",{"a":"b"},[1,2]]'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray3() - { - $data = array('a' => 'b', 'c' => 'd', 'e' => 'f', 5 => 'g'); - - $render = new Json(); - $render->setTable($data); - $expected = '[{"a":"b","c":"d","e":"f","5":"g"}]'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray4() - { - $data = array('a' => 'b', 'c' => array(1, 2, 3, 4), 'e' => array('f' => 'g', 'h' => 'i', 'j' => 'k')); - - $render = new Json(); - $render->setTable($data); - $expected = '{"a":"b","c":[1,2,3,4],"e":{"f":"g","h":"i","j":"k"}}'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray5() - { - $data = array('a' => 'b'); - - $render = new Json(); - $render->setTable($data); - $expected = '[{"a":"b"}]'; - - $this->assertEquals($expected, $render->render()); - } - -} diff --git a/tests/PHPUnit/Core/DataTable/Renderer/PHPTest.php b/tests/PHPUnit/Core/DataTable/Renderer/PHPTest.php deleted file mode 100644 index 7ba4088e5c..0000000000 --- a/tests/PHPUnit/Core/DataTable/Renderer/PHPTest.php +++ /dev/null @@ -1,530 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Manager; -use Piwik\DataTable; -use Piwik\DataTable\Renderer\Php; -use Piwik\DataTable\Row; -use Piwik\DataTable\Simple; - -class DataTable_Renderer_PHPTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - parent::setUp(); - Manager::getInstance()->deleteAll(); - } - - /** - * DATA TESTS - * ----------------------- - * for each renderer we test the case - * - datatableSimple - * - normal datatable with 2 row (including columns and metadata) - */ - protected function _getDataTableTest() - { - $dataTable = new DataTable(); - - $arraySubTableForRow2 = array( - array(Row::COLUMNS => array('label' => 'sub1', 'count' => 1, 'bool' => false)), - array(Row::COLUMNS => array('label' => 'sub2', 'count' => 2, 'bool' => true)), - ); - $subDataTableForRow2 = new DataTable(); - $subDataTableForRow2->addRowsFromArray($arraySubTableForRow2); - - $array = array( - array(Row::COLUMNS => array('label' => 'Google©', 'bool' => false, 'goals' => array('idgoal=1' => array('revenue' => 5.5, 'nb_conversions' => 10)), 'nb_uniq_visitors' => 11, 'nb_visits' => 11, 'nb_actions' => 17, 'max_actions' => '5', 'sum_visit_length' => 517, 'bounce_count' => 9), - Row::METADATA => array('url' => 'http://www.google.com/display"and,properly', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!', 'nb_uniq_visitors' => 15, 'bool' => true, 'nb_visits' => 151, 'nb_actions' => 147, 'max_actions' => '50', 'sum_visit_length' => 517, 'bounce_count' => 90), - Row::METADATA => array('url' => 'http://www.yahoo.com', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png'), - Row::DATATABLE_ASSOCIATED => $subDataTableForRow2, - ) - ); - $dataTable->addRowsFromArray($array); - return $dataTable; - } - - protected function _getDataTableSimpleTest() - { - $array = array('max_actions' => 14.0, 'nb_uniq_visitors' => 57.0, 'nb_visits' => 66.0, 'nb_actions' => 151.0, 'sum_visit_length' => 5118.0, 'bounce_count' => 44.0,); - - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableSimpleOneRowTest() - { - $array = array('nb_visits' => 14.0); - - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableEmpty() - { - $table = new DataTable; - return $table; - } - - protected function _getDataTableSimpleOneZeroRowTest() - { - $array = array('nb_visits' => 0); - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableSimpleOneFalseRowTest() - { - $array = array('is_excluded' => false); - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - /** - * @group Core - */ - public function testPHPTest1() - { - $dataTable = $this->_getDataTableTest(); - $render = new Php(); - $render->setTable($dataTable); - $render->setRenderSubTables(true); - - $expected = serialize(array( - 0 => - array( - 'label' => 'Google©', - 'bool' => false, - 'goals' => array( - 'idgoal=1' => array( - 'revenue' => 5.5, - 'nb_conversions' => 10, - ), - ), - 'nb_uniq_visitors' => 11, - 'nb_visits' => 11, - 'nb_actions' => 17, - 'max_actions' => '5', - 'sum_visit_length' => 517, - 'bounce_count' => 9, - 'url' => 'http://www.google.com/display"and,properly', - 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png', - ), - 1 => - array( - 'label' => 'Yahoo!', - 'nb_uniq_visitors' => 15, - 'bool' => true, - 'nb_visits' => 151, - 'nb_actions' => 147, - 'max_actions' => '50', - 'sum_visit_length' => 517, - 'bounce_count' => 90, - 'url' => 'http://www.yahoo.com', - 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png', - 'idsubdatatable' => 2, - 'subtable' => - array( - 0 => - array( - 'label' => 'sub1', - 'count' => 1, - 'bool' => false, - ), - 1 => - array( - 'label' => 'sub2', - 'count' => 2, - 'bool' => true, - ), - ), - ), - )); - $rendered = $render->render(null); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testPHPTest2() - { - $dataTable = $this->_getDataTableSimpleTest(); - $render = new Php(); - $render->setTable($dataTable); - $expected = serialize(array( - 'max_actions' => 14.0, - 'nb_uniq_visitors' => 57.0, - 'nb_visits' => 66.0, - 'nb_actions' => 151.0, - 'sum_visit_length' => 5118.0, - 'bounce_count' => 44.0, - )); - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testPHPTest3() - { - $dataTable = $this->_getDataTableSimpleOneRowTest(); - $render = new Php(); - $render->setTable($dataTable); - $expected = serialize(14.0); - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testPHPTest4() - { - $dataTable = $this->_getDataTableEmpty(); - $render = new Php(); - $render->setTable($dataTable); - $expected = serialize(array()); - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testPHPTest5() - { - $dataTable = $this->_getDataTableSimpleOneZeroRowTest(); - $render = new Php(); - $render->setTable($dataTable); - $expected = serialize(0); - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testPHPTest6() - { - $dataTable = $this->_getDataTableSimpleOneFalseRowTest(); - $render = new Php(); - $render->setTable($dataTable); - $expected = serialize(false); - $this->assertEquals($expected, $render->render()); - } - - /** - * DATA OF DATATABLE_ARRAY - * ------------------------- - */ - - protected function _getDataTableMapTest() - { - $array1 = array( - array(Row::COLUMNS => array('label' => 'Google', 'nb_uniq_visitors' => 11, 'nb_visits' => 11,), - Row::METADATA => array('url' => 'http://www.google.com', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!', 'nb_uniq_visitors' => 15, 'nb_visits' => 151,), - Row::METADATA => array('url' => 'http://www.yahoo.com', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png'), - ) - ); - $table1 = new DataTable(); - $table1->addRowsFromArray($array1); - - $array2 = array( - array(Row::COLUMNS => array('label' => 'Google1©', 'nb_uniq_visitors' => 110, 'nb_visits' => 110,), - Row::METADATA => array('url' => 'http://www.google.com1', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png1'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!1', 'nb_uniq_visitors' => 150, 'nb_visits' => 1510,), - Row::METADATA => array('url' => 'http://www.yahoo.com1', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png1'), - ) - ); - $table2 = new DataTable(); - $table2->addRowsFromArray($array2); - - $table3 = new DataTable(); - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'date1'); - $table->addTable($table2, 'date2'); - $table->addTable($table3, 'date3'); - - return $table; - } - - protected function _getDataTableSimpleMapTest() - { - $array1 = array('max_actions' => 14.0, 'nb_uniq_visitors' => 57.0,); - $table1 = new Simple; - $table1->addRowsFromArray($array1); - - $array2 = array('max_actions' => 140.0, 'nb_uniq_visitors' => 570.0,); - $table2 = new Simple; - $table2->addRowsFromArray($array2); - - $table3 = new Simple; - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'row1'); - $table->addTable($table2, 'row2'); - $table->addTable($table3, 'row3'); - - return $table; - } - - protected function _getDataTableSimpleOneRowMapTest() - { - $array1 = array('nb_visits' => 14.0); - $table1 = new Simple; - $table1->addRowsFromArray($array1); - $array2 = array('nb_visits' => 15.0); - $table2 = new Simple; - $table2->addRowsFromArray($array2); - - $table3 = new Simple; - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'row1'); - $table->addTable($table2, 'row2'); - $table->addTable($table3, 'row3'); - - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_normal() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableMapTest(), 'idSite'); - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_simple() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableSimpleMapTest(), 'idSite'); - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_simpleOneRow() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableSimpleOneRowMapTest(), 'idSite'); - return $table; - } - - /** - * @group Core - */ - public function testPHPMapTest1() - { - $dataTable = $this->_getDataTableMapTest(); - $render = new Php(); - $render->setTable($dataTable); - $rendered = $render->render(); - - $expected = serialize(array( - 'date1' => - array( - 0 => - array( - 'label' => 'Google', - 'nb_uniq_visitors' => 11, - 'nb_visits' => 11, - 'url' => 'http://www.google.com', - 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png', - ), - 1 => - array( - 'label' => 'Yahoo!', - 'nb_uniq_visitors' => 15, - 'nb_visits' => 151, - 'url' => 'http://www.yahoo.com', - 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png', - ), - ), - 'date2' => - array( - 0 => - array( - 'label' => 'Google1©', - 'nb_uniq_visitors' => 110, - 'nb_visits' => 110, - 'url' => 'http://www.google.com1', - 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png1', - ), - 1 => - array( - 'label' => 'Yahoo!1', - 'nb_uniq_visitors' => 150, - 'nb_visits' => 1510, - 'url' => 'http://www.yahoo.com1', - 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png1', - ), - ), - 'date3' => array(), - )); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testPHPMapTest2() - { - $dataTable = $this->_getDataTableSimpleMapTest(); - $render = new Php(); - $render->setTable($dataTable); - $rendered = $render->render(); - - $expected = serialize(array( - 'row1' => - array( - 'max_actions' => 14.0, - 'nb_uniq_visitors' => 57.0, - ), - 'row2' => - array( - 'max_actions' => 140.0, - 'nb_uniq_visitors' => 570.0, - ), - 'row3' => - array(), - )); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testPHPMapTest3() - { - $dataTable = $this->_getDataTableSimpleOneRowMapTest(); - $render = new Php(); - $render->setTable($dataTable); - $rendered = $render->render(); - - $expected = serialize(array( - 'row1' => 14.0, - 'row2' => 15.0, - 'row3' => array(), - )); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testPHPMapIsMadeOfMapTest1() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_normal(); - $render = new Php(); - $render->setTable($dataTable); - $rendered = $render->render(); - - $expected = serialize(array('idSite' => - array( - 'date1' => - array( - 0 => - array( - 'label' => 'Google', - 'nb_uniq_visitors' => 11, - 'nb_visits' => 11, - 'url' => 'http://www.google.com', - 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png', - ), - 1 => - array( - 'label' => 'Yahoo!', - 'nb_uniq_visitors' => 15, - 'nb_visits' => 151, - 'url' => 'http://www.yahoo.com', - 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png', - ), - ), - 'date2' => - array( - 0 => - array( - 'label' => 'Google1©', - 'nb_uniq_visitors' => 110, - 'nb_visits' => 110, - 'url' => 'http://www.google.com1', - 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png1', - ), - 1 => - array( - 'label' => 'Yahoo!1', - 'nb_uniq_visitors' => 150, - 'nb_visits' => 1510, - 'url' => 'http://www.yahoo.com1', - 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png1', - ), - ), - 'date3' => array(), - ))); - - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testPHPMapIsMadeOfMapTest2() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_simple(); - $render = new Php(); - $render->setTable($dataTable); - $rendered = $render->render(); - - $expected = serialize(array('idSite' => - array( - 'row1' => - array( - 'max_actions' => 14.0, - 'nb_uniq_visitors' => 57.0, - ), - 'row2' => - array( - 'max_actions' => 140.0, - 'nb_uniq_visitors' => 570.0, - ), - 'row3' => - array(), - ))); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testPHPMapIsMadeOfMapTest3() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_simpleOneRow(); - $render = new Php(); - $render->setTable($dataTable); - $rendered = $render->render(); - - $expected = serialize(array('idSite' => - array( - 'row1' => 14.0, - 'row2' => 15.0, - 'row3' => array(), - ))); - $this->assertEquals($expected, $rendered); - } -} diff --git a/tests/PHPUnit/Core/DataTable/Renderer/XMLTest.php b/tests/PHPUnit/Core/DataTable/Renderer/XMLTest.php deleted file mode 100644 index f8c2a93072..0000000000 --- a/tests/PHPUnit/Core/DataTable/Renderer/XMLTest.php +++ /dev/null @@ -1,658 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable\Manager; -use Piwik\DataTable; -use Piwik\DataTable\Renderer\Xml; -use Piwik\DataTable\Row; -use Piwik\DataTable\Simple; - -class DataTable_Renderer_XMLTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - parent::setUp(); - Manager::getInstance()->deleteAll(); - } - - /** - * DATA TESTS - * ----------------------- - * for each renderer we test the case - * - datatableSimple - * - normal datatable with 2 row (including columns and metadata) - */ - protected function _getDataTableTest() - { - $dataTable = new DataTable(); - - $arraySubTableForRow2 = array( - array(Row::COLUMNS => array('label' => 'sub1', 'count' => 1, 'bool' => false)), - array(Row::COLUMNS => array('label' => 'sub2', 'count' => 2, 'bool' => true)), - ); - $subDataTableForRow2 = new DataTable(); - $subDataTableForRow2->addRowsFromArray($arraySubTableForRow2); - - $array = array( - array(Row::COLUMNS => array('label' => 'Google©', 'bool' => false, 'goals' => array('idgoal=1' => array('revenue' => 5.5, 'nb_conversions' => 10)), 'nb_uniq_visitors' => 11, 'nb_visits' => 11, 'nb_actions' => 17, 'max_actions' => '5', 'sum_visit_length' => 517, 'bounce_count' => 9), - Row::METADATA => array('url' => 'http://www.google.com/display"and,properly', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!', 'nb_uniq_visitors' => 15, 'bool' => true, 'nb_visits' => 151, 'nb_actions' => 147, 'max_actions' => '50', 'sum_visit_length' => 517, 'bounce_count' => 90), - Row::METADATA => array('url' => 'http://www.yahoo.com', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png'), - Row::DATATABLE_ASSOCIATED => $subDataTableForRow2, - ) - ); - $dataTable->addRowsFromArray($array); - return $dataTable; - } - - protected function _getDataTableSimpleTest() - { - $array = array('max_actions' => 14.0, 'nb_uniq_visitors' => 57.0, 'nb_visits' => 66.0, 'nb_actions' => 151.0, 'sum_visit_length' => 5118.0, 'bounce_count' => 44.0,); - - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableSimpleOneRowTest() - { - $array = array('nb_visits' => 14.0); - - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableEmpty() - { - $table = new DataTable; - return $table; - } - - protected function _getDataTableSimpleOneZeroRowTest() - { - $array = array('nb_visits' => 0); - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - protected function _getDataTableSimpleOneFalseRowTest() - { - $array = array('is_excluded' => false); - $table = new Simple; - $table->addRowsFromArray($array); - return $table; - } - - /** - * @group Core - */ - public function testXMLTest1() - { - $dataTable = $this->_getDataTableTest(); - $render = new Xml(); - $render->setTable($dataTable); - $render->setRenderSubTables(true); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result> - <row> - <label>Google©</label> - <bool>0</bool> - <goals> - <row idgoal=\'1\'> - <revenue>5.5</revenue> - <nb_conversions>10</nb_conversions> - </row> - </goals> - <nb_uniq_visitors>11</nb_uniq_visitors> - <nb_visits>11</nb_visits> - <nb_actions>17</nb_actions> - <max_actions>5</max_actions> - <sum_visit_length>517</sum_visit_length> - <bounce_count>9</bounce_count> - <url>http://www.google.com/display"and,properly</url> - <logo>./plugins/Referrers/images/searchEngines/www.google.com.png</logo> - </row> - <row> - <label>Yahoo!</label> - <nb_uniq_visitors>15</nb_uniq_visitors> - <bool>1</bool> - <nb_visits>151</nb_visits> - <nb_actions>147</nb_actions> - <max_actions>50</max_actions> - <sum_visit_length>517</sum_visit_length> - <bounce_count>90</bounce_count> - <url>http://www.yahoo.com</url> - <logo>./plugins/Referrers/images/searchEngines/www.yahoo.com.png</logo> - <idsubdatatable>2</idsubdatatable> - <subtable> - <row> - <label>sub1</label> - <count>1</count> - <bool>0</bool> - </row> - <row> - <label>sub2</label> - <count>2</count> - <bool>1</bool> - </row> - </subtable> - </row> -</result>'; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testXMLTest2() - { - $dataTable = $this->_getDataTableSimpleTest(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result> - <max_actions>14</max_actions> - <nb_uniq_visitors>57</nb_uniq_visitors> - <nb_visits>66</nb_visits> - <nb_actions>151</nb_actions> - <sum_visit_length>5118</sum_visit_length> - <bounce_count>44</bounce_count> -</result>'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testXMLTest3() - { - $dataTable = $this->_getDataTableSimpleOneRowTest(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result>14</result>'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testXMLTest4() - { - $dataTable = $this->_getDataTableEmpty(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result />'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testXMLTest5() - { - $dataTable = $this->_getDataTableSimpleOneZeroRowTest(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result>0</result>'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testXMLTest6() - { - $dataTable = $this->_getDataTableSimpleOneFalseRowTest(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result>0</result>'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testXMLRendererSuccessfullyRendersWhenSimpleDataTableColumnsHaveInvalidXmlCharacters() - { - $dataTable = $this->_getDataTableSimpleWithInvalidChars(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result> - <col name="$%@(%">1</col> - <col name="avbs$">2</col> - <col name="b/">2</col> -</result>'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testXMLRendererSuccessfullyRendersWhenDataTableColumnsHaveInvalidXmlCharacters() - { - $dataTable = $this->_getDataTableWithInvalidChars(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result> - <row> - <col name="$%@(%">1</col> - <col name="avbs$">2</col> - <col name="b/">2</col> - </row> -</result>'; - $this->assertEquals($expected, $render->render()); - } - - /** - * DATA OF DATATABLE_ARRAY - * ------------------------- - */ - - protected function _getDataTableMapTest() - { - $array1 = array( - array(Row::COLUMNS => array('label' => 'Google', 'nb_uniq_visitors' => 11, 'nb_visits' => 11,), - Row::METADATA => array('url' => 'http://www.google.com', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!', 'nb_uniq_visitors' => 15, 'nb_visits' => 151,), - Row::METADATA => array('url' => 'http://www.yahoo.com', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png'), - ) - ); - $table1 = new DataTable(); - $table1->addRowsFromArray($array1); - - $array2 = array( - array(Row::COLUMNS => array('label' => 'Google1©', 'nb_uniq_visitors' => 110, 'nb_visits' => 110,), - Row::METADATA => array('url' => 'http://www.google.com1', 'logo' => './plugins/Referrers/images/searchEngines/www.google.com.png1'), - ), - array(Row::COLUMNS => array('label' => 'Yahoo!1', 'nb_uniq_visitors' => 150, 'nb_visits' => 1510,), - Row::METADATA => array('url' => 'http://www.yahoo.com1', 'logo' => './plugins/Referrers/images/searchEngines/www.yahoo.com.png1'), - ) - ); - $table2 = new DataTable(); - $table2->addRowsFromArray($array2); - - $table3 = new DataTable(); - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'date1'); - $table->addTable($table2, 'date2'); - $table->addTable($table3, 'date3'); - - return $table; - } - - protected function _getDataTableSimpleMapTest() - { - $array1 = array('max_actions' => 14.0, 'nb_uniq_visitors' => 57.0,); - $table1 = new Simple; - $table1->addRowsFromArray($array1); - - $array2 = array('max_actions' => 140.0, 'nb_uniq_visitors' => 570.0,); - $table2 = new Simple; - $table2->addRowsFromArray($array2); - - $table3 = new Simple; - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'row1'); - $table->addTable($table2, 'row2'); - $table->addTable($table3, 'row3'); - - return $table; - } - - protected function _getDataTableSimpleOneRowMapTest() - { - $array1 = array('nb_visits' => 14.0); - $table1 = new Simple; - $table1->addRowsFromArray($array1); - $array2 = array('nb_visits' => 15.0); - $table2 = new Simple; - $table2->addRowsFromArray($array2); - - $table3 = new Simple; - - $table = new DataTable\Map(); - $table->setKeyName('testKey'); - $table->addTable($table1, 'row1'); - $table->addTable($table2, 'row2'); - $table->addTable($table3, 'row3'); - - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_normal() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableMapTest(), 'idSite'); - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_simple() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableSimpleMapTest(), 'idSite'); - return $table; - } - - protected function _getDataTableMap_containsDataTableMap_simpleOneRow() - { - $table = new DataTable\Map(); - $table->setKeyName('parentArrayKey'); - $table->addTable($this->_getDataTableSimpleOneRowMapTest(), 'idSite'); - return $table; - } - - /** - * @group Core - */ - public function testXMLMapTest1() - { - $dataTable = $this->_getDataTableMapTest(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<results> - <result testKey="date1"> - <row> - <label>Google</label> - <nb_uniq_visitors>11</nb_uniq_visitors> - <nb_visits>11</nb_visits> - <url>http://www.google.com</url> - <logo>./plugins/Referrers/images/searchEngines/www.google.com.png</logo> - </row> - <row> - <label>Yahoo!</label> - <nb_uniq_visitors>15</nb_uniq_visitors> - <nb_visits>151</nb_visits> - <url>http://www.yahoo.com</url> - <logo>./plugins/Referrers/images/searchEngines/www.yahoo.com.png</logo> - </row> - </result> - <result testKey="date2"> - <row> - <label>Google1©</label> - <nb_uniq_visitors>110</nb_uniq_visitors> - <nb_visits>110</nb_visits> - <url>http://www.google.com1</url> - <logo>./plugins/Referrers/images/searchEngines/www.google.com.png1</logo> - </row> - <row> - <label>Yahoo!1</label> - <nb_uniq_visitors>150</nb_uniq_visitors> - <nb_visits>1510</nb_visits> - <url>http://www.yahoo.com1</url> - <logo>./plugins/Referrers/images/searchEngines/www.yahoo.com.png1</logo> - </row> - </result> - <result testKey="date3" /> -</results>'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testXMLArrayIsMadeOfMapTest1() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_normal(); - - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<results> - <result parentArrayKey="idSite"> - <result testKey="date1"> - <row> - <label>Google</label> - <nb_uniq_visitors>11</nb_uniq_visitors> - <nb_visits>11</nb_visits> - <url>http://www.google.com</url> - <logo>./plugins/Referrers/images/searchEngines/www.google.com.png</logo> - </row> - <row> - <label>Yahoo!</label> - <nb_uniq_visitors>15</nb_uniq_visitors> - <nb_visits>151</nb_visits> - <url>http://www.yahoo.com</url> - <logo>./plugins/Referrers/images/searchEngines/www.yahoo.com.png</logo> - </row> - </result> - <result testKey="date2"> - <row> - <label>Google1©</label> - <nb_uniq_visitors>110</nb_uniq_visitors> - <nb_visits>110</nb_visits> - <url>http://www.google.com1</url> - <logo>./plugins/Referrers/images/searchEngines/www.google.com.png1</logo> - </row> - <row> - <label>Yahoo!1</label> - <nb_uniq_visitors>150</nb_uniq_visitors> - <nb_visits>1510</nb_visits> - <url>http://www.yahoo.com1</url> - <logo>./plugins/Referrers/images/searchEngines/www.yahoo.com.png1</logo> - </row> - </result> - <result testKey="date3" /> - </result> -</results>'; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testXMLMapTest2() - { - $dataTable = $this->_getDataTableSimpleMapTest(); - $render = new Xml(); - $render->setTable($dataTable); - - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<results> - <result testKey="row1"> - <max_actions>14</max_actions> - <nb_uniq_visitors>57</nb_uniq_visitors> - </result> - <result testKey="row2"> - <max_actions>140</max_actions> - <nb_uniq_visitors>570</nb_uniq_visitors> - </result> - <result testKey="row3" /> -</results>'; - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testXMLArrayIsMadeOfMapTest2() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_simple(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<results> - <result parentArrayKey="idSite"> - <result testKey="row1"> - <max_actions>14</max_actions> - <nb_uniq_visitors>57</nb_uniq_visitors> - </result> - <result testKey="row2"> - <max_actions>140</max_actions> - <nb_uniq_visitors>570</nb_uniq_visitors> - </result> - <result testKey="row3" /> - </result> -</results>'; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testXMLMapTest3() - { - $dataTable = $this->_getDataTableSimpleOneRowMapTest(); - $render = new Xml(); - $render->setTable($dataTable); - - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<results> - <result testKey="row1">14</result> - <result testKey="row2">15</result> - <result testKey="row3" /> -</results>'; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testXMLArrayIsMadeOfMapTest3() - { - $dataTable = $this->_getDataTableMap_containsDataTableMap_simpleOneRow(); - $render = new Xml(); - $render->setTable($dataTable); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<results> - <result parentArrayKey="idSite"> - <result testKey="row1">14</result> - <result testKey="row2">15</result> - <result testKey="row3" /> - </result> -</results>'; - $rendered = $render->render(); - $this->assertEquals($expected, $rendered); - } - - /** - * @group Core - */ - public function testRenderArray1() - { - $data = array(); - - $render = new Xml(); - $render->setTable($data); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result />'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray2() - { - $data = array("firstElement", - array("firstElement", - "secondElement"), - "thirdElement"); - - $render = new Xml(); - $render->setTable($data); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result> - <row>firstElement</row> - <row> - <row>firstElement</row> - <row>secondElement</row> - </row> - <row>thirdElement</row> -</result>'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray3() - { - $data = array('a' => 'b', 'c' => 'd', 'e' => 'f', 5 => 'g'); - - $render = new Xml(); - $render->setTable($data); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result> - <row> - <a>b</a> - <c>d</c> - <e>f</e> - <row key="5">g</row> - </row> -</result>'; - - $this->assertEquals($expected, $render->render()); - } - - /** - * @group Core - */ - public function testRenderArray4() - { - $data = array('c' => array(1, 2, 3, 4), 'e' => array('f' => 'g', 'h' => 'i', 'j' => 'k')); - - $render = new Xml(); - $render->setTable($data); - $expected = '<?xml version="1.0" encoding="utf-8" ?> -<result> - <c> - <row>1</row> - <row>2</row> - <row>3</row> - <row>4</row> - </c> - <e> - <f>g</f> - <h>i</h> - <j>k</j> - </e> -</result>'; - - $this->assertEquals($expected, $render->render()); - } - - private function _getDataTableSimpleWithInvalidChars() - { - $table = new DataTable\Simple(); - $table->addRowsFromSimpleArray( - array("$%@(%" => 1, "avbs$" => 2, "b/" => 2) - ); - return $table; - } - - private function _getDataTableWithInvalidChars() - { - $table = new DataTable(); - $table->addRowsFromSimpleArray( - array("$%@(%" => 1, "avbs$" => 2, "b/" => 2) - ); - return $table; - } -} diff --git a/tests/PHPUnit/Core/DataTable/RowTest.php b/tests/PHPUnit/Core/DataTable/RowTest.php deleted file mode 100644 index 2ecb2d3d53..0000000000 --- a/tests/PHPUnit/Core/DataTable/RowTest.php +++ /dev/null @@ -1,235 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\DataTable; -use Piwik\DataTable\Row; - -/** - * @group Core - */ -class RowTest extends PHPUnit_Framework_TestCase -{ - /** - * @var Row - */ - private $row; - - public function setUp() - { - $this->row = new Row(); - } - - public function testDataTableAssociatedIsNegativeWhenSubDataTableInMemory() - { - $testRow = $this->getTestRowWithSubDataTableLoaded(); - $this->assertTrue($testRow->c[Row::DATATABLE_ASSOCIATED] < 0); - } - - public function testDataTableAssociatedIsNegativeWhenSubDataTableAdded() - { - $testRow = $this->getTestRowWithSubDataTableNotLoaded(); - $testRow->addSubtable($this->getTestSubDataTable()); - $this->assertTrue($testRow->c[Row::DATATABLE_ASSOCIATED] < 0); - } - - public function testDataTableAssociatedIsNegativeWhenSubDataTableSetted() - { - $testRow = $this->getTestRowWithSubDataTableNotLoaded(); - $testRow->setSubtable($this->getTestSubDataTable()); - $this->assertTrue($testRow->c[Row::DATATABLE_ASSOCIATED] < 0); - } - - public function testIdSubDataTabledIsPositiveWhenSubDataTableInMemory() - { - $testRow = $this->getTestRowWithSubDataTableLoaded(); - $this->assertTrue($testRow->getIdSubDataTable() > 0); - } - - public function testDataTableAssociatedIsPositiveOnSerializedRow() - { - $testRow = $this->getTestRowWithSubDataTableLoaded(); - - // testDataTableAssociatedIsPositiveOnSerializedRow is only valid as long as the Row is not modified after being unserialized - $this->assertFalse(method_exists($testRow, '__wakeup')); - - $serializedTestRow = serialize($testRow); - $unserializedTestRow = unserialize($serializedTestRow); - - $this->assertTrue($unserializedTestRow->c[Row::DATATABLE_ASSOCIATED] > 0); - } - - public function testDataTableAssociatedIsNegativeAfterSerialize() - { - $testRow = $this->getTestRowWithSubDataTableLoaded(); - - serialize($testRow); - - $testRow->cleanPostSerialize(); - - $this->assertTrue($testRow->c[Row::DATATABLE_ASSOCIATED] < 0); - } - - public function testIsSubDataTableLoadedIsTrueWhenSubDataTableInMemory() - { - $testRow = $this->getTestRowWithSubDataTableLoaded(); - $this->assertTrue($testRow->isSubtableLoaded()); - } - - public function testIsSubDataTableLoadedIsFalseWhenSubDataTableNotInMemory() - { - $testRow = $this->getTestRowWithSubDataTableNotLoaded(); - $this->assertFalse($testRow->isSubtableLoaded()); - } - - public function test_getColumn_shouldReturnRawScalarValue() - { - $this->assertColumnSavesValue(5, 'testInteger', 5); - $this->assertColumnSavesValue(5.444, 'testFloat', 5.444); - $this->assertColumnSavesValue('MyString', 'testString', 'MyString'); - $this->assertColumnSavesValue(array(array(1 => '5')), 'testArray', array(array(1 => '5'))); - } - - public function test_getColumn_shouldResolveACallable() - { - $this->assertColumnSavesValue(6, 'testClosure', function () { - return 6; - }); - - $this->assertColumnSavesValue(7, 'testCallable', array($this, 'callbackReturnScalar')); - } - - public function test_getColumn_shouldPassRowToCallable() - { - $callbackRow = null; - - $this->row->addColumn('testClosure', function (Row $row) use (&$callbackRow) { - $callbackRow = $row; - return $row; - }); - - $returnedRow = $this->row->getColumn('testClosure'); - $this->assertNotEmpty($callbackRow); - $this->assertSame($returnedRow, $callbackRow); - } - - public function test_getColumn_shouldReturnFalseIfValueIsNull() - { - $this->assertColumnSavesValue(false, 'testScalar', null); - $this->assertColumnSavesValue(false, 'testClosure', function () { - return null; - }); - } - - public function test_getColumns_shouldNotCallAnyCallableForSecurity() - { - $this->assertColumnSavesValue('print_r', 'testScalar', 'print_r'); - $this->assertColumnSavesValue(array('print_r'), 'testScalar', array('print_r')); - $this->assertColumnSavesValue(array(null, 'print_r'), 'testScalar', array(null, 'print_r')); - - $this->assertColumnSavesValue('phpinfo', 'testScalar', 'phpinfo'); - $this->assertColumnSavesValue(array('phpinfo'), 'testScalar', array('phpinfo')); - $this->assertColumnSavesValue(array(null, 'phpinfo'), 'testScalar', array(null, 'phpinfo')); - } - - public function test_getColumns_shouldReturnAllColumns() - { - $this->row->setColumns(array( - 'nb_visits' => 4, - 'label' => 'Test', - 'closure' => function () { return 5; }, - 'callable' => array($this, 'callbackReturnScalar'), - 'goals' => array(1 => array()) - )); - - $expected = array( - 'nb_visits' => 4, - 'label' => 'Test', - 'closure' => 5, - 'callable' => 7, - 'goals' => array(1 => array()) - ); - - $this->assertEquals($expected, $this->row->getColumns()); - } - - public function test_getColumns_shouldNotConvertNullValuesToFalse() - { - $this->row->setColumns(array( - 'nb_visits' => null, - 'label' => 'Test', - 'closure' => function () { return null; }, - 'boolean' => false - )); - - $expected = array( - 'nb_visits' => null, - 'label' => 'Test', - 'closure' => null, - 'boolean' => false - ); - - $this->assertSame($expected, $this->row->getColumns()); - } - - public function callbackReturnScalar(Row $row) - { - return 7; - } - - public function test_SumRow_shouldIgnoreCallableValues_AndNotRaiseAnyException() - { - $columns = array( - 'nb_visits' => 5, - 'label' => 'Test', - 'closure' => function () { return 7; }, - ); - - $this->row->setColumns($columns); - - $secondRow = new Row(array(Row::COLUMNS => $columns)); - - $this->row->sumRow($secondRow); - - $this->assertEquals(10, $this->row->getColumn('nb_visits')); - $this->assertEquals(7, $this->row->getColumn('closure')); - } - - private function assertColumnSavesValue($expectedValue, $columnName, $valueToSet) - { - $this->row->setColumn($columnName, $valueToSet); - $this->assertSame($expectedValue, $this->row->getColumn($columnName)); - } - - protected function getTestRowWithSubDataTableLoaded() - { - $testSubDataTable = $this->getTestSubDataTable(); - - $testRow = new Row( - array( - Row::DATATABLE_ASSOCIATED => $testSubDataTable - ) - ); - - return $testRow; - } - - protected function getTestSubDataTable() - { - return new DataTable(); - } - - protected function getTestRowWithSubDataTableNotLoaded() - { - $testRow = new Row( - array( - Row::DATATABLE_ASSOCIATED => 50 - ) - ); - - return $testRow; - } -} diff --git a/tests/PHPUnit/Core/DataTableTest.php b/tests/PHPUnit/Core/DataTableTest.php deleted file mode 100644 index afb3e168fe..0000000000 --- a/tests/PHPUnit/Core/DataTableTest.php +++ /dev/null @@ -1,856 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\Common; -use Piwik\DataTable\Manager; -use Piwik\DataTable\Row; -use Piwik\DataTable; -use Piwik\Timer; - -class DataTableTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testApplyFilter() - { - $table = $this->_getDataTable1ForTest(); - $this->assertEquals(4, $table->getRowsCount()); - $table->filter('Limit', array(2, 2)); - $this->assertEquals(2, $table->getRowsCount()); - $table->filter('Limit', array(0, 1)); - $this->assertEquals(1, $table->getRowsCount()); - } - - protected function _getSimpleTestDataTable() - { - $table = new DataTable; - $table->addRowsFromArray( - array( - array(Row::COLUMNS => array('label' => 'ten', 'count' => 10)), - array(Row::COLUMNS => array('label' => 'ninety', 'count' => 90)), - array(Row::COLUMNS => array('label' => 'hundred', 'count' => 100)), - DataTable::ID_SUMMARY_ROW => array(Row::COLUMNS => array('label' => 'summary', 'count' => 200)) - ) - ); - return $table; - } - - /** - * @group Core - */ - public function testRenameColumn() - { - $table = $this->_getSimpleTestDataTable(); - $this->assertEquals(array(10, 90, 100, 200), $table->getColumn('count')); - $table->renameColumn('count', 'renamed'); - $this->assertEquals(array(false, false, false, false), $table->getColumn('count')); - $this->assertEquals(array(10, 90, 100, 200), $table->getColumn('renamed')); - } - - /** - * @group Core - */ - public function testDeleteColumn() - { - $table = $this->_getSimpleTestDataTable(); - $this->assertEquals(array(10, 90, 100, 200), $table->getColumn('count')); - $table->deleteColumn('count'); - $this->assertEquals(array(false, false, false, false), $table->getColumn('count')); - } - - /** - * @group Core - */ - public function testDeleteRow() - { - $table = $this->_getSimpleTestDataTable(); - - // normal row - $idToDelete = 1; - $this->assertEquals(2, count($table->getRowFromId($idToDelete)->getColumns())); - $table->deleteRow($idToDelete); - $this->assertFalse($table->getRowFromId($idToDelete)); - - // summary row special case - $idToDelete = DataTable::ID_SUMMARY_ROW; - $this->assertEquals(2, count($table->getRowFromId($idToDelete)->getColumns())); - $table->deleteRow($idToDelete); - $this->assertFalse($table->getRowFromId($idToDelete)); - } - - /** - * @group Core - */ - public function testGetLastRow() - { - $table = $this->_getSimpleTestDataTable(); - $rowsCount = $table->getRowsCount(); - - $this->assertEquals($table->getLastRow(), $table->getRowFromId(DataTable::ID_SUMMARY_ROW)); - $table->deleteRow(DataTable::ID_SUMMARY_ROW); - - $this->assertEquals($table->getLastRow(), $table->getRowFromId($rowsCount - 2)); - } - - /** - * @group Core - */ - public function testGetRowFromIdSubDataTable() - { - $table1 = $this->_getDataTable1ForTest(); - $idTable1 = $table1->getId(); - $table2 = $this->_getDataTable2ForTest(); - $this->assertFalse($table2->getRowFromIdSubDataTable($idTable1)); - - $table2->getFirstRow()->addSubtable($table1); - $this->assertEquals($table2->getRowFromIdSubDataTable($idTable1), $table2->getFirstRow()); - - $table3 = $this->_getDataTable1ForTest(); - $idTable3 = $table3->getId(); - $table2->getLastRow()->addSubtable($table3); - $this->assertEquals($table2->getRowFromIdSubDataTable($idTable3), $table2->getLastRow()); - } - - /** - * we test the count rows and the count rows recursive version - * on a Simple array (1 level only) - * - * @group Core - */ - public function testCountRowsSimple() - { - - $table = new DataTable; - $idcol = Row::COLUMNS; - $rows = array( - array($idcol => array('label' => 'google')), - array($idcol => array('label' => 'ask')), - array($idcol => array('label' => 'piwik')), - array($idcol => array('label' => 'yahoo')), - array($idcol => array('label' => 'amazon')), - array($idcol => array('label' => '238975247578949')), - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))'))); - - $table->addRowsFromArray($rows); - - $this->assertEquals(count($rows), $table->getRowsCount()); - $this->assertEquals(count($rows), $table->getRowsCountRecursive()); - } - - /** - * we test the count rows and the count rows recursive version - * on a Complex array (rows with 2 and 3 levels only) - * - * the recursive count returns - * the sum of the number of rows of all the subtables - * + the number of rows in the parent table - * - * @group Core - */ - public function testCountRowsComplex() - { - - $idcol = Row::COLUMNS; - $idsubtable = Row::DATATABLE_ASSOCIATED; - - // table to go in the SUB table of RoW1 - $tableSubOfSubOfRow1 = new DataTable; - $rows1sub = array( - array($idcol => array('label' => 'google')), - array($idcol => array('label' => 'google78')), - array($idcol => array('label' => 'googlaegge')), - array($idcol => array('label' => 'gogeoggle')), - array($idcol => array('label' => 'goaegaegaogle')), - array($idcol => array('label' => 'ask')), - array($idcol => array('label' => '238975247578949')), - ); - $tableSubOfSubOfRow1->addRowsFromArray($rows1sub); - - // table to go in row1 - $tableSubOfRow1 = new DataTable; - $rows1 = array( - array($idcol => array('label' => 'google'), $idsubtable => $tableSubOfSubOfRow1), - array($idcol => array('label' => 'ask')), - array($idcol => array('label' => '238975247578949')), - ); - $tableSubOfRow1->addRowsFromArray($rows1); - - // table to go in row2 - $tableSubOfRow2 = new DataTable; - $rows2 = array( - array($idcol => array('label' => 'google')), - array($idcol => array('label' => 'ask')), - array($idcol => array('label' => '238975247578949')), - array($idcol => array('label' => 'agaegaesk')), - array($idcol => array('label' => '23g 8975247578949')), - ); - $tableSubOfRow2->addRowsFromArray($rows2); - - // main parent table - $table = new DataTable; - $rows = array( - array($idcol => array('label' => 'row1')), - array($idcol => array('label' => 'row2'), - $idsubtable => $tableSubOfRow1), - array($idcol => array('label' => 'row3'), - $idsubtable => $tableSubOfRow2), - ); - $table->addRowsFromArray($rows); - - $this->assertEquals(count($rows), $table->getRowsCount()); - $countAllRows = count($rows) + count($rows1) + count($rows2) + count($rows1sub); - $this->assertEquals($countAllRows, $table->getRowsCountRecursive()); - } - - /** - * Simple test of the DataTable_Row - * - * @group Core - */ - public function testRow() - { - $columns = array('test_column' => 145, - 092582495 => new Timer, - 'super' => array('this column has an array value, amazing')); - $metadata = array('logo' => 'piwik.png', - 'super' => array('this column has an array value, amazing')); - $arrayRow = array( - Row::COLUMNS => $columns, - Row::METADATA => $metadata, - 'fake useless key' => 38959, - 43905724897 => 'value'); - $row = new Row($arrayRow); - - $this->assertEquals($columns, $row->getColumns()); - $this->assertEquals($metadata, $row->getMetadata()); - $this->assertNull($row->getIdSubDataTable()); - - } - - /** - * Simple test of the DataTable_Row - * - * @group Core - */ - public function testSumRow() - { - $columns = array('test_int' => 145, - 'test_float' => 145.5, - 'test_float3' => 1.5, - 'test_stringint' => "145", - "test" => 'string fake', - 'integerArrayToSum' => array(1 => 1, 2 => 10.0, 3 => array(1 => 2, 2 => 3)), - ); - $metadata = array('logo' => 'piwik.png', - 'super' => array('this column has an array value, amazing')); - $arrayRow = array( - Row::COLUMNS => $columns, - Row::METADATA => $metadata, - 'fake useless key' => 38959, - 43905724897 => 'value'); - $row1 = new Row($arrayRow); - - $columns2 = array('test_int' => 5, - 'test_float' => 4.5, - 'test_float2' => 14.5, - 'test_stringint' => "5", - 0925824 => 'toto', - 'integerArrayToSum' => array(1 => 5, 2 => 5.5, 3 => array(2 => 4)), - ); - $finalRow = new Row(array(Row::COLUMNS => $columns2)); - $finalRow->sumRow($row1); - $columnsWanted = array('test_int' => 150, - 'test_float' => 150.0, - 'test_float2' => 14.5, - 'test_float3' => 1.5, - 'test_stringint' => 150, //add also strings!! - 'test' => 'string fake', - 'integerArrayToSum' => array(1 => 6, 2 => 15.5, 3 => array(1 => 2, 2 => 7)), - 0925824 => 'toto', - ); - - // Also testing that metadata is copied over - $rowWanted = new Row(array(Row::COLUMNS => $columnsWanted, Row::METADATA => $metadata)); - $this->assertTrue(Row::isEqual($rowWanted, $finalRow)); - - // testing that, 'sumRow' does not result in extra unwanted attributes being serialized - $expectedRow = 'O:19:"Piwik\DataTable\Row":1:{s:1:"c";a:3:{i:0;a:8:{s:8:"test_int";i:150;s:10:"test_float";d:150;s:11:"test_float2";d:14.5;s:14:"test_stringint";i:150;i:0;s:4:"toto";s:17:"integerArrayToSum";a:3:{i:1;i:6;i:2;d:15.5;i:3;a:2:{i:2;i:7;i:1;i:2;}}s:11:"test_float3";d:1.5;s:4:"test";s:11:"string fake";}i:1;a:2:{s:4:"logo";s:9:"piwik.png";s:5:"super";a:1:{i:0;s:39:"this column has an array value, amazing";}}i:3;N;}}'; - $this->assertEquals($expectedRow, serialize($finalRow)); - - // Testing sumRow with disabled metadata sum - $rowWanted = new Row(array(Row::COLUMNS => $columnsWanted)); // no metadata - $finalRow = new Row(array(Row::COLUMNS => $columns2)); - $finalRow->sumRow($row1, $enableCopyMetadata = false); - $this->assertTrue(Row::isEqual($rowWanted, $finalRow)); - } - - /** - * @group Core - */ - public function test_unserializeWorks_WhenDataTableFormatPriorPiwik2() - { - $serializedDatatable = ''; - // Prior Piwik 2.0, we didn't use namespaces. Some - require PIWIK_INCLUDE_PATH . "/tests/resources/pre-Piwik2-DataTable-archived.php"; - require_once PIWIK_INCLUDE_PATH . "/core/DataTable/Bridges.php"; - - $this->assertTrue(strlen($serializedDatatable) > 1000); - - $table = unserialize($serializedDatatable); - $this->assertTrue($table[0] instanceof \Piwik\DataTable\Row); - } - - /** - * Test that adding two string column values results in an exception. - * - * @group Core - * - * @expectedException Exception - */ - public function testSumRow_stringException() - { - $columns = array( - 'super' => array('this column has an array string that will be 0 when algorithm sums the value'), - ); - $row1 = new Row(array(Row::COLUMNS => $columns)); - - $columns2 = array( - 'super' => array('this column has geagaean array value, amazing'), - ); - $row2 = new Row(array(Row::COLUMNS => $columns2)); - - $row2->sumRow($row1); - $this->fail("sumRow did not throw when adding two string columns."); - } - - /** - * Test serialize with an infinite recursion (a row linked to a table in the parent hierarchy) - * After 100 recursion must throw an exception - * - * @group Core - * - * @expectedException Exception - */ - public function testSerializeWithInfiniteRecursion() - { - $table = new DataTable; - $table->addRowFromArray(array(Row::COLUMNS => array('visits' => 245, 'visitors' => 245), - Row::DATATABLE_ASSOCIATED => $table,)); - - $table->getSerialized(); - } - - /** - * Test queing filters - * - * @group Core - */ - public function testFilterQueueSortString() - { - - $idcol = Row::COLUMNS; - - $table = new DataTable; - $rows = array( - array($idcol => array('label' => 'google')), //0 - array($idcol => array('label' => 'tsk')), //1 - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))')), //2 - ); - $table->addRowsFromArray($rows); - - $expectedtable = new DataTable; - $rows = array( - array($idcol => array('label' => 'google')), //0 - array($idcol => array('label' => 'Q*(%&*("$&%*(&"$*")"))')), //2 - array($idcol => array('label' => 'tsk')), //1 - ); - $expectedtable->addRowsFromArray($rows); - - $expectedtableReverse = new DataTable; - $expectedtableReverse->addRowsFromArray(array_reverse($rows)); - - $tableCopy = clone $table; - $this->assertTrue(DataTable::isEqual($tableCopy, $table)); - - // queue the filter and check the table didnt change - $table->queueFilter("Sort", array('label', 'asc')); - $this->assertTrue(DataTable::isEqual($tableCopy, $table)); - - // apply filter and check the table is sorted - $table->applyQueuedFilters(); - $this->assertTrue(DataTable::isEqual($expectedtable, $table)); - - // apply one more filter check it hasnt changed - $table->queueFilter("Sort", array('label', 'desc')); - $this->assertTrue(DataTable::isEqual($expectedtable, $table)); - - // now apply the second sort and check it is correctly sorted - $table->applyQueuedFilters(); - $this->assertTrue(DataTable::isEqual($expectedtableReverse, $table)); - - // do one more time to make sure it doesnt change - $table->applyQueuedFilters(); - $this->assertTrue(DataTable::isEqual($expectedtableReverse, $table)); - } - - /** - * General tests that tries to test the normal behaviour of DataTable - * - * We create some tables, add rows, some of the rows link to sub tables - * - * Then we serialize everything, and we check that the unserialize give the same object back - * - * @group Core - */ - public function testGeneral() - { - /* - * create some fake tables to make sure that the serialized array of the first TABLE - * does not take in consideration those tables - */ - $useless1 = new DataTable; - $useless1->addRowFromArray(array(Row::COLUMNS => array(13,),)); - /* - * end fake tables - */ - - /* - * MAIN TABLE - */ - $table = new DataTable; - $subtable = new DataTable; - $idtable = $table->getId(); - $idsubtable = $subtable->getId(); - - /* - * create some fake tables to make sure that the serialized array of the first TABLE - * does not take in consideration those tables - * -> we check that the DataTable_Manager is not impacting DataTable - */ - $useless1->addRowFromArray(array(Row::COLUMNS => array(8487,),)); - $useless3 = new DataTable; - $useless3->addRowFromArray(array(Row::COLUMNS => array(8487,),)); - /* - * end fake tables - */ - - $row = array(Row::COLUMNS => array(0 => 1554, 1 => 42, 2 => 657, 3 => 155744,), - Row::METADATA => array('logo' => 'test.png')); - $row = new Row($row); - - $table->addRow($row); - $table->addRowFromArray(array(Row::COLUMNS => array(0 => 1554, 1 => 42,), - Row::METADATA => array('url' => 'piwik.org'))); - - $table->addRowFromArray(array(Row::COLUMNS => array(0 => 787877888787,), - Row::METADATA => array('url' => 'OUPLA ADDED'), - Row::DATATABLE_ASSOCIATED => $subtable)); - - /* - * SUB TABLE - */ - - $row = array(Row::COLUMNS => array(0 => 1554,), - Row::METADATA => array('searchengine' => 'google'), - ); - $subtable->addRowFromArray($row); - - $row = array(Row::COLUMNS => array(0 => 84894,), - Row::METADATA => array('searchengine' => 'yahoo'), - ); - $subtable->addRowFromArray($row); - $row = array(Row::COLUMNS => array(0 => 4898978989,), - Row::METADATA => array('searchengine' => 'ask'), - ); - $subtable->addRowFromArray($row); - - /* - * SUB SUB TABLE - */ - $subsubtable = new DataTable; - $subsubtable->addRowFromArray(array(Row::COLUMNS => array(245), - Row::METADATA => array('yes' => 'subsubmetadata1'),) - ); - - $subsubtable->addRowFromArray(array(Row::COLUMNS => array(13,), - Row::METADATA => array('yes' => 'subsubmetadata2'),) - ); - - $row = array(Row::COLUMNS => array(0 => 666666666666666,), - Row::METADATA => array('url' => 'NEW ROW ADDED'), - Row::DATATABLE_ASSOCIATED => $subsubtable); - - $subtable->addRowFromArray($row); - - $idsubsubtable = $subsubtable->getId(); - - $serialized = ($table->getSerialized()); - - $this->assertEquals(array_keys($serialized), array($idsubsubtable, $idsubtable, 0)); - - // In the next test we compare an unserialized datatable with its original instance. - // The unserialized datatable rows will have positive DATATABLE_ASSOCIATED ids. - // Positive DATATABLE_ASSOCIATED ids mean that the associated sub-datatables are not loaded in memory. - // In this case, this is NOT true: we know that the sub-datatable is loaded in memory. - // HOWEVER, because of datatable id conflicts happening in the datatable manager, it is not yet - // possible to know, after unserializing a datatable, if its sub-datatables are loaded in memory. - $expectedTableRows = array(); - foreach ($table->getRows() as $currentRow) { - $expectedTableRow = clone $currentRow; - - $currentRowAssociatedDatatableId = $currentRow->c[Row::DATATABLE_ASSOCIATED]; - if ($currentRowAssociatedDatatableId != null) { - // making DATATABLE_ASSOCIATED ids positive - $expectedTableRow->c[Row::DATATABLE_ASSOCIATED] = -1 * $currentRowAssociatedDatatableId; - } - - $expectedTableRows[] = $expectedTableRow; - } - - $tableAfter = new DataTable; - $tableAfter->addRowsFromSerializedArray($serialized[0]); - - $this->assertEquals($expectedTableRows, $tableAfter->getRows()); - - $subsubtableAfter = new DataTable; - $subsubtableAfter->addRowsFromSerializedArray($serialized[$idsubsubtable]); - $this->assertEquals($subsubtable->getRows(), $subsubtableAfter->getRows()); - $this->assertEquals($subsubtable->getRows(), DataTable::fromSerializedArray($serialized[$idsubsubtable])->getRows()); - $this->assertTrue($subsubtable->getRowsCount() > 0); - - $this->assertEquals($table, Manager::getInstance()->getTable($idtable)); - $this->assertEquals($subsubtable, Manager::getInstance()->getTable($idsubsubtable)); - } - - /** - * for all datatable->addDatatable tests we check that - * - row uniqueness is based on the label + presence of the SUBTABLE id - * => the label is the criteria used to match 2 rows in 2 datatable - * - no metadata are lost in the first datatable rows that have been changed - * - when a subtable - */ - - /** - * add an empty datatable to a normal datatable - * - * @group Core - */ - public function testAddSimpleNoRowTable2() - { - $table = $this->_getDataTable1ForTest(); - $tableEmpty = new DataTable; - $tableAfter = clone $table; - $tableAfter->addDataTable($tableEmpty); - $this->assertTrue(DataTable::isEqual($table, $tableAfter)); - } - - /** - * add a normal datatable to an empty datatable - * - * @group Core - */ - public function testAddSimpleNoRowTable1() - { - $table = $this->_getDataTable1ForTest(); - $tableEmpty = new DataTable; - $tableEmpty->addDataTable($table); - $this->assertTrue(DataTable::isEqual($tableEmpty, $table)); - } - - /** - * add to the datatable another datatable// they don't have any row in common - * - * @group Core - */ - public function testAddSimpleNoCommonRow() - { - $table1 = $this->_getDataTable1ForTest(); - $table2 = $this->_getDataTable2ForTest(); - - $table1->addDataTable($table2); - - $rowsExpected = array_merge($this->_getRowsDataTable1ForTest(), $this->_getRowsDataTable2ForTest()); - $tableExpected = new DataTable; - $tableExpected->addRowsFromArray($rowsExpected); - - $this->assertTrue(DataTable::isEqual($table1, $tableExpected)); - } - - /** - * add 2 datatable with some common rows - * - * @group Core - */ - public function testAddSimpleSomeCommonRow() - { - - $idcol = Row::COLUMNS; - - $rows = array( - array($idcol => array('label' => 'google', 'visits' => 1)), - array($idcol => array('label' => 'ask', 'visits' => 2)), - array($idcol => array('label' => '123', 'visits' => 2)), - DataTable::ID_SUMMARY_ROW => array($idcol => array('label' => DataTable::LABEL_SUMMARY_ROW, 'visits' => 7)) - ); - $table = new DataTable; - $table->addRowsFromArray($rows); - - $rows2 = array( - array($idcol => array('label' => 'test', 'visits' => 1)), - array($idcol => array('label' => 'ask', 'visits' => 111)), - array($idcol => array('label' => ' google ', 'visits' => 5)), - array($idcol => array('label' => '123', 'visits' => 2)), - ); - $table2 = new DataTable; - $table2->addRowsFromArray($rows2); - - $table->addDataTable($table2); - - $rowsExpected = array( - array($idcol => array('label' => 'google', 'visits' => 1)), - array($idcol => array('label' => 'ask', 'visits' => 113)), - array($idcol => array('label' => '123', 'visits' => 4)), - array($idcol => array('label' => 'test', 'visits' => 1)), - array($idcol => array('label' => ' google ', 'visits' => 5)), - DataTable::ID_SUMMARY_ROW => array($idcol => array('label' => DataTable::LABEL_SUMMARY_ROW, 'visits' => 7)) - ); - $tableExpected = new DataTable; - $tableExpected->addRowsFromArray($rowsExpected); - - $this->assertTrue(DataTable::isEqual($table, $tableExpected)); - } - - /** - * add 2 datatable with only common rows - * - * @group Core - */ - public function testAddSimpleAllCommonRow() - { - $idcol = Row::COLUMNS; - - $rows = array( - array($idcol => array('label' => 'google', 'visits' => 1)), - array($idcol => array('label' => 'ask', 'visits' => 2)), - array($idcol => array('label' => '123', 'visits' => 2)), - DataTable::ID_SUMMARY_ROW => array($idcol => array('label' => DataTable::LABEL_SUMMARY_ROW, 'visits' => 7)) - ); - $table = new DataTable; - $table->addRowsFromArray($rows); - - $rows2 = array( - array($idcol => array('label' => 'google', 'visits' => -1)), - array($idcol => array('label' => 'ask', 'visits' => 0)), - array($idcol => array('label' => '123', 'visits' => 1.5)), - DataTable::ID_SUMMARY_ROW => array($idcol => array('label' => DataTable::LABEL_SUMMARY_ROW, 'visits' => 8)) - ); - $table2 = new DataTable; - $table2->addRowsFromArray($rows2); - - $table->addDataTable($table2); - - $rowsExpected = array( - array($idcol => array('label' => 'google', 'visits' => 0)), - array($idcol => array('label' => 'ask', 'visits' => 2)), - array($idcol => array('label' => '123', 'visits' => 3.5)), - DataTable::ID_SUMMARY_ROW => array($idcol => array('label' => DataTable::LABEL_SUMMARY_ROW, 'visits' => 15)) - ); - $tableExpected = new DataTable; - $tableExpected->addRowsFromArray($rowsExpected); - - $this->assertTrue(DataTable::isEqual($table, $tableExpected)); - } - - /** - * test add 2 different tables to the same table - * - * @group Core - */ - public function testAddDataTable2times() - { - - $idcol = Row::COLUMNS; - - $rows = array( - array($idcol => array('label' => 'google', 'visits' => 1)), - array($idcol => array('label' => 'ask', 'visits' => 0)), - array($idcol => array('label' => '123', 'visits' => 2)), - DataTable::ID_SUMMARY_ROW => array($idcol => array('label' => DataTable::LABEL_SUMMARY_ROW, 'visits' => 1)) - ); - $table = new DataTable; - $table->addRowsFromArray($rows); - - $rows2 = array( - array($idcol => array('label' => 'google2', 'visits' => -1)), - array($idcol => array('label' => 'ask', 'visits' => 100)), - array($idcol => array('label' => '123456', 'visits' => 1.5)), - ); - $table2 = new DataTable; - $table2->addRowsFromArray($rows2); - - $rows3 = array( - array($idcol => array('label' => 'google2', 'visits' => -1)), - array($idcol => array('label' => 'ask', 'visits' => -10)), - array($idcol => array('label' => '123ab', 'visits' => 1.5)), - DataTable::ID_SUMMARY_ROW => array($idcol => array('label' => DataTable::LABEL_SUMMARY_ROW, 'visits' => 3)) - ); - $table3 = new DataTable; - $table3->addRowsFromArray($rows3); - - // add the 2 tables - $table->addDataTable($table2); - $table->addDataTable($table3); - - $rowsExpected = array( - array($idcol => array('label' => 'google', 'visits' => 1)), - array($idcol => array('label' => 'ask', 'visits' => 90)), - array($idcol => array('label' => '123', 'visits' => 2)), - array($idcol => array('label' => 'google2', 'visits' => -2)), - array($idcol => array('label' => '123456', 'visits' => 1.5)), - array($idcol => array('label' => '123ab', 'visits' => 1.5)), - DataTable::ID_SUMMARY_ROW => array($idcol => array('label' => DataTable::LABEL_SUMMARY_ROW, 'visits' => 4)) - ); - $tableExpected = new DataTable; - $tableExpected->addRowsFromArray($rowsExpected); - - $this->assertTrue(DataTable::isEqual($table, $tableExpected)); - } - - /** - * @group Core - */ - public function testUnrelatedDataTableNotDestructed() - { - $mockedDataTable = $this->getMock('\Piwik\DataTable', array('__destruct')); - $mockedDataTable->expects($this->never())->method('__destruct'); - - $rowBeingDestructed = new Row(); - - // we simulate the fact that the value of Row::DATATABLE_ASSOCIATED retrieved - // from the database is in conflict with one of the Manager managed table identifiers. - // This is a rare but legitimate case as identifiers are not thoroughly synchronized - // when the expanded parameter is false. - $rowBeingDestructed->c[Row::DATATABLE_ASSOCIATED] = $mockedDataTable->getId(); - - Common::destroy($rowBeingDestructed); - } - - /** - * @group Core - */ - public function testGetSerializedCallsCleanPostSerialize() - { - $mockedDataTableRow = $this->getMock('\Piwik\DataTable\Row', array('cleanPostSerialize')); - $mockedDataTableRow->expects($this->once())->method('cleanPostSerialize'); - - $dataTableBeingSerialized = new DataTable(); - $dataTableBeingSerialized->addRow($mockedDataTableRow); - - $dataTableBeingSerialized->getSerialized(); - } - - /** - * @group Core - */ - public function testSubDataTableIsDestructed() - { - $mockedDataTable = $this->getMock('\Piwik\DataTable', array('__destruct')); - $mockedDataTable->expects($this->once())->method('__destruct'); - - $rowBeingDestructed = new Row(); - $rowBeingDestructed->setSubtable($mockedDataTable); - - Common::destroy($rowBeingDestructed); - } - - /** - * @group Core - */ - public function test_serializeFails_onSubTableNotFound() - { - // create a simple table with a subtable - $table1 = $this->_getDataTable1ForTest(); - $table2 = $this->_getDataTable2ForTest(); - $table2->getFirstRow()->addSubtable($table1); - $idSubtable = $table1->getId(); - - /* Check it looks good: - $renderer = DataTable\Renderer::factory('xml'); - $renderer->setTable($table2); - $renderer->setRenderSubTables(true); - echo $renderer->render(); - */ - - // test serialize: - // - subtable is serialized as expected - $serializedStrings = $table2->getSerialized(); - - // both the main table and the sub table are serialized - $this->assertEquals(sizeof($serializedStrings), 2); - $serialized = implode(",", $serializedStrings); - - // the serialized string references the id subtable - $this->assertTrue( false !== strpos($serialized, 'i:' . $idSubtable), "not found the id sub table in the serialized, not expected"); - - // KABOOM, we delete the subtable, reproducing a "random data issue" - Manager::getInstance()->deleteTable($idSubtable); - - // Now we will serialize this "broken datatable" and check it works. - - // - it does not throw an exception - $serializedStrings = $table2->getSerialized(); - - // - the serialized table does NOT contain the sub table - $this->assertEquals(sizeof($serializedStrings), 1); // main table only is serialized - $serialized = implode(",", $serializedStrings); - - // - the serialized string does NOT contain the id subtable (the row was cleaned up as expected) - $this->assertTrue( false === strpos($serialized, 'i:' . $idSubtable), "found the id sub table in the serialized, not expected"); - - } - - protected function _getDataTable1ForTest() - { - $rows = $this->_getRowsDataTable1ForTest(); - $table = new DataTable; - $table->addRowsFromArray($rows); - return $table; - } - - protected function _getDataTable2ForTest() - { - $rows = $this->_getRowsDataTable2ForTest(); - $table = new DataTable; - $table->addRowsFromArray($rows); - return $table; - } - - protected function _getRowsDataTable1ForTest() - { - $rows = array( - array(Row::COLUMNS => array('label' => 'google', 'visits' => 1)), - array(Row::COLUMNS => array('label' => 'ask', 'visits' => 2)), - array(Row::COLUMNS => array('label' => '123', 'visits' => 2)), - DataTable::ID_SUMMARY_ROW => array(Row::COLUMNS => array('label' => DataTable::LABEL_SUMMARY_ROW, 'visits' => 4)) - - ); - return $rows; - } - - protected function _getRowsDataTable2ForTest() - { - $rows = array( - array(Row::COLUMNS => array('label' => 'test', 'visits' => 1)), - array(Row::COLUMNS => array('label' => ' google ', 'visits' => 3)), - array(Row::COLUMNS => array('label' => '123a', 'visits' => 2)), - ); - return $rows; - } - -} diff --git a/tests/PHPUnit/Core/DateTest.php b/tests/PHPUnit/Core/DateTest.php deleted file mode 100644 index 84041f53fd..0000000000 --- a/tests/PHPUnit/Core/DateTest.php +++ /dev/null @@ -1,293 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Date; -use Piwik\SettingsServer; - -/** - * @group Core_DateTest - */ -class DateTest extends PHPUnit_Framework_TestCase -{ - /** - * create today object check that timestamp is correct (midnight) - * - * @group Core - */ - public function testToday() - { - $date = Date::today(); - $this->assertEquals(strtotime(date("Y-m-d ") . " 00:00:00"), $date->getTimestamp()); - - // test getDatetime() - $this->assertEquals($date->getDatetime(), $date->getDateStartUTC()); - $date = $date->setTime('12:00:00'); - $this->assertEquals(date('Y-m-d') . ' 12:00:00', $date->getDatetime()); - } - - /** - * create today object check that timestamp is correct (midnight) - * - * @group Core - */ - public function testYesterday() - { - $date = Date::yesterday(); - $this->assertEquals(strtotime(date("Y-m-d", strtotime('-1day')) . " 00:00:00"), $date->getTimestamp()); - } - - /** - * @group Core - */ - public function testInvalidDateThrowsException() - { - try { - Date::factory('0001-01-01'); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * @group Core - */ - public function testFactoryTimezone() - { - // now in UTC converted to UTC+10 means adding 10 hours - $date = Date::factory('now', 'UTC+10'); - $dateExpected = Date::now()->addHour(10); - $this->assertEquals($dateExpected->getDatetime(), $date->getDatetime()); - - // Congo is in UTC+1 all year long (no DST) - $dateExpected = Date::factory('now')->addHour(1); - $date = Date::factory('now', 'Africa/Brazzaville'); - $this->assertEquals($dateExpected->getDatetime(), $date->getDatetime()); - - // yesterday same time in Congo is the same as today in Congo - 24 hours - $date = Date::factory('yesterdaySameTime', 'Africa/Brazzaville'); - $dateExpected = Date::factory('now', 'Africa/Brazzaville')->subHour(24); - $this->assertEquals($dateExpected->getDatetime(), $date->getDatetime()); - - if (SettingsServer::isTimezoneSupportEnabled()) { - // convert to/from local time - $now = time(); - $date = Date::factory($now, 'America/New_York'); - $time = $date->getTimestamp(); - $this->assertTrue($time < $now); - - $date = Date::factory($time)->setTimezone('America/New_York'); - $time = $date->getTimestamp(); - $this->assertEquals($now, $time); - } - } - - /** - * @group Core - */ - public function testSetTimezoneDayInUTC() - { - $date = Date::factory('2010-01-01'); - - $dayStart = '2010-01-01 00:00:00'; - $dayEnd = '2010-01-01 23:59:59'; - $this->assertEquals($dayStart, $date->getDateStartUTC()); - $this->assertEquals($dayEnd, $date->getDateEndUTC()); - - // try with empty timezone - $date = $date->setTimezone(''); - $this->assertEquals($dayStart, $date->getDateStartUTC()); - $this->assertEquals($dayEnd, $date->getDateEndUTC()); - - $date = $date->setTimezone('UTC'); - $this->assertEquals($dayStart, $date->getDateStartUTC()); - $this->assertEquals($dayEnd, $date->getDateEndUTC()); - - if (SettingsServer::isTimezoneSupportEnabled()) { - $date = $date->setTimezone('Europe/Paris'); - $utcDayStart = '2009-12-31 23:00:00'; - $utcDayEnd = '2010-01-01 22:59:59'; - $this->assertEquals($utcDayStart, $date->getDateStartUTC()); - $this->assertEquals($utcDayEnd, $date->getDateEndUTC()); - } - - $date = $date->setTimezone('UTC+1'); - $utcDayStart = '2009-12-31 23:00:00'; - $utcDayEnd = '2010-01-01 22:59:59'; - $this->assertEquals($utcDayStart, $date->getDateStartUTC()); - $this->assertEquals($utcDayEnd, $date->getDateEndUTC()); - - $date = $date->setTimezone('UTC-1'); - $utcDayStart = '2010-01-01 01:00:00'; - $utcDayEnd = '2010-01-02 00:59:59'; - $this->assertEquals($utcDayStart, $date->getDateStartUTC()); - $this->assertEquals($utcDayEnd, $date->getDateEndUTC()); - - if (SettingsServer::isTimezoneSupportEnabled()) { - $date = $date->setTimezone('America/Vancouver'); - $utcDayStart = '2010-01-01 08:00:00'; - $utcDayEnd = '2010-01-02 07:59:59'; - $this->assertEquals($utcDayStart, $date->getDateStartUTC()); - $this->assertEquals($utcDayEnd, $date->getDateEndUTC()); - } - } - - /** - * @group Core - */ - public function testModifyDateWithTimezone() - { - $date = Date::factory('2010-01-01'); - $date = $date->setTimezone('UTC-1'); - - $timestamp = $date->getTimestamp(); - $date = $date->addHour(0)->addHour(0)->addHour(0); - $this->assertEquals($timestamp, $date->getTimestamp()); - - if (SettingsServer::isTimezoneSupportEnabled()) { - $date = Date::factory('2010-01-01')->setTimezone('Europe/Paris'); - $dateExpected = clone $date; - $date = $date->addHour(2); - $dateExpected = $dateExpected->addHour(1.1)->addHour(0.9)->addHour(1)->subHour(1); - $this->assertEquals($dateExpected->getTimestamp(), $date->getTimestamp()); - } - } - - /** - * @group Core - */ - public function testGetDateStartUTCEndDuringDstTimezone() - { - if (SettingsServer::isTimezoneSupportEnabled()) { - $date = Date::factory('2010-03-28'); - - $date = $date->setTimezone('Europe/Paris'); - $utcDayStart = '2010-03-27 23:00:00'; - $utcDayEnd = '2010-03-28 21:59:59'; - - $this->assertEquals($utcDayStart, $date->getDateStartUTC()); - $this->assertEquals($utcDayEnd, $date->getDateEndUTC()); - } - } - - /** - * @group Core - */ - public function testAddHour() - { - // add partial hours less than 1 - $dayStart = '2010-03-28 00:00:00'; - $dayExpected = '2010-03-28 00:18:00'; - $date = Date::factory($dayStart)->addHour(0.3); - $this->assertEquals($dayExpected, $date->getDatetime()); - $date = $date->subHour(0.3); - $this->assertEquals($dayStart, $date->getDatetime()); - - // add partial hours - $dayExpected = '2010-03-28 05:45:00'; - $date = Date::factory($dayStart)->addHour(5.75); - $this->assertEquals($dayExpected, $date->getDatetime()); - - // remove partial hours - $dayExpected = '2010-03-27 18:15:00'; - $date = Date::factory($dayStart)->subHour(5.75); - $this->assertEquals($dayExpected, $date->getDatetime()); - } - - /** - * @group Core - */ - public function testAddHourLongHours() - { - $dateTime = '2010-01-03 11:22:33'; - $expectedTime = '2010-01-05 11:28:33'; - $this->assertEquals($expectedTime, Date::factory($dateTime)->addHour(48.1)->getDatetime()); - $this->assertEquals($dateTime, Date::factory($dateTime)->addHour(48.1)->subHour(48.1)->getDatetime()); - } - - /** - * @group Core - */ - public function testAddPeriod() - { - $date = Date::factory('2010-01-01'); - $dateExpected = Date::factory('2010-01-06'); - $date = $date->addPeriod(5, 'day'); - $this->assertEquals($dateExpected->getTimestamp(), $date->getTimestamp()); - - $date = Date::factory('2010-03-01'); - $dateExpected = Date::factory('2010-04-05'); - $date = $date->addPeriod(5, 'week'); - $this->assertEquals($dateExpected->getTimestamp(), $date->getTimestamp()); - } - - /** - * @group Core - */ - public function testSubPeriod() - { - $date = Date::factory('2010-03-01'); - $dateExpected = Date::factory('2010-02-15'); - $date = $date->subPeriod(2, 'week'); - $this->assertEquals($dateExpected->getTimestamp(), $date->getTimestamp()); - - $date = Date::factory('2010-12-15'); - $dateExpected = Date::factory('2005-12-15'); - $date = $date->subPeriod(5, 'year'); - $this->assertEquals($dateExpected->getTimestamp(), $date->getTimestamp()); - } - - /** - * @group Core - */ - public function testAddPeriodMonthRespectsMaxDaysInMonth() - { - $date = Date::factory('2014-07-31'); - $dateExpected = Date::factory('2014-06-30'); - $dateActual = $date->subPeriod(1, 'month'); - $this->assertEquals($dateExpected->toString(), $dateActual->toString()); - - // test leap year - $date = Date::factory('2000-03-31'); - $dateExpected = Date::factory('2000-02-29'); - $dateActual = $date->subPeriod(1, 'month'); - $this->assertEquals($dateExpected->toString(), $dateActual->toString()); - - $date = Date::factory('2000-01-31'); - $dateExpected = Date::factory('2000-02-29'); - $dateActual = $date->addPeriod(1, 'month'); - $this->assertEquals($dateExpected->toString(), $dateActual->toString()); - } - - /** - * @group Core - */ - public function testIsLeapYear() - { - $date = Date::factory('2011-03-01'); - $this->assertFalse($date->isLeapYear()); - $date = Date::factory('2011-01-01'); - $this->assertFalse($date->isLeapYear()); - $date = Date::factory('2011-01-31'); - $this->assertFalse($date->isLeapYear()); - - $date = Date::factory('2012-01-01'); - $this->assertTrue($date->isLeapYear()); - $date = Date::factory('2012-12-31'); - $this->assertTrue($date->isLeapYear()); - - $date = Date::factory('2013-01-01'); - $this->assertFalse($date->isLeapYear()); - $date = Date::factory('2013-12-31'); - $this->assertFalse($date->isLeapYear()); - - if (PHP_INT_SIZE > 4) { // dates after 19/01/2038 03:14:07 fail on 32-bit arch - $date = Date::factory('2052-01-01'); - $this->assertTrue($date->isLeapYear()); - } - } -} diff --git a/tests/PHPUnit/Core/DependencyTest.php b/tests/PHPUnit/Core/DependencyTest.php deleted file mode 100644 index 3c7b783e95..0000000000 --- a/tests/PHPUnit/Core/DependencyTest.php +++ /dev/null @@ -1,284 +0,0 @@ -<?php -use Piwik\Plugin\Dependency; -use Piwik\Plugin\Manager as PluginManager; -use Piwik\Version; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * @group Core - */ -class DependencyTest extends PHPUnit_Framework_TestCase -{ - /** - * @var Dependency - */ - private $dependency; - - public function setUp() - { - parent::setUp(); - $this->dependency = new Dependency(); - } - - public function test_getMissingDependencies_shouldReturnEmptyArray_IfNoInputGiven() - { - $this->assertMissingDependency(null, array()); - $this->assertMissingDependency(array(), array()); - } - - public function test_getMissingDependencies_EmptyVersion_ShouldBeIgnored() - { - $this->assertMissingDependency(array('php' => ''), array()); - } - - public function test_getMissingDependencies_multipleConditions() - { - $this->assertMissingDependency(array('php' => '<5.2', 'piwik' => '<2.0'), array( - $this->missingPhp('<5.2'), - $this->missingPiwik('<2.0') - )); - - $this->assertMissingDependency(array('php' => '<5.2', 'piwik' => '<9.0'), array( - $this->missingPhp('<5.2') - )); - - $this->assertMissingDependency(array('php' => '<9.2', 'piwik' => '<2.0'), array( - $this->missingPiwik('<2.0') - )); - - $this->assertMissingDependency(array('php' => '<9.2', 'piwik' => '<9.0'), array()); - } - - public function test_getMissingDependencies_multipleConditions_differentConditions() - { - $this->assertMissingDependency(array('php' => '<5.2', 'piwik' => '>2.0'), array( - $this->missingPhp('<5.2') - )); - - $this->assertMissingDependency(array('php' => '>=5.3', 'piwik' => '<2.0'), array( - $this->missingPiwik('<2.0') - )); - - $this->assertMissingDependency(array('php' => '!=' . PHP_VERSION, 'piwik' => '<>' . Version::VERSION), array( - $this->missingPhp('!=' . PHP_VERSION), - $this->missingPiwik('<>' . Version::VERSION) - )); - } - - public function test_getMissingVersion_AND_Condition() - { - $this->assertMissingDependency(array('php' => '<2.0,>=9.0', 'piwik' => '<2.0'), array( - $this->missingPhp('<2.0,>=9.0', '<2.0, >=9.0'), - $this->missingPiwik('<2.0') - )); - } - - public function test_getMissingDependencies_detectsPHPVersion() - { - $this->assertMissingDependency(array('php' => '>=2.1'), array()); - $this->assertMissingDependency(array('php' => '>=' . PHP_VERSION), array()); - $this->assertMissingDependency(array('php' => '>' . PHP_VERSION), array( - $this->missingPhp('>' . PHP_VERSION) - )); - $this->assertMissingDependency(array('php' => '>=9.2'), array( - $this->missingPhp('>=9.2') - )); - } - - public function test_getMissingDependencies_detectsPiwikVersion() - { - $this->assertMissingDependency(array('piwik' => '>=2.1'), array()); - $this->assertMissingDependency(array('piwik' => '>=' . Version::VERSION), array()); - $this->assertMissingDependency(array('piwik' => '>' . Version::VERSION), array( - $this->missingPiwik('>' . Version::VERSION) - )); - $this->assertMissingDependency(array('piwik' => '>=9.2'), array( - $this->missingPiwik('>=9.2') - )); - } - - public function test_getMissingDependencies_detectUnknownDependencyName() - { - $this->assertMissingDependency(array('unkNowN' => '>99.99'), array( - $this->buildMissingDependecy('unkNowN', '', '>99.99') - )); - $this->assertMissingDependency(array('unkNowN' => '>=0.01'), array( - $this->buildMissingDependecy('unkNowN', '', '>=0.01') - )); - } - - public function test_getMissingDependencies_detectsPluginVersion() - { - PluginManager::getInstance()->returnLoadedPluginsInfo(); - - $this->assertMissingDependency(array('Annotations' => '>=2.1'), array()); - $this->assertMissingDependency(array('Annotations' => '>=' . Version::VERSION), array()); - $this->assertMissingDependency(array('Annotations' => '>' . Version::VERSION), array( - $this->buildMissingDependecy('Annotations', Version::VERSION, '>' . Version::VERSION) - )); - $this->assertMissingDependency(array('Annotations' => '>=9.2'), array( - $this->buildMissingDependecy('Annotations', Version::VERSION, '>=9.2') - )); - } - - public function test_getMissingDependencies_setPiwikVersion() - { - $this->assertMissingDependency(array('piwik' => '>=9.2'), array($this->missingPiwik('>=9.2'))); - - $this->dependency->setPiwikVersion('9.2'); - - $this->assertMissingDependency(array('piwik' => '>=9.2'), array()); - } - - public function test_getMissingVersion_EmptyCurrentAndRequiredVersion_ShouldBeIgnored() - { - $this->assertMissingVersion(null, null, array()); - $this->assertMissingVersion('', '', array()); - } - - public function test_getMissingVersion_EmptyCurrentVersion_ShouldBeDeclaredAsMissing() - { - $this->assertMissingVersion('', '5.5', array('>=5.5')); - } - - public function test_getMissingVersion_EmptyRequiredVersion_ShouldBeIgnored() - { - $this->assertMissingVersion('5.5', '', array()); - } - - public function test_getMissingVersion_shouldIgnoreAnyWhitespace() - { - $this->assertMissingVersion('5.5 ', '5.5', array()); - $this->assertMissingVersion(' 5.5 ', '5.5', array()); - $this->assertMissingVersion('5.5', ' 5.5', array()); - $this->assertMissingVersion('5.5', ' 5.5 ', array()); - } - - public function test_getMissingVersion_NoComparisonDefined_ShouldUseGreatherThanOrEqualByDefault() - { - $this->assertMissingVersion('5.4', '5.2', array()); - $this->assertMissingVersion('5.4', '5.4', array()); - $this->assertMissingVersion('5.4', '9.2', array('>=9.2')); - } - - public function test_getMissingVersion_GreatherThanOrEqual() - { - $this->assertMissingVersion('5.4', '>=5.2', array()); - $this->assertMissingVersion('5.4', '>=5.4', array()); - $this->assertMissingVersion('5.4', '>=9.2', array('>=9.2')); - } - - public function test_getMissingVersion_GreatherThan() - { - $this->assertMissingVersion('5.4', '>5.2', array()); - $this->assertMissingVersion('5.4', '>5.4', array('>5.4')); - $this->assertMissingVersion('5.4', '>9.2', array('>9.2')); - } - - public function test_getMissingVersion_LowerThanOrEqual() - { - $this->assertMissingVersion('5.4', '<=5.2', array('<=5.2')); - $this->assertMissingVersion('5.4', '<=5.4', array()); - $this->assertMissingVersion('5.4', '<=9.2', array()); - } - - public function test_getMissingVersion_lowerThan() - { - $this->assertMissingVersion('5.4', '<5.2', array('<5.2')); - $this->assertMissingVersion('5.4', '<5.4', array('<5.4')); - $this->assertMissingVersion('5.4', '<9.2', array()); - } - - public function test_getMissingVersion_notEqual() - { - $this->assertMissingVersion('5.4', '<>5.2', array()); - $this->assertMissingVersion('5.4', '<>5.4', array('<>5.4')); - $this->assertMissingVersion('5.4', '<>9.2', array()); - } - - public function test_getMissingVersion_notEqualUsingBang() - { - $this->assertMissingVersion('5.4', '!=5.2', array()); - $this->assertMissingVersion('5.4', '!=5.4', array('!=5.4')); - $this->assertMissingVersion('5.4', '!=9.2', array()); - } - - public function test_getMissingVersion_exact() - { - $this->assertMissingVersion('5.4', '==5.2', array('==5.2')); - $this->assertMissingVersion('5.4', '==5.4', array()); - $this->assertMissingVersion('5.4', '==9.2', array('==9.2')); - } - - public function test_getMissingVersion_AND_Condition_returnsOnlyNonMatchingVersions() - { - $this->assertMissingVersion('5.4', '<5.2,>9.0', array('<5.2', '>9.0')); - $this->assertMissingVersion('5.4', '>5.2,<9.0', array()); - $this->assertMissingVersion('5.4', '>5.2,<9.0,<2.0', array('<2.0')); - $this->assertMissingVersion('5.4', '>5.2,<9.0,<2.0,>=9.0', array('<2.0', '>=9.0')); - $this->assertMissingVersion('5.4', '<2.0,>=9.0', array('<2.0', '>=9.0')); - } - - public function test_getMissingVersion_AND_Condition_shouldIgnoreAnyWhitespace() - { - $this->assertMissingVersion('5.2', '5.5 , 5.4, 5.3', array('>=5.5', '>=5.4', '>=5.3')); - $this->assertMissingVersion('5.5', '5.5 , 5.4, 5.3', array()); - $this->assertMissingVersion(' 5.2 ', '5.5 , 5.4, 5.3', array('>=5.5', '>=5.4', '>=5.3')); - $this->assertMissingVersion(' 5.2 ', '>5.5 , <5.4, ==5.3', array('>5.5', '==5.3')); - $this->assertMissingVersion(' 5.2 ', '>5.5 , !=5.4, ==5.3', array('>5.5', '==5.3')); - } - - public function test_getMissingVersion() - { - $this->assertMissingVersion('5.2', '<5.2,>9.0', array('<5.2', '>9.0')); - $this->assertMissingVersion('5.2', '<=5.2,>9.0', array('>9.0')); - $this->assertMissingVersion('5.1', '<5.2,>9.0', array('>9.0')); - $this->assertMissingVersion('9.1', '<5.2,>9.0', array('<5.2')); - $this->assertMissingVersion('5.2', '>=5.2,<=9.0', array()); - $this->assertMissingVersion('9.0', '>=5.2,<=9.0', array()); - $this->assertMissingVersion('6.4', '>=5.2,<=9.0', array()); - } - - private function missingPiwik($requiredVersion, $causedBy = null) - { - return $this->buildMissingDependecy('piwik', Version::VERSION, $requiredVersion, $causedBy); - } - - private function missingPhp($requiredVersion, $causedBy = null) - { - return $this->buildMissingDependecy('php', PHP_VERSION, $requiredVersion, $causedBy); - } - - private function buildMissingDependecy($name, $currentVersion, $requiredVersion, $causedBy = null) - { - if (is_null($causedBy)) { - $causedBy = $requiredVersion; - } - - return array( - 'requirement' => $name, - 'actualVersion' => $currentVersion, - 'requiredVersion' => $requiredVersion, - 'causedBy' => $causedBy - ); - } - - private function assertMissingDependency($requires, $expectedMissing) - { - $missing = $this->dependency->getMissingDependencies($requires); - - $this->assertEquals($expectedMissing, $missing); - } - - private function assertMissingVersion($currentVersion, $requiredVersion, $expectedMissing) - { - $missing = $this->dependency->getMissingVersions($currentVersion, $requiredVersion); - - $this->assertEquals($expectedMissing, $missing); - } - -} - diff --git a/tests/PHPUnit/Core/DeprecatedMethodsTest.php b/tests/PHPUnit/Core/DeprecatedMethodsTest.php deleted file mode 100644 index 6bbcc64110..0000000000 --- a/tests/PHPUnit/Core/DeprecatedMethodsTest.php +++ /dev/null @@ -1,72 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\AssetManager; -use Piwik\AssetManager\UIAsset; -use Piwik\Plugin; - -/** - * @group Core - */ -class DeprecatedMethodsTest extends PHPUnit_Framework_TestCase -{ - - public function test_version2_0_4() - { - $validTill = '2014-10-20'; - $this->assertDeprecatedMethodIsRemoved('\Piwik\Period', 'factory', $validTill); - - $validTill = '2014-10-20'; - $this->assertDeprecatedMethodIsRemoved('\Piwik\Config', 'getConfigSuperUserForBackwardCompatibility', $validTill); - $this->assertDeprecatedMethodIsRemoved('\Piwik\Menu\MenuAdmin', 'addEntry', $validTill); - $this->assertDeprecatedMethodIsRemoved('\Piwik\Menu\MenuAdmin', 'removeEntry', $validTill); - $this->assertDeprecatedMethodIsRemoved('\Piwik\Menu\MenuTop', 'addEntry', $validTill); - $this->assertDeprecatedMethodIsRemoved('\Piwik\Menu\MenuTop', 'removeEntry', $validTill); - - $validTill = '2014-10-20'; - $this->assertDeprecatedMethodIsRemoved('\Piwik\SettingsPiwik', 'rewriteTmpPathWithHostname', $validTill); - - $this->assertDeprecatedMethodIsRemovedInPiwik3('\Piwik\Menu\MenuAbstract', 'add'); - } - - private function assertDeprecatedMethodIsRemoved($className, $method, $removalDate) - { - $now = \Piwik\Date::now(); - $removalDate = \Piwik\Date::factory($removalDate); - - $class = new ReflectionClass($className); - $methodExists = $class->hasMethod($method); - - if (!$now->isLater($removalDate)) { - - $errorMessage = $className . '::' . $method . ' should still exists until ' . $removalDate . ' although it is deprecated.'; - $this->assertTrue($methodExists, $errorMessage); - return; - } - - $errorMessage = $className . '::' . $method . ' should be removed as the method is deprecated but it is not.'; - $this->assertFalse($methodExists, $errorMessage); - } - - private function assertDeprecatedMethodIsRemovedInPiwik3($className, $method) - { - $version = \Piwik\Version::VERSION; - - $class = new ReflectionClass($className); - $methodExists = $class->hasMethod($method); - - if (-1 === version_compare($version, '3.0.0')) { - - $errorMessage = $className . '::' . $method . ' should still exists until 3.0 although it is deprecated.'; - $this->assertTrue($methodExists, $errorMessage); - return; - } - - $errorMessage = $className . '::' . $method . ' should be removed as the method is deprecated but it is not.'; - $this->assertFalse($methodExists, $errorMessage); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/FactoryTest.php b/tests/PHPUnit/Core/FactoryTest.php deleted file mode 100644 index d85efcc2ce..0000000000 --- a/tests/PHPUnit/Core/FactoryTest.php +++ /dev/null @@ -1,33 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\BaseFactory; - -/** - * @group Core - * @group Core_FactoryTest - */ -class FactoryTest extends PHPUnit_Framework_TestCase -{ - public function testCreatingExistingClassSucceeds() - { - $instance = BaseFactory::factory("Piwik\\Timer"); - - $this->assertNotNull($instance); - $this->assertInstanceOf("Piwik\\Timer", $instance); - } - - /** - * @expectedException Exception - * @expectedExceptionMessage Invalid class ID - */ - public function testCreatingInvalidClassThrows() - { - BaseFactory::factory("This\\Class\\Does\\Not\\Exist"); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/FilesystemTest.php b/tests/PHPUnit/Core/FilesystemTest.php deleted file mode 100644 index 26518c1a08..0000000000 --- a/tests/PHPUnit/Core/FilesystemTest.php +++ /dev/null @@ -1,245 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Filesystem; - -/** - * @group Core - */ -class FilesystemTest extends PHPUnit_Framework_TestCase -{ - private $testPath; - - public function setUp() - { - parent::setUp(); - $this->testPath = PIWIK_INCLUDE_PATH . '/tmp/filesystemtest'; - Filesystem::mkdir($this->testPath); - } - - public function tearDown() - { - Filesystem::unlinkRecursive($this->testPath, true); - - parent::tearDown(); - } - - public function test_sortFilesDescByPathLength_shouldNotFail_IfEmptyArrayGiven() - { - $result = Filesystem::sortFilesDescByPathLength(array()); - $this->assertEquals(array(), $result); - } - - public function test_sortFilesDescByPathLength_shouldNotChangeOrder_IfAllHaveSameLength() - { - $input = array('xyz/1.gif', 'x/xyz.gif', 'xxyyzzgg'); - $result = Filesystem::sortFilesDescByPathLength($input); - $this->assertEquals($input, $result); - } - - public function test_sortFilesDescByPathLength_shouldOrderDesc_IfDifferentLengthsGiven() - { - $input = array('xyz/1.gif', '1.gif', 'x', 'x/xyz.gif', 'xyz', 'xxyyzzgg', 'xyz/long.gif'); - $result = Filesystem::sortFilesDescByPathLength($input); - - $expected = array( - 'xyz/long.gif', - 'x/xyz.gif', - 'xyz/1.gif', - 'xxyyzzgg', - '1.gif', - 'xyz', - 'x', - ); - $this->assertEquals($expected, $result); - } - - public function test_directoryDiff_shouldNotReturnDifference_IfBothDirectoriesAreSame() - { - $dir = PIWIK_INCLUDE_PATH . '/core'; - $result = Filesystem::directoryDiff($dir, $dir); - - $this->assertEquals(array(), $result); - } - - public function test_directoryDiff_shouldNotReturnAnything_IfTargetEmpty() - { - $result = Filesystem::directoryDiff($this->createSourceFiles(), $this->createEmptyTarget()); - - $this->assertEquals(array(), $result); - } - - public function test_directoryDiff_shouldReturnAllTargetFiles_IfSourceIsEmpty() - { - $result = Filesystem::directoryDiff($this->createEmptySource(), $this->createTargetFiles()); - - $this->assertEquals(array( - '/DataTable', - '/DataTable/BaseFilter.php', - '/DataTable/Bridges.php', - '/DataTable/DataTableInterface.php', - '/DataTable/Filter', - '/DataTable/Manager.php', - '/DataTable/Map.php', - '/DataTable/Renderer', - '/DataTable/Renderer.php', - '/DataTable/Row', - '/DataTable/Row.php', - '/DataTable/Simple.php', - '/DataTable/Renderer/Console.php', - '/DataTable/Renderer/Csv.php', - '/DataTable/Renderer/Html.php', - '/DataTable/Renderer/Json.php', - '/DataTable/Renderer/Php.php', - '/DataTable/Renderer/Rss.php', - '/DataTable/Renderer/Tsv.php', - '/DataTable/Renderer/Xml', - '/DataTable/Renderer/Xml.php', - '/DataTable/Renderer/Xml/Other.php', - '/DataTable/Row/DataTableSummaryRow.php' - ), $result); - } - - public function test_directoryDiff_shouldReturnFilesPresentInTargetButNotSource_IfSourceAndTargetGiven() - { - $result = Filesystem::directoryDiff($this->createSourceFiles(), $this->createTargetFiles()); - - $this->assertEquals(array( - '/DataTable/Filter', - '/DataTable/Row', - '/DataTable/Renderer/Json.php', - '/DataTable/Renderer/Php.php', - '/DataTable/Renderer/Rss.php', - '/DataTable/Renderer/Xml', - '/DataTable/Renderer/Xml/Other.php', - '/DataTable/Row/DataTableSummaryRow.php', - ), $result); - } - - public function test_unlinkTargetFilesNotPresentInSource_shouldUnlinkFilesPresentInTargetButNotSource_IfSourceAndTargetGiven() - { - $source = $this->createSourceFiles(); - $target = $this->createTargetFiles(); - - // make sure there is a difference between those folders - $result = Filesystem::directoryDiff($source, $target); - $this->assertCount(8, $result); - - Filesystem::unlinkTargetFilesNotPresentInSource($source, $target); - - // make sure there is no longer a difference - $result = Filesystem::directoryDiff($source, $target); - $this->assertEquals(array(), $result); - - $result = Filesystem::directoryDiff($target, $source); - $this->assertEquals(array( - '/DataTable/NotInTarget.php', - '/DataTable/Renderer/NotInTarget.php' - ), $result); - } - - public function test_unlinkTargetFilesNotPresentInSource_shouldNotFail_IfBothEmpty() - { - $source = $this->createEmptySource(); - $target = $this->createEmptyTarget(); - - Filesystem::unlinkTargetFilesNotPresentInSource($source, $target); - } - - public function test_unlinkTargetFilesNotPresentInSource_shouldUnlinkAllTargetFiles_IfSourceIsEmpty() - { - $source = $this->createEmptySource(); - $target = $this->createTargetFiles(); - - // make sure there is a difference between those folders - $result = Filesystem::directoryDiff($source, $target); - $this->assertNotEmpty($result); - - Filesystem::unlinkTargetFilesNotPresentInSource($source, $target); - - // make sure there is no longer a difference - $result = Filesystem::directoryDiff($source, $target); - $this->assertEquals(array(), $result); - - $result = Filesystem::directoryDiff($target, $source); - $this->assertEquals(array(), $result); - } - - private function createSourceFiles() - { - $source = $this->createEmptySource(); - Filesystem::mkdir($source . '/DataTable'); - Filesystem::mkdir($source . '/DataTable/Renderer'); - - file_put_contents($source . '/DataTable/Renderer/Console.php', ''); - file_put_contents($source . '/DataTable/Renderer/Csv.php', ''); - file_put_contents($source . '/DataTable/Renderer/Html.php', ''); - file_put_contents($source . '/DataTable/Renderer/Tsv.php', ''); - file_put_contents($source . '/DataTable/Renderer/Xml.php', ''); - file_put_contents($source . '/DataTable/Renderer/NotInTarget.php', ''); - - file_put_contents($source . '/DataTable/BaseFilter.php', ''); - file_put_contents($source . '/DataTable/Bridges.php', ''); - file_put_contents($source . '/DataTable/DataTableInterface.php', ''); - file_put_contents($source . '/DataTable/NotInTarget.php', ''); - file_put_contents($source . '/DataTable/Manager.php', ''); - file_put_contents($source . '/DataTable/Map.php', ''); - file_put_contents($source . '/DataTable/Renderer.php', ''); - file_put_contents($source . '/DataTable/Row.php', ''); - file_put_contents($source . '/DataTable/Simple.php', ''); - - return $source; - } - - private function createTargetFiles() - { - $target = $this->createEmptyTarget(); - Filesystem::mkdir($target . '/DataTable'); - Filesystem::mkdir($target . '/DataTable/Filter'); - Filesystem::mkdir($target . '/DataTable/Renderer'); - Filesystem::mkdir($target . '/DataTable/Renderer/Xml'); - Filesystem::mkdir($target . '/DataTable/Row'); - - file_put_contents($target . '/DataTable/Renderer/Console.php', ''); - file_put_contents($target . '/DataTable/Renderer/Csv.php', ''); - file_put_contents($target . '/DataTable/Renderer/Html.php', ''); - file_put_contents($target . '/DataTable/Renderer/Json.php', ''); - file_put_contents($target . '/DataTable/Renderer/Php.php', ''); - file_put_contents($target . '/DataTable/Renderer/Rss.php', ''); - file_put_contents($target . '/DataTable/Renderer/Tsv.php', ''); - file_put_contents($target . '/DataTable/Renderer/Xml.php', ''); - file_put_contents($target . '/DataTable/Renderer/Xml/Other.php', ''); - - file_put_contents($target . '/DataTable/Row/DataTableSummaryRow.php', ''); - - file_put_contents($target . '/DataTable/BaseFilter.php', ''); - file_put_contents($target . '/DataTable/Bridges.php', ''); - file_put_contents($target . '/DataTable/DataTableInterface.php', ''); - file_put_contents($target . '/DataTable/Manager.php', ''); - file_put_contents($target . '/DataTable/Map.php', ''); - file_put_contents($target . '/DataTable/Renderer.php', ''); - file_put_contents($target . '/DataTable/Row.php', ''); - file_put_contents($target . '/DataTable/Simple.php', ''); - - return $target; - } - - private function createEmptySource() - { - Filesystem::mkdir($this->testPath . '/source'); - - return $this->testPath . '/source'; - } - - private function createEmptyTarget() - { - Filesystem::mkdir($this->testPath . '/target'); - - return $this->testPath . '/target'; - } - -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/Http/fixture.zip b/tests/PHPUnit/Core/Http/fixture.zip Binary files differdeleted file mode 100644 index 2388859d52..0000000000 --- a/tests/PHPUnit/Core/Http/fixture.zip +++ /dev/null diff --git a/tests/PHPUnit/Core/HttpTest.php b/tests/PHPUnit/Core/HttpTest.php deleted file mode 100644 index af2711c530..0000000000 --- a/tests/PHPUnit/Core/HttpTest.php +++ /dev/null @@ -1,123 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Http; -use Piwik\Tests\Fixture; - -/** - * @group HttpTest - */ -class HttpTest extends PHPUnit_Framework_TestCase -{ - /** - * Dataprovider for testFetchRemoteFile - */ - public function getMethodsToTest() - { - return array( - 'curl' => array('curl'), - 'fopen' => array('fopen'), - 'socket' => array('socket'), - ); - } - - /** - * @group Core - * - * @dataProvider getMethodsToTest - */ - public function testFetchRemoteFile($method) - { - $this->assertNotNull(Http::getTransportMethod()); - $result = Http::sendHttpRequestBy($method, Fixture::getRootUrl() . 'piwik.js', 30); - $this->assertTrue(strpos($result, 'Piwik') !== false); - } - - /** - * @group Core - */ - public function testFetchApiLatestVersion() - { - $destinationPath = PIWIK_USER_PATH . '/tmp/latest/LATEST'; - Http::fetchRemoteFile(Fixture::getRootUrl(), $destinationPath, 3); - $this->assertFileExists($destinationPath); - $this->assertGreaterThan(0, filesize($destinationPath)); - } - - /** - * @group Core - */ - public function testFetchLatestZip() - { - $destinationPath = PIWIK_USER_PATH . '/tmp/latest/latest.zip'; - Http::fetchRemoteFile(Fixture::getRootUrl() . 'tests/PHPUnit/Core/Http/fixture.zip', $destinationPath, 3, 30); - $this->assertFileExists($destinationPath); - $this->assertGreaterThan(0, filesize($destinationPath)); - } - - /** - * @group Core - * @dataProvider getMethodsToTest - */ - public function testCustomByteRange($method) - { - $result = Http::sendHttpRequestBy( - $method, - Fixture::getRootUrl() . '/piwik.js', - 30, - $userAgent = null, - $destinationPath = null, - $file = null, - $followDepth = 0, - $acceptLanguage = false, - $acceptInvalidSslCertificate = false, - $byteRange = array(10, 20), - $getExtendedInfo = true - ); - - if ($method != 'fopen') { - $this->assertEquals(206, $result['status']); - $this->assertTrue(isset($result['headers']['Content-Range'])); - $this->assertEquals('bytes 10-20/', substr($result['headers']['Content-Range'], 0, 12)); - $this->assertEquals('application/x-javascript', $result['headers']['Content-Type']); - } - } - - /** - * @group Core - * - * @dataProvider getMethodsToTest - */ - public function testHEADOperation($method) - { - if ($method == 'fopen') { - return; // not supported w/ this method - } - - $result = Http::sendHttpRequestBy( - $method, - Fixture::getRootUrl() . 'tests/PHPUnit/Core/Http/fixture.zip', - 30, - $userAgent = null, - $destinationPath = null, - $file = null, - $followDepth = 0, - $acceptLanguage = false, - $acceptInvalidSslCertificate = false, - $byteRange = false, - $getExtendedInfo = true, - $httpMethod = 'HEAD' - ); - - $this->assertEquals('', $result['data']); - $this->assertEquals(200, $result['status']); - - $this->assertTrue(isset($result['headers']['Content-Length']), "Content-Length header not set!"); - $this->assertTrue(is_numeric($result['headers']['Content-Length']), "Content-Length header not numeric!"); - $this->assertEquals('application/zip', $result['headers']['Content-Type']); - } -} diff --git a/tests/PHPUnit/Core/IPTest.php b/tests/PHPUnit/Core/IPTest.php deleted file mode 100644 index f12d37dfed..0000000000 --- a/tests/PHPUnit/Core/IPTest.php +++ /dev/null @@ -1,690 +0,0 @@ -<?php -use Piwik\Common; -use Piwik\Config; -use Piwik\IP; -use Piwik\SettingsServer; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class IPTest extends PHPUnit_Framework_TestCase -{ - /** - * Dataprovider for testSanitizeIp - */ - public function getIPData() - { - return array( // input, output - // single IPv4 address - array('127.0.0.1', '127.0.0.1'), - - // single IPv6 address (ambiguous) - array('::1', '::1'), - array('::ffff:127.0.0.1', '::ffff:127.0.0.1'), - array('2001:5c0:1000:b::90f8', '2001:5c0:1000:b::90f8'), - - // single IPv6 address - array('[::1]', '::1'), - array('[2001:5c0:1000:b::90f8]', '2001:5c0:1000:b::90f8'), - array('[::ffff:127.0.0.1]', '::ffff:127.0.0.1'), - - // single IPv4 address (CIDR notation) - array('192.168.1.1/32', '192.168.1.1'), - - // single IPv6 address (CIDR notation) - array('::1/128', '::1'), - array('::ffff:127.0.0.1/128', '::ffff:127.0.0.1'), - array('2001:5c0:1000:b::90f8/128', '2001:5c0:1000:b::90f8'), - - // IPv4 address with port - array('192.168.1.2:80', '192.168.1.2'), - - // IPv6 address with port - array('[::1]:80', '::1'), - array('[::ffff:127.0.0.1]:80', '::ffff:127.0.0.1'), - array('[2001:5c0:1000:b::90f8]:80', '2001:5c0:1000:b::90f8'), - - // hostnames with port? - array('localhost', 'localhost'), - array('localhost:80', 'localhost'), - array('www.example.com', 'www.example.com'), - array('example.com:80', 'example.com'), - array('example.com:8080', 'example.com'), - array('sub.example.com:8080', 'sub.example.com'), - ); - } - - /** - * @dataProvider getIPData - * @group Core - */ - public function testSanitizeIp($ip, $expected) - { - $this->assertEquals($expected, IP::sanitizeIp($ip)); - } - - /** - * Dataprovider for testSanitizeIpRange - */ - public function getIPRangeData() - { - return array( - array('', false), - array(' 127.0.0.1 ', '127.0.0.1/32'), - array('192.168.1.0', '192.168.1.0/32'), - array('192.168.1.1/24', '192.168.1.1/24'), - array('192.168.1.2/16', '192.168.1.2/16'), - array('192.168.1.3/8', '192.168.1.3/8'), - array('192.168.2.*', '192.168.2.0/24'), - array('192.169.*.*', '192.169.0.0/16'), - array('193.*.*.*', '193.0.0.0/8'), - array('*.*.*.*', '0.0.0.0/0'), - array('*.*.*.1', false), - array('*.*.1.1', false), - array('*.1.1.1', false), - array('1.*.1.1', false), - array('1.1.*.1', false), - array('1.*.*.1', false), - array('::1', '::1/128'), - array('::ffff:127.0.0.1', '::ffff:127.0.0.1/128'), - array('2001:5c0:1000:b::90f8', '2001:5c0:1000:b::90f8/128'), - array('::1/64', '::1/64'), - array('::ffff:127.0.0.1/64', '::ffff:127.0.0.1/64'), - array('2001:5c0:1000:b::90f8/64', '2001:5c0:1000:b::90f8/64'), - ); - } - - /** - * @dataProvider getIPRangeData - * @group Core - */ - public function testSanitizeIpRange($ip, $expected) - { - $this->assertEquals($expected, IP::sanitizeIpRange($ip)); - } - - /** - * Dataprovider for testP2N - */ - public function getP2NTestData() - { - return array( - // IPv4 - array('0.0.0.0', "\x00\x00\x00\x00"), - array('127.0.0.1', "\x7F\x00\x00\x01"), - array('192.168.1.12', "\xc0\xa8\x01\x0c"), - array('255.255.255.255', "\xff\xff\xff\xff"), - - // IPv6 - array('::', "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), - array('::1', "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"), - array('::fffe:7f00:1', "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xfe\x7f\x00\x00\x01"), - array('::ffff:127.0.0.1', "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x7f\x00\x00\x01"), - array('2001:5c0:1000:b::90f8', "\x20\x01\x05\xc0\x10\x00\x00\x0b\x00\x00\x00\x00\x00\x00\x90\xf8"), - ); - } - - /** - * @dataProvider getP2NTestData - * @group Core - */ - public function testP2N($P, $N) - { - $this->assertEquals($N, IP::P2N($P)); - } - - /** - * Dataprovider for testP2NInvalidInput - */ - public function getP2NInvalidInputData() - { - return array( - // not a series of dotted numbers - array(null), - array(''), - array('alpha'), - array('...'), - - // missing an octet - array('.0.0.0'), - array('0..0.0'), - array('0.0..0'), - array('0.0.0.'), - - // octets must be 0-255 - array('-1.0.0.0'), - array('1.1.1.256'), - - // leading zeros not supported (i.e., can be ambiguous, e.g., octal) - array('07.07.07.07'), - ); - } - - /** - * @group Core - * - * @dataProvider getP2NInvalidInputData - */ - public function testP2NInvalidInput($P) - { - $this->assertEquals("\x00\x00\x00\x00", IP::P2N($P)); - } - - /** - * @group Core - */ - public function getN2PTestData() - { - // a valid network address is either 4 or 16 bytes; those lines are intentionally left blank ;) - return array( - array(null), - array(''), - array("\x01"), - array("\x01\x00"), - array("\x01\x00\x00"), - - array("\x01\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), - - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), - ); - } - - /** - * @dataProvider getP2NTestData - * @group Core - */ - public function testN2P($P, $N) - { - $this->assertEquals($P, IP::N2P($N), "$P vs" . IP::N2P($N)); - } - - /** - * @dataProvider getN2PTestData - * @group Core - */ - public function testN2PinvalidInput($N) - { - $this->assertEquals("0.0.0.0", IP::N2P($N), bin2hex($N)); - } - - /** - * @dataProvider getP2NTestData - * @group Core - */ - public function testPrettyPrint($P, $N) - { - $this->assertEquals($P, IP::prettyPrint($N), "$P vs" . IP::N2P($N)); - } - - /** - * @dataProvider getN2PTestData - * @group Core - */ - public function testPrettyPrintInvalidInput($N) - { - $this->assertEquals("0.0.0.0", IP::prettyPrint($N), bin2hex($N)); - } - - /** - * Dataprovider for IP4 test data - */ - public function getIPv4Data() - { - // a valid network address is either 4 or 16 bytes; those lines are intentionally left blank ;) - return array( - // invalid - array(null, false), - array("", false), - - // IPv4 - array("\x00\x00\x00\x00", true), - array("\x7f\x00\x00\x01", true), - - // IPv4-compatible (this transitional format is deprecated in RFC 4291, section 2.5.5.1) - array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\xa8\x01\x01", true), - - // IPv4-mapped (RFC 4291, 2.5.5.2) - array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xc0\xa8\x01\x02", true), - - // other IPv6 address - array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\xc0\xa8\x01\x03", false), - array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xc0\xa8\x01\x04", false), - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\xa8\x01\x05", false), - - /* - * We assume all stored IP addresses (pre-Piwik 1.4) were converted from UNSIGNED INT to VARBINARY. - * The following is just for informational purposes. - */ - - // 192.168.1.0 - array('-1062731520', false), - array('3232235776', false), - - // 10.10.10.10 - array('168430090', false), - - // 0.0.39.15 - this is the ambiguous case (i.e., 4 char string) - array('9999', true), - array("\x39\x39\x39\x39", true), - - // 0.0.3.231 - array('999', false), - array("\x39\x39\x39", false), - ); - - } - - /** - * @dataProvider getIPv4Data - * @group Core - */ - public function testIsIPv4($ip, $bool) - { - $this->assertEquals($bool, IP::isIPv4($ip), bin2hex($ip)); - } - - /** - * Dataprovider for long2ip test - */ - public function getLong2IPTestData() - { - // a valid network address is either 4 or 16 bytes; those lines are intentionally left blank ;) - return array( - // invalid - array(null, '0.0.0.0'), - array("", '0.0.0.0'), - - // IPv4 - array("\x7f\x00\x00\x01", '127.0.0.1'), - - // IPv4-compatible (this transitional format is deprecated in RFC 4291, section 2.5.5.1) - array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\xa8\x01\x01", '192.168.1.1'), - - // IPv4-mapped (RFC 4291, 2.5.5.2) - array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xc0\xa8\x01\x02", '192.168.1.2'), - - // other IPv6 address - array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\xc0\xa8\x01\x03", '0.0.0.0'), - array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xc0\xa8\x01\x04", '0.0.0.0'), - array("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\xa8\x01\x05", '0.0.0.0'), - - /* - * We assume all stored IP addresses (pre-Piwik 1.4) were converted from UNSIGNED INT to VARBINARY. - * The following is just for informational purposes. - */ - - // 192.168.1.0 - array('-1062731520', '0.0.0.0'), - array('3232235776', '0.0.0.0'), - - // 10.10.10.10 - array('168430090', '0.0.0.0'), - - // 0.0.39.15 - this is the ambiguous case (i.e., 4 char string) - array('9999', '57.57.57.57'), - array("\x39\x39\x39\x39", '57.57.57.57'), - - // 0.0.3.231 - array('999', '0.0.0.0'), - array("\x39\x39\x39", '0.0.0.0'), - ); - } - - /** - * @dataProvider getLong2IPTestData - * @group Core - */ - public function testLong2ip($N, $P) - { - $this->assertEquals($P, IP::long2ip($N), bin2hex($N)); - // this is our compatibility function - $this->assertEquals($P, Common::long2ip($N), bin2hex($N)); - } - - /** - * Dataprovider for ip range test - */ - public function getIPsForRangeTest() - { - return array( - - // invalid ranges - array(null, false), - array('', false), - array('0', false), - - // single IPv4 - array('127.0.0.1', array("\x7f\x00\x00\x01", "\x7f\x00\x00\x01")), - - // IPv4 with wildcards - array('192.168.1.*', array("\xc0\xa8\x01\x00", "\xc0\xa8\x01\xff")), - array('192.168.*.*', array("\xc0\xa8\x00\x00", "\xc0\xa8\xff\xff")), - array('192.*.*.*', array("\xc0\x00\x00\x00", "\xc0\xff\xff\xff")), - array('*.*.*.*', array("\x00\x00\x00\x00", "\xff\xff\xff\xff")), - - // single IPv4 in expected CIDR notation - array('192.168.1.1/24', array("\xc0\xa8\x01\x00", "\xc0\xa8\x01\xff")), - - array('192.168.1.127/32', array("\xc0\xa8\x01\x7f", "\xc0\xa8\x01\x7f")), - array('192.168.1.127/31', array("\xc0\xa8\x01\x7e", "\xc0\xa8\x01\x7f")), - array('192.168.1.127/30', array("\xc0\xa8\x01\x7c", "\xc0\xa8\x01\x7f")), - array('192.168.1.127/29', array("\xc0\xa8\x01\x78", "\xc0\xa8\x01\x7f")), - array('192.168.1.127/28', array("\xc0\xa8\x01\x70", "\xc0\xa8\x01\x7f")), - array('192.168.1.127/27', array("\xc0\xa8\x01\x60", "\xc0\xa8\x01\x7f")), - array('192.168.1.127/26', array("\xc0\xa8\x01\x40", "\xc0\xa8\x01\x7f")), - array('192.168.1.127/25', array("\xc0\xa8\x01\x00", "\xc0\xa8\x01\x7f")), - - array('192.168.1.255/32', array("\xc0\xa8\x01\xff", "\xc0\xa8\x01\xff")), - array('192.168.1.255/31', array("\xc0\xa8\x01\xfe", "\xc0\xa8\x01\xff")), - array('192.168.1.255/30', array("\xc0\xa8\x01\xfc", "\xc0\xa8\x01\xff")), - array('192.168.1.255/29', array("\xc0\xa8\x01\xf8", "\xc0\xa8\x01\xff")), - array('192.168.1.255/28', array("\xc0\xa8\x01\xf0", "\xc0\xa8\x01\xff")), - array('192.168.1.255/27', array("\xc0\xa8\x01\xe0", "\xc0\xa8\x01\xff")), - array('192.168.1.255/26', array("\xc0\xa8\x01\xc0", "\xc0\xa8\x01\xff")), - array('192.168.1.255/25', array("\xc0\xa8\x01\x80", "\xc0\xa8\x01\xff")), - - array('192.168.255.255/24', array("\xc0\xa8\xff\x00", "\xc0\xa8\xff\xff")), - array('192.168.255.255/23', array("\xc0\xa8\xfe\x00", "\xc0\xa8\xff\xff")), - array('192.168.255.255/22', array("\xc0\xa8\xfc\x00", "\xc0\xa8\xff\xff")), - array('192.168.255.255/21', array("\xc0\xa8\xf8\x00", "\xc0\xa8\xff\xff")), - array('192.168.255.255/20', array("\xc0\xa8\xf0\x00", "\xc0\xa8\xff\xff")), - array('192.168.255.255/19', array("\xc0\xa8\xe0\x00", "\xc0\xa8\xff\xff")), - array('192.168.255.255/18', array("\xc0\xa8\xc0\x00", "\xc0\xa8\xff\xff")), - array('192.168.255.255/17', array("\xc0\xa8\x80\x00", "\xc0\xa8\xff\xff")), - - // single IPv6 - array('::1', array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01")), - - // single IPv6 in expected CIDR notation - array('::1/128', array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01")), - array('::1/127', array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01")), - array('::fffe:7f00:1/120', array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xfe\x7f\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xfe\x7f\x00\x00\xff")), - array('::ffff:127.0.0.1/120', array("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x7f\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x7f\x00\x00\xff")), - - array('2001:ca11:911::b0b:15:dead/128', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xad", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xad")), - array('2001:ca11:911::b0b:15:dead/127', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xac", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xad")), - array('2001:ca11:911::b0b:15:dead/126', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xac", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xaf")), - array('2001:ca11:911::b0b:15:dead/125', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xa8", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xaf")), - array('2001:ca11:911::b0b:15:dead/124', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xa0", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xaf")), - array('2001:ca11:911::b0b:15:dead/123', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xa0", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xbf")), - array('2001:ca11:911::b0b:15:dead/122', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\x80", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xbf")), - array('2001:ca11:911::b0b:15:dead/121', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\x80", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xff")), - array('2001:ca11:911::b0b:15:dead/120', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\x00", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\xff")), - array('2001:ca11:911::b0b:15:dead/119', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xde\x00", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xdf\xff")), - array('2001:ca11:911::b0b:15:dead/118', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xdc\x00", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xdf\xff")), - array('2001:ca11:911::b0b:15:dead/117', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xd8\x00", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xdf\xff")), - array('2001:ca11:911::b0b:15:dead/116', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xd0\x00", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xdf\xff")), - array('2001:ca11:911::b0b:15:dead/115', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xc0\x00", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xdf\xff")), - array('2001:ca11:911::b0b:15:dead/114', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xc0\x00", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xff\xff")), - array('2001:ca11:911::b0b:15:dead/113', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\x80\x00", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xff\xff")), - array('2001:ca11:911::b0b:15:dead/112', array("\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\x00\x00", "\x20\x01\xca\x11\x09\x11\x00\x00\x00\x00\x0b\x0b\x00\x15\xff\xff")), - ); - } - - /** - * @dataProvider getIPsForRangeTest - * @group Core - */ - public function testGetIpsForRange($range, $expected) - { - $this->assertEquals($expected, IP::getIpsForRange($range)); - } - - /** - * Dataprovider for testIsIpInRange - */ - public function getIpsInRangeData() - { - return array( - array('192.168.1.10', array( - '192.168.1.9' => false, - '192.168.1.10' => true, - '192.168.1.11' => false, - - // IPv6 addresses (including IPv4 mapped) have to be compared against IPv6 address ranges - '::ffff:192.168.1.10' => false, - )), - - array('::ffff:192.168.1.10', array( - '::ffff:192.168.1.9' => false, - '::ffff:192.168.1.10' => true, - '::ffff:c0a8:010a' => true, - '0000:0000:0000:0000:0000:ffff:c0a8:010a' => true, - '::ffff:192.168.1.11' => false, - - // conversely, IPv4 addresses have to be compared against IPv4 address ranges - '192.168.1.10' => false, - )), - - array('192.168.1.10/32', array( - '192.168.1.9' => false, - '192.168.1.10' => true, - '192.168.1.11' => false, - )), - - array('192.168.1.10/31', array( - '192.168.1.9' => false, - '192.168.1.10' => true, - '192.168.1.11' => true, - '192.168.1.12' => false, - )), - - array('192.168.1.128/25', array( - '192.168.1.127' => false, - '192.168.1.128' => true, - '192.168.1.255' => true, - '192.168.2.0' => false, - )), - - array('192.168.1.10/24', array( - '192.168.0.255' => false, - '192.168.1.0' => true, - '192.168.1.1' => true, - '192.168.1.2' => true, - '192.168.1.3' => true, - '192.168.1.4' => true, - '192.168.1.7' => true, - '192.168.1.8' => true, - '192.168.1.15' => true, - '192.168.1.16' => true, - '192.168.1.31' => true, - '192.168.1.32' => true, - '192.168.1.63' => true, - '192.168.1.64' => true, - '192.168.1.127' => true, - '192.168.1.128' => true, - '192.168.1.255' => true, - '192.168.2.0' => false, - )), - - array('192.168.1.*', array( - '192.168.0.255' => false, - '192.168.1.0' => true, - '192.168.1.1' => true, - '192.168.1.2' => true, - '192.168.1.3' => true, - '192.168.1.4' => true, - '192.168.1.7' => true, - '192.168.1.8' => true, - '192.168.1.15' => true, - '192.168.1.16' => true, - '192.168.1.31' => true, - '192.168.1.32' => true, - '192.168.1.63' => true, - '192.168.1.64' => true, - '192.168.1.127' => true, - '192.168.1.128' => true, - '192.168.1.255' => true, - '192.168.2.0' => false, - )), - ); - } - - /** - * @group Core - * - * @dataProvider getIpsInRangeData - */ - public function testIsIpInRange($range, $test) - { - foreach ($test as $ip => $expected) { - // range as a string - $this->assertEquals($expected, IP::isIpInRange(IP::P2N($ip), array($range)), "$ip in $range"); - - // range as an array(low, high) - $aRange = IP::getIpsForRange($range); - $aRange[0] = IP::N2P($aRange[0]); - $aRange[1] = IP::N2P($aRange[1]); - $this->assertEquals($expected, IP::isIpInRange(IP::P2N($ip), array($aRange)), "$ip in $range"); - } - } - - /** - * Dataprovider for ip from header tests - */ - public function getIpFromHeaderTestData() - { - return array( - array('localhost inside LAN', array('127.0.0.1', '', null, null, '127.0.0.1')), - array('outside LAN, no proxy', array('128.252.135.4', '', null, null, '128.252.135.4')), - array('outside LAN, no (trusted) proxy', array('128.252.135.4', '137.18.2.13, 128.252.135.4', '', null, '128.252.135.4')), - array('outside LAN, one trusted proxy', array('192.168.1.10', '137.18.2.13, 128.252.135.4, 192.168.1.10', 'HTTP_X_FORWARDED_FOR', null, '128.252.135.4')), - array('outside LAN, proxy', array('192.168.1.10', '128.252.135.4, 192.168.1.10', 'HTTP_X_FORWARDED_FOR', null, '128.252.135.4')), - array('outside LAN, misconfigured proxy', array('192.168.1.10', '128.252.135.4, 192.168.1.10, 192.168.1.10', 'HTTP_X_FORWARDED_FOR', null, '128.252.135.4')), - array('outside LAN, multiple proxies', array('192.168.1.10', '128.252.135.4, 192.168.1.20, 192.168.1.10', 'HTTP_X_FORWARDED_FOR', '192.168.1.*', '128.252.135.4')), - array('outside LAN, multiple proxies', array('[::ffff:7f00:10]', '128.252.135.4, [::ffff:7f00:20], [::ffff:7f00:10]', 'HTTP_X_FORWARDED_FOR', '::ffff:7f00:0/120', '128.252.135.4')), - ); - } - - /** - * @dataProvider getIpFromHeaderTestData - * @group Core - */ - public function testGetIpFromHeader($description, $test) - { - Config::getInstance()->setTestEnvironment(); - - $_SERVER['REMOTE_ADDR'] = $test[0]; - $_SERVER['HTTP_X_FORWARDED_FOR'] = $test[1]; - Config::getInstance()->General['proxy_client_headers'] = array($test[2]); - Config::getInstance()->General['proxy_ips'] = array($test[3]); - $this->assertEquals($test[4], IP::getIpFromHeader(), $description); - } - - /** - * Dataprovider - * @return array - */ - public function getIpTestData() - { - return array( - array('0.0.0.0'), - array('72.14.204.99'), - array('127.0.0.1'), - array('169.254.0.1'), - array('208.80.152.2'), - array('224.0.0.1'), - ); - } - - /** - * @group Core - * - * @dataProvider getIpTestData - */ - public function testGetNonProxyIpFromHeader($ip) - { - $this->assertEquals($ip, IP::getNonProxyIpFromHeader($ip, array())); - } - - /** - * @group Core - * - * @dataProvider getIpTestData - */ - public function testGetNonProxyIpFromHeader2($ip) - { - // 1.1.1.1 is not a trusted proxy - $_SERVER['REMOTE_ADDR'] = '1.1.1.1'; - $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; - $this->assertEquals('1.1.1.1', IP::getNonProxyIpFromHeader('1.1.1.1', array('HTTP_X_FORWARDED_FOR'))); - } - - /** - * @group Core - * - * @dataProvider getIpTestData - */ - public function testGetNonProxyIpFromHeader3($ip) - { - // 1.1.1.1 is a trusted proxy - $_SERVER['REMOTE_ADDR'] = '1.1.1.1'; - - $_SERVER['HTTP_X_FORWARDED_FOR'] = $ip; - $this->assertEquals($ip, IP::getNonProxyIpFromHeader('1.1.1.1', array('HTTP_X_FORWARDED_FOR'))); - - $_SERVER['HTTP_X_FORWARDED_FOR'] = '1.2.3.4, ' . $ip; - $this->assertEquals($ip, IP::getNonProxyIpFromHeader('1.1.1.1', array('HTTP_X_FORWARDED_FOR'))); - - // misconfiguration - $_SERVER['HTTP_X_FORWARDED_FOR'] = $ip . ', 1.1.1.1'; - $this->assertEquals($ip, IP::getNonProxyIpFromHeader('1.1.1.1', array('HTTP_X_FORWARDED_FOR'))); - } - - /** - * Dataprovider for testGetLastIpFromList - */ - public function getLastIpFromListTestData() - { - return array( - array('', ''), - array('127.0.0.1', '127.0.0.1'), - array(' 127.0.0.1 ', '127.0.0.1'), - array(' 192.168.1.1, 127.0.0.1', '127.0.0.1'), - array('192.168.1.1 ,127.0.0.1 ', '127.0.0.1'), - array('192.168.1.1,', ''), - ); - } - - /** - * @group Core - * - * @dataProvider getLastIpFromListTestData - */ - public function testGetLastIpFromList($csv, $expected) - { - // without excluded IPs - $this->assertEquals($expected, IP::getLastIpFromList($csv)); - - // with excluded Ips - $this->assertEquals($expected, IP::getLastIpFromList($csv . ', 10.10.10.10', array('10.10.10.10'))); - } - - /** - * @group Core - */ - public function testGetHostByAddr() - { - $hosts = array('localhost', 'localhost.localdomain', strtolower(@php_uname('n')), '127.0.0.1'); - $host = IP::getHostByAddr('127.0.0.1'); - $this->assertTrue(in_array(strtolower($host), $hosts), $host . ' -> localhost'); - - if (!SettingsServer::isWindows() || PHP_VERSION >= '5.3') { - $hosts = array('ip6-localhost', 'localhost', 'localhost.localdomain', strtolower(@php_uname('n')), '::1'); - $this->assertTrue(in_array(strtolower(IP::getHostByAddr('::1')), $hosts), '::1 -> ip6-localhost'); - } - } -} diff --git a/tests/PHPUnit/Core/Menu/MenuReportingTest.php b/tests/PHPUnit/Core/Menu/MenuReportingTest.php deleted file mode 100644 index b82c4a1aaf..0000000000 --- a/tests/PHPUnit/Core/Menu/MenuReportingTest.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\Access; -use Piwik\Plugin\Report; -use Piwik\Piwik; -use Piwik\Metrics; -use Piwik\Translate; -use Piwik\Menu\MenuReporting; -use Piwik\Plugin\Manager as PluginManager; - - -/** - * @group Core - */ -class Menu_ReportingTest extends PHPUnit_Framework_TestCase -{ - /** - * @var MenuReporting - */ - private $menu; - - public function setUp() - { - PluginManager::getInstance()->unloadPlugins(); - $this->menu = MenuReporting::getInstance(); - - Access::setSingletonInstance(new FakeAccess()); - } - - public function tearDown() - { - MenuReporting::getInstance()->unsetInstance(); - Access::setSingletonInstance(null); - parent::tearDown(); - } - - public function test_getMenu_shouldBeNull_IfNoItems() - { - $this->assertNull($this->menu->getMenu()); - } - - public function test_getMenu_shouldTriggerAddItemsEvent_toBeBackwardsCompatible() - { - $this->loadSomePlugins(); - - $triggered = false; - Piwik::addAction('Menu.Reporting.addItems', function () use (&$triggered) { - $triggered = true; - }); - - $this->menu->getMenu(); - - $this->assertTrue($triggered); - } - - public function test_getMenu_shouldAddMenuItemsOfReports() - { - $this->loadSomePlugins(); - - $items = $this->menu->getMenu(); - - $this->assertNotEmpty($items); - $this->assertGreaterThan(20, $items); - $this->assertEquals(array('General_Actions', 'General_Visitors'), array_keys($items)); - $this->assertNotEmpty($items['General_Actions']['General_Pages']); - $this->assertEquals('menuGetPageUrls', $items['General_Actions']['General_Pages']['_url']['action']); - } - - private function loadSomePlugins() - { - PluginManager::getInstance()->loadPlugins(array( - 'Actions', 'DevicesDetection', 'CoreVisualizations', 'API', 'Morpheus' - )); - } - -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/MetricsTest.php b/tests/PHPUnit/Core/MetricsTest.php deleted file mode 100644 index c7052102e8..0000000000 --- a/tests/PHPUnit/Core/MetricsTest.php +++ /dev/null @@ -1,132 +0,0 @@ -<?php
-use Piwik\Access;
-use Piwik\Metrics;
-
-/**
- * Piwik - free/libre analytics platform
- *
- * @link http://piwik.org
- * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
- */
-class Core_MetricsTest extends PHPUnit_Framework_TestCase
-{
- /**
- * @group Core
- */
- public function testGetVisitsMetricNames()
- {
- $names = Metrics::getVisitsMetricNames();
- $expectedNames = array(
- 1 => 'nb_uniq_visitors',
- 2 => 'nb_visits',
- 39 => 'nb_users',
- 3 => 'nb_actions',
- 4 => 'max_actions',
- 5 => 'sum_visit_length',
- 6 => 'bounce_count',
- 7 => 'nb_visits_converted',
- );
- $this->assertEquals($expectedNames, $names);
- }
-
- /**
- * @group Core
- */
- public function testGetMappingFromIdToName()
- {
- $mapping = Metrics::getMappingFromIdToName();
- $expectedMapping = array(
- 'nb_uniq_visitors' => 1,
- 'nb_visits' => 2,
- 'nb_actions' => 3,
- 'max_actions' => 4,
- 'sum_visit_length' => 5,
- 'bounce_count' => 6,
- 'nb_users' => 39,
- 'nb_visits_converted' => 7,
- 'nb_conversions' => 8,
- 'revenue' => 23,
- 'goals' => 10,
- 'sum_daily_nb_uniq_visitors' => 11,
- 'sum_daily_nb_users' => 40,
- 'nb_hits' => 12,
- 'sum_time_spent' => 13,
- 'sum_time_generation' => 30,
- 'nb_hits_with_time_generation' => 31,
- 'min_time_generation' => 32,
- 'max_time_generation' => 33,
- 'exit_nb_uniq_visitors' => 14,
- 'exit_nb_visits' => 15,
- 'sum_daily_exit_nb_uniq_visitors' => 16,
- 'entry_nb_uniq_visitors' => 17,
- 'sum_daily_entry_nb_uniq_visitors' => 18,
- 'entry_nb_visits' => 19,
- 'entry_nb_actions' => 20,
- 'entry_sum_visit_length' => 21,
- 'entry_bounce_count' => 22,
- 'nb_hits_following_search' => 29,
- 'quantity' => 24,
- 'price' => 25,
- 'price_viewed' => 27,
- 'orders' => 26,
- 'nb_events' => 34,
- 'sum_event_value' => 35,
- 'min_event_value' => 36,
- 'max_event_value' => 37,
- 'nb_events_with_value' => 38,
- 'nb_impressions' => 41,
- 'nb_interactions' => 42
- );
- $this->assertEquals($expectedMapping, $mapping);
- }
-
- public function getLowerValuesBetter()
- {
- return array(
- array('bounce', true),
- array('exit', true),
- array('', false),
- array('price', false),
- );
- }
-
- /**
- * @dataProvider getLowerValuesBetter
- * @group Core
- */
- public function testIsLowerValueBetter($column, $expected)
- {
- $actual = Metrics::isLowerValueBetter($column);
- $this->assertEquals($expected, $actual);
- }
-
- public function getUnitColumns()
- {
- return array(
- array('avg_time_on_page', 's'),
- array('sum_time_spent', 's'),
- array('conversion_rate', '%'),
- array('revenue', '€'),
- array('nb_visits', ''),
- );
- }
-
- /**
- * @dataProvider getUnitColumns
- * @group Core
- */
- public function testGetUnit($column, $expected)
- {
- \Piwik\Site::setSites(array(
- 1 => array('name' => 'TestSite', 'currency' => 'EUR')
- ));
-
- $pseudoMockAccess = new FakeAccess;
- FakeAccess::$superUser = true;
- Access::setSingletonInstance($pseudoMockAccess);
-
- $actual = Metrics::getUnit($column, 1);
- $this->assertEquals($expected, $actual);
- }
-
-}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/NonceTest.php b/tests/PHPUnit/Core/NonceTest.php deleted file mode 100644 index 9d0d8ef37d..0000000000 --- a/tests/PHPUnit/Core/NonceTest.php +++ /dev/null @@ -1,38 +0,0 @@ -<?php -use Piwik\Config; -use Piwik\Nonce; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class NonceTest extends PHPUnit_Framework_TestCase -{ - /** - * Dataprovider for acceptable origins test - */ - public function getAcceptableOriginsTestData() - { - return array( - // HTTP_HOST => expected - array('example.com', array('http://example.com', 'https://example.com')), - array('example.com:80', array('http://example.com', 'https://example.com')), - array('example.com:443', array('http://example.com', 'https://example.com')), - array('example.com:8080', array('http://example.com', 'https://example.com', 'http://example.com:8080', 'https://example.com:8080')), - ); - } - - /** - * @dataProvider getAcceptableOriginsTestData - * @group Core - */ - public function test_getAcceptableOrigins($host, $expected) - { - Config::getInstance()->General['enable_trusted_host_check'] = 0; - $_SERVER['HTTP_HOST'] = $host; - Config::getInstance()->General['trusted_hosts'] = array('example.com'); - $this->assertEquals($expected, Nonce::getAcceptableOrigins(), $host); - } -} diff --git a/tests/PHPUnit/Core/Period/DayTest.php b/tests/PHPUnit/Core/Period/DayTest.php deleted file mode 100644 index eb653fcc5c..0000000000 --- a/tests/PHPUnit/Core/Period/DayTest.php +++ /dev/null @@ -1,253 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Date; -use Piwik\Period\Day; -use Piwik\Translate; - -/** - * Testing Period_Day - */ -class Period_DayTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testInvalidDate() - { - try { - new Day('Invalid Date'); - } catch (Exception $e) { - return; - } - $this->fail('Expected Exception not raised'); - } - - /** - * @group Core - */ - public function testToString() - { - $period = new Day(Date::today()); - $this->assertEquals(date("Y-m-d"), $period->getPrettyString()); - $this->assertEquals(date("Y-m-d"), (string)$period); - $this->assertEquals(date("Y-m-d"), $period->toString()); - } - - /** - * today is NOT finished - * @group Core - */ - public function testDayIsFinishedToday() - { - $period = new Day(Date::today()); - $this->assertEquals(date("Y-m-d"), $period->toString()); - $this->assertEquals(array(), $period->getSubperiods()); - $this->assertEquals(0, $period->getNumberOfSubperiods()); - } - - /** - * yesterday 23:59:59 is finished - * @group Core - */ - public function testDayIsFinishedYesterday() - { - - $period = new Day(Date::yesterday()); - $this->assertEquals(date("Y-m-d", time() - 86400), $period->toString()); - $this->assertEquals(array(), $period->getSubperiods()); - $this->assertEquals(0, $period->getNumberOfSubperiods()); - } - - /** - * tomorrow is not finished - * @group Core - */ - public function testDayIsFinishedTomorrow() - { - $period = new Day(Date::factory(date("Y-m-d", time() + 86400))); - $this->assertEquals(date("Y-m-d", time() + 86400), $period->toString()); - $this->assertEquals(array(), $period->getSubperiods()); - $this->assertEquals(0, $period->getNumberOfSubperiods()); - } - - /** - * test day doesnt exist 31st feb - * @group Core - */ - public function testDayIsFinished31stfeb() - { - $period = new Day(Date::factory("2007-02-31")); - $this->assertEquals("2007-03-03", $period->toString()); - $this->assertEquals(array(), $period->getSubperiods()); - $this->assertEquals(0, $period->getNumberOfSubperiods()); - } - - /** - * test date that doesn't exist, should return the corresponding correct date - * @group Core - */ - public function testDayGetDateStart1() - { - // create the period - $period = new Day(Date::factory("2007-02-31")); - - // start date - $startDate = $period->getDateStart(); - - // expected string - $this->assertEquals("2007-03-03", $startDate->toString()); - - // check that for a day, getDateStart = getStartEnd - $this->assertEquals($startDate, $period->getDateEnd()); - } - - /** - * test normal date - * @group Core - */ - public function testDayGetDateStart2() - { - // create the period - $period = new Day(Date::factory("2007-01-03")); - - // start date - $startDate = $period->getDateStart(); - - // expected string - $this->assertEquals("2007-01-03", $startDate->toString()); - - // check that for a day, getDateStart = getStartEnd - $this->assertEquals($startDate, $period->getDateEnd()); - } - - /** - * test last day of year - * @group Core - */ - public function testDayGetDateStart3() - { - // create the period - $period = new Day(Date::factory("2007-12-31")); - - // start date - $startDate = $period->getDateStart(); - - // expected string - $this->assertEquals("2007-12-31", $startDate->toString()); - - // check that for a day, getDateStart = getStartEnd - $this->assertEquals($startDate, $period->getDateEnd()); - } - - /** - * test date that doesn't exist, should return the corresponding correct date - * @group Core - */ - public function testDayGetDateEnd1() - { - // create the period - $period = new Day(Date::factory("2007-02-31")); - - // end date - $endDate = $period->getDateEnd(); - - // expected string - $this->assertEquals("2007-03-03", $endDate->toString()); - } - - /** - * test normal date - * @group Core - */ - public function testDayGetDateEnd2() - { - // create the period - $period = new Day(Date::factory("2007-04-15")); - - // end date - $endDate = $period->getDateEnd(); - - // expected string - $this->assertEquals("2007-04-15", $endDate->toString()); - } - - /** - * test last day of year - * @group Core - */ - public function testDayGetDateEnd3() - { - // create the period - $period = new Day(Date::factory("2007-12-31")); - - // end date - $endDate = $period->getDateEnd(); - - // expected string - $this->assertEquals("2007-12-31", $endDate->toString()); - } - - /** - * adding a subperiod should not be possible - * @group Core - */ - public function testAddSubperiodFails() - { - // create the period - $period = new Day(Date::factory("2007-12-31")); - - try { - $period->addSubperiod(''); - } catch (Exception $e) { - return; - } - // expected string - $this->fail('Exception not raised'); - } - - /** - * @group Core - */ - public function testGetLocalizedShortString() - { - $this->loadEnglishTranslation(); - - $month = new Day(Date::factory('2024-10-09')); - $shouldBe = 'Wed 9 Oct'; - $this->assertEquals($shouldBe, $month->getLocalizedShortString()); - } - - /** - * @group Core - */ - public function testGetLocalizedLongString() - { - $this->loadEnglishTranslation(); - - $month = new Day(Date::factory('2024-10-09')); - $shouldBe = 'Wednesday 9 October 2024'; - $this->assertEquals($shouldBe, $month->getLocalizedLongString()); - } - - /** - * @group Core - */ - public function testGetPrettyString() - { - $this->loadEnglishTranslation(); - - $month = new Day(Date::factory('2024-10-09')); - $shouldBe = '2024-10-09'; - $this->assertEquals($shouldBe, $month->getPrettyString()); - } - - private function loadEnglishTranslation() - { - Translate::reloadLanguage('en'); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/Period/MonthTest.php b/tests/PHPUnit/Core/Period/MonthTest.php deleted file mode 100644 index 5821aceee5..0000000000 --- a/tests/PHPUnit/Core/Period/MonthTest.php +++ /dev/null @@ -1,309 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Date; -use Piwik\Period\Month; -use Piwik\Translate; - -/** - * Testing Period_Month - */ -class Period_MonthTest extends PHPUnit_Framework_TestCase -{ - /** - * testing december - * @group Core - */ - public function testMonthDec() - { - $month = new Month(Date::factory("2006-12-31")); - $correct = array( - "2006-12-01", - "2006-12-02", - "2006-12-03", - "2006-12-04", - "2006-12-05", - "2006-12-06", - "2006-12-07", - "2006-12-08", - "2006-12-09", - "2006-12-10", - "2006-12-11", - "2006-12-12", - "2006-12-13", - "2006-12-14", - "2006-12-15", - "2006-12-16", - "2006-12-17", - "2006-12-18", - "2006-12-19", - "2006-12-20", - "2006-12-21", - "2006-12-22", - "2006-12-23", - "2006-12-24", - "2006-12-25", - "2006-12-26", - "2006-12-27", - "2006-12-28", - "2006-12-29", - "2006-12-30", - "2006-12-31",); - $this->assertEquals($correct, $month->toString()); - $this->assertEquals(31, $month->getNumberOfSubperiods()); - } - - /** - * testing month feb leap year - * @group Core - */ - public function testMonthFebLeap() - { - $month = new Month(Date::factory("2024-02-11")); - $correct = array( - "2024-02-01", - "2024-02-02", - "2024-02-03", - "2024-02-04", - "2024-02-05", - "2024-02-06", - "2024-02-07", - "2024-02-08", - "2024-02-09", - "2024-02-10", - "2024-02-11", - "2024-02-12", - "2024-02-13", - "2024-02-14", - "2024-02-15", - "2024-02-16", - "2024-02-17", - "2024-02-18", - "2024-02-19", - "2024-02-20", - "2024-02-21", - "2024-02-22", - "2024-02-23", - "2024-02-24", - "2024-02-25", - "2024-02-26", - "2024-02-27", - "2024-02-28", - "2024-02-29",); - $this->assertEquals($correct, $month->toString()); - $this->assertEquals(29, $month->getNumberOfSubperiods()); - } - - /** - * testing month feb non-leap year - * @group Core - */ - public function testMonthFebNonLeap() - { - $month = new Month(Date::factory("2023-02-11")); - $correct = array( - "2023-02-01", - "2023-02-02", - "2023-02-03", - "2023-02-04", - "2023-02-05", - "2023-02-06", - "2023-02-07", - "2023-02-08", - "2023-02-09", - "2023-02-10", - "2023-02-11", - "2023-02-12", - "2023-02-13", - "2023-02-14", - "2023-02-15", - "2023-02-16", - "2023-02-17", - "2023-02-18", - "2023-02-19", - "2023-02-20", - "2023-02-21", - "2023-02-22", - "2023-02-23", - "2023-02-24", - "2023-02-25", - "2023-02-26", - "2023-02-27", - "2023-02-28",); - $this->assertEquals($correct, $month->toString()); - $this->assertEquals(28, $month->getNumberOfSubperiods()); - } - - /** - * testing jan - * @group Core - */ - public function testMonthJan() - { - $month = new Month(Date::factory("2007-01-01")); - $correct = array( - "2007-01-01", - "2007-01-02", - "2007-01-03", - "2007-01-04", - "2007-01-05", - "2007-01-06", - "2007-01-07", - "2007-01-08", - "2007-01-09", - "2007-01-10", - "2007-01-11", - "2007-01-12", - "2007-01-13", - "2007-01-14", - "2007-01-15", - "2007-01-16", - "2007-01-17", - "2007-01-18", - "2007-01-19", - "2007-01-20", - "2007-01-21", - "2007-01-22", - "2007-01-23", - "2007-01-24", - "2007-01-25", - "2007-01-26", - "2007-01-27", - "2007-01-28", - "2007-01-29", - "2007-01-30", - "2007-01-31",); - $this->assertEquals($correct, $month->toString()); - $this->assertEquals(31, $month->getNumberOfSubperiods()); - } - - /** - * testing month containing a time change (DST) - * @group Core - */ - public function testMonthDSTChangeMarch() - { - $month = new Month(Date::factory("2007-02-31")); - $correct = array( - "2007-03-01", - "2007-03-02", - "2007-03-03", - "2007-03-04", - "2007-03-05", - "2007-03-06", - "2007-03-07", - "2007-03-08", - "2007-03-09", - "2007-03-10", - "2007-03-11", - "2007-03-12", - "2007-03-13", - "2007-03-14", - "2007-03-15", - "2007-03-16", - "2007-03-17", - "2007-03-18", - "2007-03-19", - "2007-03-20", - "2007-03-21", - "2007-03-22", - "2007-03-23", - "2007-03-24", - "2007-03-25", - "2007-03-26", - "2007-03-27", - "2007-03-28", - "2007-03-29", - "2007-03-30", - "2007-03-31",); - $this->assertEquals($correct, $month->toString()); - $this->assertEquals(31, $month->getNumberOfSubperiods()); - } - - /** - * @group Core - */ - public function testMonthDSTChangeOct() - { - $month = new Month(Date::factory("2017-10-31")); - $correct = array( - "2017-10-01", - "2017-10-02", - "2017-10-03", - "2017-10-04", - "2017-10-05", - "2017-10-06", - "2017-10-07", - "2017-10-08", - "2017-10-09", - "2017-10-10", - "2017-10-11", - "2017-10-12", - "2017-10-13", - "2017-10-14", - "2017-10-15", - "2017-10-16", - "2017-10-17", - "2017-10-18", - "2017-10-19", - "2017-10-20", - "2017-10-21", - "2017-10-22", - "2017-10-23", - "2017-10-24", - "2017-10-25", - "2017-10-26", - "2017-10-27", - "2017-10-28", - "2017-10-29", - "2017-10-30", - "2017-10-31",); - $this->assertEquals($correct, $month->toString()); - $this->assertEquals(31, $month->getNumberOfSubperiods()); - } - - /** - * @group Core - */ - public function testGetLocalizedShortString() - { - $this->loadEnglishTranslation(); - - $month = new Month(Date::factory('2024-10-09')); - $shouldBe = 'Oct 2024'; - $this->assertEquals($shouldBe, $month->getLocalizedShortString()); - } - - /** - * @group Core - */ - public function testGetLocalizedLongString() - { - $this->loadEnglishTranslation(); - - $month = new Month(Date::factory('2024-10-09')); - $shouldBe = '2024, October'; - $this->assertEquals($shouldBe, $month->getLocalizedLongString()); - } - - /** - * @group Core - */ - public function testGetPrettyString() - { - $this->loadEnglishTranslation(); - - $month = new Month(Date::factory('2024-10-09')); - $shouldBe = '2024-10'; - $this->assertEquals($shouldBe, $month->getPrettyString()); - } - - private function loadEnglishTranslation() - { - Translate::reloadLanguage('en'); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/Period/RangeTest.php b/tests/PHPUnit/Core/Period/RangeTest.php deleted file mode 100644 index b2114a4372..0000000000 --- a/tests/PHPUnit/Core/Period/RangeTest.php +++ /dev/null @@ -1,1320 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Date; -use Piwik\Period\Month; -use Piwik\Period\Range; -use Piwik\Period\Week; -use Piwik\Period\Year; -use Piwik\Translate; - -/** - * @group Core_Period_RangeTest - */ -class Period_RangeTest extends PHPUnit_Framework_TestCase -{ - // test range 1 - /** - * @group Core - */ - public function testRangeToday() - { - $range = new Range('day', 'last1'); - $today = Date::today(); - - $correct = array( - $today->toString(), - ); - $correct = array_reverse($correct); - - $this->assertEquals(1, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testRangeTodayUtcPlus12() - { - // rather ugly test, UTC+23 doesn't exist, but it's a way to test that last1 in UTC+23 will be "our" UTC tomorrow - $range = new Range('day', 'last1', 'UTC+23'); - $today = Date::now()->addHour(23); - - $correct = array( - $today->toString(), - ); - $correct = array_reverse($correct); - - $this->assertEquals(1, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range 2 - /** - * @group Core - */ - public function testRange2days() - { - $range = new Range('day', 'last2'); - $today = Date::today(); - - $correct = array( - $today->toString(), - $today->subDay(1)->toString() - ); - $correct = array_reverse($correct); - - $this->assertEquals(2, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range 3 - /** - * @group Core - */ - public function testRange5days() - { - $range = new Range('day', 'last50'); - $today = Date::today(); - - $correct = array(); - for ($i = 0; $i < 50; $i++) { - $correct[] = $today->subDay($i)->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(50, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range 4 - /** - * @group Core - */ - public function testRangePrevious3days() - { - $range = new Range('day', 'previous3'); - $yesterday = Date::yesterday(); - - $correct = array(); - for ($i = 0; $i < 3; $i++) { - $correct[] = $yesterday->subDay($i)->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(3, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range date1,date2 - /** - * @group Core - */ - public function testRangeComma1() - { - - $range = new Range('day', '2008-01-01,2008-01-03'); - - $correct = array( - '2008-01-01', - '2008-01-02', - '2008-01-03', - ); - - $this->assertEquals(3, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range date1,date2 - /** - * @group Core - */ - public function testRangeComma2() - { - - $range = new Range('day', '2007-12-22,2008-01-03'); - - $correct = array( - '2007-12-22', - '2007-12-23', - '2007-12-24', - '2007-12-25', - '2007-12-26', - '2007-12-27', - '2007-12-28', - '2007-12-29', - '2007-12-30', - '2007-12-31', - '2008-01-01', - '2008-01-02', - '2008-01-03', - ); - - $this->assertEquals(13, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range date1,date2 - /** - * @group Core - */ - public function testRangeWeekcomma1() - { - $range = new Range('week', '2007-12-22,2008-01-03'); - $range2 = new Range('week', '2007-12-19,2008-01-03'); - - $correct = array( - array( - '2007-12-17', - '2007-12-18', - '2007-12-19', - '2007-12-20', - '2007-12-21', - '2007-12-22', - '2007-12-23', - ), - array( - '2007-12-24', - '2007-12-25', - '2007-12-26', - '2007-12-27', - '2007-12-28', - '2007-12-29', - '2007-12-30', - ), - array( - '2007-12-31', - '2008-01-01', - '2008-01-02', - '2008-01-03', - '2008-01-04', - '2008-01-05', - '2008-01-06', - ) - ); - - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals(count($correct), $range2->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - $this->assertEquals($correct, $range2->toString()); - } - - // test range date1,date2 - /** - * @group Core - */ - public function testRangeYearcomma1() - { - $range = new Range('year', '2006-12-22,2007-01-03'); - - $correct = array( - array( - 0 => '2006-01-01', - 1 => '2006-02-01', - 2 => '2006-03-01', - 3 => '2006-04-01', - 4 => '2006-05-01', - 5 => '2006-06-01', - 6 => '2006-07-01', - 7 => '2006-08-01', - 8 => '2006-09-01', - 9 => '2006-10-01', - 10 => '2006-11-01', - 11 => '2006-12-01', - ), - 1 => - array( - 0 => '2007-01-01', - 1 => '2007-02-01', - 2 => '2007-03-01', - 3 => '2007-04-01', - 4 => '2007-05-01', - 5 => '2007-06-01', - 6 => '2007-07-01', - 7 => '2007-08-01', - 8 => '2007-09-01', - 9 => '2007-10-01', - 10 => '2007-11-01', - 11 => '2007-12-01', - ), - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range date1,date2 - /** - * @group Core - */ - public function testRangeMonthcomma1() - { - $range = new Range('month', '2006-12-22,2007-01-03'); - - $correct = array( - array( - '2006-12-01', - '2006-12-02', - '2006-12-03', - '2006-12-04', - '2006-12-05', - '2006-12-06', - '2006-12-07', - '2006-12-08', - '2006-12-09', - '2006-12-10', - '2006-12-11', - '2006-12-12', - '2006-12-13', - '2006-12-14', - '2006-12-15', - '2006-12-16', - '2006-12-17', - '2006-12-18', - '2006-12-19', - '2006-12-20', - '2006-12-21', - '2006-12-22', - '2006-12-23', - '2006-12-24', - '2006-12-25', - '2006-12-26', - '2006-12-27', - '2006-12-28', - '2006-12-29', - '2006-12-30', - '2006-12-31', - ), - array( - '2007-01-01', - '2007-01-02', - '2007-01-03', - '2007-01-04', - '2007-01-05', - '2007-01-06', - '2007-01-07', - '2007-01-08', - '2007-01-09', - '2007-01-10', - '2007-01-11', - '2007-01-12', - '2007-01-13', - '2007-01-14', - '2007-01-15', - '2007-01-16', - '2007-01-17', - '2007-01-18', - '2007-01-19', - '2007-01-20', - '2007-01-21', - '2007-01-22', - '2007-01-23', - '2007-01-24', - '2007-01-25', - '2007-01-26', - '2007-01-27', - '2007-01-28', - '2007-01-29', - '2007-01-30', - '2007-01-31', - ), - ); - - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range WEEK - /** - * @group Core - */ - public function testRangeWeek() - { - $range = new Range('week', 'last50'); - $today = Date::today(); - - $correct = array(); - for ($i = 0; $i < 50; $i++) { - $date = $today->subDay($i * 7); - $week = new Week($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(50, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range WEEK last1 - /** - * @group Core - */ - public function testRangeWeekLast1() - { - $range = new Range('week', 'last1'); - $currentWeek = new Week(Date::today()); - $this->assertEquals(1, $range->getNumberOfSubperiods()); - $this->assertEquals(array($currentWeek->toString()), $range->toString()); - } - - // test range MONTH - /** - * @group Core - */ - public function testRangeMonth() - { - $range = new Range('month', 'last20'); - $today = Date::today(); - - $correct = array(); - for ($i = 0; $i < 20; $i++) { - $date = $today->subMonth($i); - $week = new Month($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(20, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range MONTH last1 - /** - * @group Core - */ - public function testRangeMonthLast1() - { - $range = new Range('month', 'last1'); - $month = new Month(Date::today()); - $this->assertEquals(1, $range->getNumberOfSubperiods()); - $this->assertEquals(array($month->toString()), $range->toString()); - } - - // test range PREVIOUS MONTH - /** - * @group Core - */ - public function testRangePreviousmonth() - { - $range = new Range('month', 'previous10'); - $end = Date::today(); - $end = $end->subMonth(1); - - $correct = array(); - for ($i = 0; $i < 10; $i++) { - $date = $end->subMonth($i); - $week = new Month($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(10, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testRangePreviousmonth_onLastDayOfMonth() - { - $end = Date::factory('2013-10-31'); - $range = new Range('month', 'previous10', 'UTC', $end); - $end = $end->subMonth(1); - - $correct = array(); - for ($i = 0; $i < 10; $i++) { - $date = $end->subMonth($i); - $week = new Month($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(10, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testRangePreviousweek_onLastDayOfWeek() - { - $end = Date::factory('2013-11-03'); - $range = new Range('week', 'previous2', 'UTC', $end); - $end = $end->subWeek(1); - - $correct = array(); - for ($i = 0; $i < 2; $i++) { - $date = $end->subWeek($i); - $week = new Week($date); - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testRangePreviousweek_onFirstDayOfWeek() - { - $end = Date::factory('2013-11-04'); - $range = new Range('week', 'previous2', 'UTC', $end); - $end = $end->subWeek(1); - - $correct = array(); - for ($i = 0; $i < 2; $i++) { - $date = $end->subWeek($i); - $week = new Week($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - $this->assertEquals($correct, $range->toString()); - } - /** - * @group Core - */ - public function testRangeLastweek_onFirstDayOfWeek() - { - $end = Date::factory('2013-11-04'); - $range = new Range('week', 'last2', 'UTC', $end); - - $correct = array(); - for ($i = 0; $i < 2; $i++) { - $date = $end->subWeek($i); - $week = new Week($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testRangeLastmonth_onLastDayOfMonth() - { - $end = Date::factory('2013-10-31'); - $range = new Range('month', 'last10', 'UTC', $end); - - $correct = array(); - for ($i = 0; $i < 10; $i++) { - $date = $end->subMonth($i); - $week = new Month($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(10, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function _testRangePreviousmonth_onFirstOfMonth() - { - $end = Date::factory('2013-11-01'); - $range = new Range('month', 'previous10', 'UTC', $end); - $end = $end->subMonth(1); - - $correct = array(); - for ($i = 0; $i < 10; $i++) { - $date = $end->subMonth($i); - $week = new Month($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(10, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function _testRangeLastmonth_onFirstOfMonth() - { - $end = Date::factory('2013-11-01'); - $range = new Range('month', 'last10', 'UTC', $end); - - $correct = array(); - for ($i = 0; $i < 10; $i++) { - $date = $end->subMonth($i); - $week = new Month($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(10, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range YEAR - /** - * @group Core - */ - public function testRangeYear() - { - $range = new Range('year', 'last10'); - $today = Date::today(); - - $correct = array(); - for ($i = 0; $i < 10; $i++) { - $date = $today->subMonth(12 * $i); - $week = new Year($date); - - $correct[] = $week->toString(); - } - $correct = array_reverse($correct); - - $this->assertEquals(10, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - // test range YEAR last1 - /** - * @group Core - */ - public function testRangeYearLast1() - { - $range = new Range('year', 'last1'); - $currentYear = new Year(Date::today()); - $this->assertEquals(1, $range->getNumberOfSubperiods()); - $this->assertEquals(array($currentYear->toString()), $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeYearUsesYearIfPossible() - { - $range = new Range('range', '2005-12-17,2008-01-03', 'UTC', Date::factory('2008-01-03')); - $year2006 = new Year(Date::factory('2006-02-02')); - $year2007 = new Year(Date::factory('2007-02-02')); - $year2008 = new Year(Date::factory('2008-02-02')); - - $correct = array( - '2005-12-17', - '2005-12-18', - array ( - "2005-12-19", - "2005-12-20", - "2005-12-21", - "2005-12-22", - "2005-12-23", - "2005-12-24", - "2005-12-25" - ), - "2005-12-26", - "2005-12-27", - "2005-12-28", - "2005-12-29", - "2005-12-30", - "2005-12-31", - $year2006->toString(), - $year2007->toString(), - $year2008->toString() - ); - - $this->assertEquals(12, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeIsYear_UsesFullYear() - { - $range = new Range('range', '2011-01-01,2011-12-31', 'UTC', Date::factory('2012-01-03')); - $year2011 = new Year(Date::factory('2011-02-02')); - - $correct = array( - $year2011->toString() - ); - - $this->assertEquals(1, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeYear_UsesCurrentYear() - { - $range = new Range('range', '2013-01-01,2013-11-01', 'UTC', Date::factory('2013-11-01')); - $year2013 = new Year(Date::factory('2013-02-02')); - - $correct = array( - $year2013->toString() - ); - - $this->assertEquals(1, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeYearUsesCurrentYear_onLastDayOfYear() - { - $range = new Range('range', '2013-01-01,2013-12-31', 'UTC', Date::factory('2013-12-31')); - $year2013 = new Year(Date::factory('2013-01-01')); - - $correct = array( - $year2013->toString() - ); - - $this->assertEquals(1, $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeWeekInsideEndingToday() - { - $range = new Range('range', '2007-12-22,2008-01-03', 'UTC', Date::factory('2008-01-03')); - - $correct = array( - '2007-12-22', - '2007-12-23', - array( - '2007-12-24', - '2007-12-25', - '2007-12-26', - '2007-12-27', - '2007-12-28', - '2007-12-29', - '2007-12-30', - ), - array( - '2007-12-31', - '2008-01-01', - '2008-01-02', - '2008-01-03', - '2008-01-04', - '2008-01-05', - '2008-01-06', - ) - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testRangeEndDateIsTodayAndStartDateNotStartOfTheWeek() - { - $range = new Range('range', '2013-10-29,2013-10-30', 'UTC', Date::factory('2013-10-30')); - - $correct = array( - '2013-10-29', - '2013-10-30' - ); - - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testRangeEndDateIsInFuture() - { - $range = new Range('range', '2013-10-29,2013-10-31', 'UTC', Date::factory('2013-10-30')); - - $correct = array( - '2013-10-29', - '2013-10-30', - '2013-10-31' - ); - - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testRangePreviousmonthEndDateIsInFutureAndEndOfTheWeek() - { - $range = new Range('range', '2013-10-29,2013-11-03', 'UTC', Date::factory('2013-10-30')); - - $correct = array( - '2013-10-29', - '2013-10-30', - '2013-10-31', - '2013-11-01', - '2013-11-02', - '2013-11-03', - ); - - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeWeekInsideEndingYesterday() - { - $todays = array( - Date::factory('2008-01-04'), - Date::factory('2008-01-05'), - Date::factory('2008-01-14'), - Date::factory('2008-02-14'), - Date::factory('2009-02-14'), - ); - - foreach ($todays as $today) { - $range = new Range('range', '2007-12-22,2008-01-03', 'UTC', $today); - - $correct = array( - '2007-12-22', - '2007-12-23', - array( - '2007-12-24', - '2007-12-25', - '2007-12-26', - '2007-12-27', - '2007-12-28', - '2007-12-29', - '2007-12-30', - ), - '2007-12-31', - '2008-01-01', - '2008-01-02', - '2008-01-03', - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - } - - /** - * @group Core - */ - public function testCustomRangeOnlyDaysLessThanOneWeek() - { - $range = new Range('range', '2007-12-30,2008-01-01'); - - $correct = array( - '2007-12-30', - '2007-12-31', - '2008-01-01', - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeOneWeekOnly() - { - $range = new Range('range', '2007-12-31,2008-01-06'); - - $correct = array( - array( - '2007-12-31', - '2008-01-01', - '2008-01-02', - '2008-01-03', - '2008-01-04', - '2008-01-05', - '2008-01-06', - ) - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeStartsWithWeek() - { - $range = new Range('range', '2007-12-31,2008-01-08'); - - $correct = array( - array( - '2007-12-31', - '2008-01-01', - '2008-01-02', - '2008-01-03', - '2008-01-04', - '2008-01-05', - '2008-01-06', - ), - '2008-01-07', - '2008-01-08', - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeEndsWithWeek() - { - $range = new Range('range', '2007-12-21,2008-01-06'); - - $correct = array( - '2007-12-21', - '2007-12-22', - '2007-12-23', - array( - '2007-12-24', - '2007-12-25', - '2007-12-26', - '2007-12-27', - '2007-12-28', - '2007-12-29', - '2007-12-30', - ), - array( - '2007-12-31', - '2008-01-01', - '2008-01-02', - '2008-01-03', - '2008-01-04', - '2008-01-05', - '2008-01-06', - ), - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeContainsMonthAndWeek() - { - $range = new Range('range', '2011-09-18,2011-11-02', 'UTC', Date::factory('2012-01-01')); - - $correct = array( - - '2011-09-18', - array( - '2011-09-19', - '2011-09-20', - '2011-09-21', - '2011-09-22', - '2011-09-23', - '2011-09-24', - '2011-09-25', - ), - - '2011-09-26', - '2011-09-27', - '2011-09-28', - '2011-09-29', - '2011-09-30', - array( - "2011-10-01", - "2011-10-02", - "2011-10-03", - "2011-10-04", - "2011-10-05", - "2011-10-06", - "2011-10-07", - "2011-10-08", - "2011-10-09", - "2011-10-10", - "2011-10-11", - "2011-10-12", - "2011-10-13", - "2011-10-14", - "2011-10-15", - "2011-10-16", - "2011-10-17", - "2011-10-18", - "2011-10-19", - "2011-10-20", - "2011-10-21", - "2011-10-22", - "2011-10-23", - "2011-10-24", - "2011-10-25", - "2011-10-26", - "2011-10-27", - "2011-10-28", - "2011-10-29", - "2011-10-30", - "2011-10-31", - ), - "2011-11-01", - "2011-11-02", - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeContainsSeveralMonthsAndWeeksStartingWithMonth() - { - // Testing when "today" is in the same month, or later in the future - $todays = array( - Date::factory('2011-10-18'), - Date::factory('2011-10-19'), - Date::factory('2011-10-24'), - Date::factory('2011-11-01'), - Date::factory('2011-11-30'), - Date::factory('2011-12-31'), - Date::factory('2021-10-18') - ); - foreach ($todays as $today) { - $range = new Range('range', '2011-08-01,2011-10-17', 'UTC', $today); - - $correct = array( - - array( - "2011-08-01", - "2011-08-02", - "2011-08-03", - "2011-08-04", - "2011-08-05", - "2011-08-06", - "2011-08-07", - "2011-08-08", - "2011-08-09", - "2011-08-10", - "2011-08-11", - "2011-08-12", - "2011-08-13", - "2011-08-14", - "2011-08-15", - "2011-08-16", - "2011-08-17", - "2011-08-18", - "2011-08-19", - "2011-08-20", - "2011-08-21", - "2011-08-22", - "2011-08-23", - "2011-08-24", - "2011-08-25", - "2011-08-26", - "2011-08-27", - "2011-08-28", - "2011-08-29", - "2011-08-30", - "2011-08-31", - ), - array( - "2011-09-01", - "2011-09-02", - "2011-09-03", - "2011-09-04", - "2011-09-05", - "2011-09-06", - "2011-09-07", - "2011-09-08", - "2011-09-09", - "2011-09-10", - "2011-09-11", - "2011-09-12", - "2011-09-13", - "2011-09-14", - "2011-09-15", - "2011-09-16", - "2011-09-17", - "2011-09-18", - "2011-09-19", - "2011-09-20", - "2011-09-21", - "2011-09-22", - "2011-09-23", - "2011-09-24", - "2011-09-25", - "2011-09-26", - "2011-09-27", - "2011-09-28", - "2011-09-29", - "2011-09-30", - ), - "2011-10-01", - "2011-10-02", - - array( - "2011-10-03", - "2011-10-04", - "2011-10-05", - "2011-10-06", - "2011-10-07", - "2011-10-08", - "2011-10-09", - ), - array( - "2011-10-10", - "2011-10-11", - "2011-10-12", - "2011-10-13", - "2011-10-14", - "2011-10-15", - "2011-10-16", - ), - "2011-10-17", - ); - - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - } - - /** - * @group Core - */ - public function testCustomRangeOneMonthOnly() - { - $range = new Range('range', '2011-09-01,2011-09-30'); - - $correct = array( - array( - "2011-09-01", - "2011-09-02", - "2011-09-03", - "2011-09-04", - "2011-09-05", - "2011-09-06", - "2011-09-07", - "2011-09-08", - "2011-09-09", - "2011-09-10", - "2011-09-11", - "2011-09-12", - "2011-09-13", - "2011-09-14", - "2011-09-15", - "2011-09-16", - "2011-09-17", - "2011-09-18", - "2011-09-19", - "2011-09-20", - "2011-09-21", - "2011-09-22", - "2011-09-23", - "2011-09-24", - "2011-09-25", - "2011-09-26", - "2011-09-27", - "2011-09-28", - "2011-09-29", - "2011-09-30", - )); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function test_CustomRange_startsWithWeek_EndsWithMonth() - { - $range = new Range('range', '2011-07-25,2011-08-31'); - - $correct = array( - - array( - '2011-07-25', - '2011-07-26', - '2011-07-27', - '2011-07-28', - '2011-07-29', - '2011-07-30', - '2011-07-31', - ), - array( - "2011-08-01", - "2011-08-02", - "2011-08-03", - "2011-08-04", - "2011-08-05", - "2011-08-06", - "2011-08-07", - "2011-08-08", - "2011-08-09", - "2011-08-10", - "2011-08-11", - "2011-08-12", - "2011-08-13", - "2011-08-14", - "2011-08-15", - "2011-08-16", - "2011-08-17", - "2011-08-18", - "2011-08-19", - "2011-08-20", - "2011-08-21", - "2011-08-22", - "2011-08-23", - "2011-08-24", - "2011-08-25", - "2011-08-26", - "2011-08-27", - "2011-08-28", - "2011-08-29", - "2011-08-30", - "2011-08-31", - )); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangeBeforeIsAfterYearRight() - { - try { - $range = new Range('range', '2007-02-09,2007-02-01'); - $this->assertEquals(0, $range->getNumberOfSubperiods()); - $this->assertEquals(array(), $range->toString()); - - $range->getPrettyString(); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * @group Core - */ - public function testCustomRangeLastN() - { - $range = new Range('range', 'last4'); - $range->setDefaultEndDate(Date::factory('2008-01-03')); - $correct = array( - '2007-12-31', - '2008-01-01', - '2008-01-02', - '2008-01-03', - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangePreviousN() - { - $range = new Range('range', 'previous3'); - $range->setDefaultEndDate(Date::factory('2008-01-03')); - $correct = array( - '2007-12-31', - '2008-01-01', - '2008-01-02', - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testCustomRangePreviousNEndToday() - { - $range = new Range('range', 'previous3'); - $correct = array( - date('Y-m-d', time() - 86400 * 3), - date('Y-m-d', time() - 86400 * 2), - date('Y-m-d', time() - 86400 * 1), - ); - $this->assertEquals(count($correct), $range->getNumberOfSubperiods()); - $this->assertEquals($correct, $range->toString()); - } - - /** - * @group Core - */ - public function testInvalidRangeThrows() - { - try { - $range = new Range('range', '0001-01-01,today'); - $range->getLocalizedLongString(); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * @group Core - */ - public function testGetLocalizedShortString() - { - $this->loadEnglishTranslation(); - $month = new Range('range', '2000-12-09,2001-02-01'); - $shouldBe = '9 Dec 00 - 1 Feb 01'; - $this->assertEquals($shouldBe, $month->getLocalizedShortString()); - } - - /** - * @group Core - */ - public function testGetLocalizedLongString() - { - $this->loadEnglishTranslation(); - $month = new Range('range', '2023-05-09,2023-05-21'); - $shouldBe = '8 May 23 - 21 May 23'; - $this->assertEquals($shouldBe, $month->getLocalizedLongString()); - } - - /** - * @group Core - */ - public function testGetPrettyString() - { - $this->loadEnglishTranslation(); - $month = new Range('range', '2007-02-09,2007-03-15'); - $shouldBe = 'From 2007-02-09 to 2007-03-15'; - $this->assertEquals($shouldBe, $month->getPrettyString()); - } - - /** - * Data provider for testLastNLimits. - */ - public function getDataForLastNLimitsTest() - { - return array(array('day', 5 * 365 + 1, 5 * 365), - array('week', 10 * 52 + 1, 10 * 52), - array('month', 121, 120), - array('year', 11, 10)); - } - - /** - * @group Core - * - * - * @dataProvider getDataForLastNLimitsTest - */ - public function testLastNLimits($period, $lastN, $expectedLastN) - { - $range = new Range($period, 'last' . $lastN); - $this->assertEquals($expectedLastN, $range->getNumberOfSubperiods()); - } - - private function loadEnglishTranslation() - { - Translate::reloadLanguage('en'); - } -} diff --git a/tests/PHPUnit/Core/Period/WeekTest.php b/tests/PHPUnit/Core/Period/WeekTest.php deleted file mode 100644 index 2994f8e13d..0000000000 --- a/tests/PHPUnit/Core/Period/WeekTest.php +++ /dev/null @@ -1,158 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Date; -use Piwik\Period\Week; -use Piwik\Translate; - -/** - * Testing Period_Week - */ -class Period_WeekTest extends PHPUnit_Framework_TestCase -{ - /** - * test week between 2 years - * @group Core - */ - public function testWeekBetween2years() - { - $week = new Week(Date::factory("2006-01-01")); - $correct = array( - "2005-12-26", - "2005-12-27", - "2005-12-28", - "2005-12-29", - "2005-12-30", - "2005-12-31", - "2006-01-01",); - $this->assertEquals($correct, $week->toString()); - $this->assertEquals(7, $week->getNumberOfSubperiods()); - } - - /** - * test week between 2 months Week Mai 29 To Mai 31 2006 - * @group Core - */ - public function testWeekBetween2month() - { - $week = new Week(Date::factory("2006-05-29")); - $correct = array( - "2006-05-29", - "2006-05-30", - "2006-05-31", - "2006-06-01", - "2006-06-02", - "2006-06-03", - "2006-06-04",); - $this->assertEquals($correct, $week->toString()); - $this->assertEquals(7, $week->getNumberOfSubperiods()); - } - - /** - * test week between feb and march for leap year - * @group Core - */ - public function testWeekFebLeapyear() - { - $correct = array( - '2023-02-27', - '2023-02-28', - '2023-03-01', - '2023-03-02', - '2023-03-03', - '2023-03-04', - '2023-03-05',); - - $week = new Week(Date::factory('2023-02-27')); - $this->assertEquals($correct, $week->toString()); - $this->assertEquals(7, $week->getNumberOfSubperiods()); - $week = new Week(Date::factory('2023-03-01')); - $this->assertEquals($correct, $week->toString()); - $this->assertEquals(7, $week->getNumberOfSubperiods()); - } - - /** - * test week between feb and march for no leap year - * @group Core - */ - public function testWeekFebnonLeapyear() - { - $correct = array( - '2024-02-26', - '2024-02-27', - '2024-02-28', - '2024-02-29', - '2024-03-01', - '2024-03-02', - '2024-03-03',); - - $week = new Week(Date::factory('2024-02-27')); - $this->assertEquals($correct, $week->toString()); - $this->assertEquals(7, $week->getNumberOfSubperiods()); - $week = new Week(Date::factory('2024-03-01')); - $this->assertEquals($correct, $week->toString()); - $this->assertEquals(7, $week->getNumberOfSubperiods()); - } - - /** - * test week normal middle of the month - * @group Core - */ - public function testWeekMiddleofmonth() - { - $correct = array( - '2024-10-07', - '2024-10-08', - '2024-10-09', - '2024-10-10', - '2024-10-11', - '2024-10-12', - '2024-10-13',); - - $week = new Week(Date::factory('2024-10-09')); - $this->assertEquals($correct, $week->toString()); - $this->assertEquals(7, $week->getNumberOfSubperiods()); - } - - /** - * @group Core - */ - public function testGetLocalizedShortString() - { - $this->loadEnglishTranslation(); - $week = new Week(Date::factory('2024-10-09')); - $shouldBe = '7 Oct - 13 Oct 24'; - $this->assertEquals($shouldBe, $week->getLocalizedShortString()); - } - - /** - * @group Core - */ - public function testGetLocalizedLongString() - { - $this->loadEnglishTranslation(); - $week = new Week(Date::factory('2024-10-09')); - $shouldBe = 'Week 7 October - 13 October 2024'; - $this->assertEquals($shouldBe, $week->getLocalizedLongString()); - } - - /** - * @group Core - */ - public function testGetPrettyString() - { - $this->loadEnglishTranslation(); - $week = new Week(Date::factory('2024-10-09')); - $shouldBe = 'From 2024-10-07 to 2024-10-13'; - $this->assertEquals($shouldBe, $week->getPrettyString()); - } - - private function loadEnglishTranslation() - { - Translate::reloadLanguage('en'); - } -} diff --git a/tests/PHPUnit/Core/Period/YearTest.php b/tests/PHPUnit/Core/Period/YearTest.php deleted file mode 100644 index ef28d619d6..0000000000 --- a/tests/PHPUnit/Core/Period/YearTest.php +++ /dev/null @@ -1,100 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Date; -use Piwik\Period\Year; -use Piwik\Translate; - -/** - * Testing Period_Year - */ -class Period_YearTest extends PHPUnit_Framework_TestCase -{ - /** - * test normal case - * @group Core - */ - public function testYearNormalcase() - { - $correct = array( - '2024-01-01', - '2024-02-01', - '2024-03-01', - '2024-04-01', - '2024-05-01', - '2024-06-01', - '2024-07-01', - '2024-08-01', - '2024-09-01', - '2024-10-01', - '2024-11-01', - '2024-12-01',); - - $year = new Year(Date::factory('2024-10-09')); - $this->assertEquals(12, $year->getNumberOfSubperiods()); - $this->assertEquals($correct, $year->toString()); - } - - /** - * test past - * @group Core - */ - public function testYearPastAndWrongdate() - { - $correct = array( - '2000-01-01', - '2000-02-01', - '2000-03-01', - '2000-04-01', - '2000-05-01', - '2000-06-01', - '2000-07-01', - '2000-08-01', - '2000-09-01', - '2000-10-01', - '2000-11-01', - '2000-12-01', - ); - - $year = new Year(Date::factory('2000-02-15')); - $this->assertEquals(12, $year->getNumberOfSubperiods()); - $this->assertEquals($correct, $year->toString()); - } - - /** - * @group Core - */ - public function testGetLocalizedShortString() - { - Translate::loadEnglishTranslation(); - $year = new Year(Date::factory('2024-10-09')); - $shouldBe = '2024'; - $this->assertEquals($shouldBe, $year->getLocalizedShortString()); - } - - /** - * @group Core - */ - public function testGetLocalizedLongString() - { - Translate::loadEnglishTranslation(); - $year = new Year(Date::factory('2024-10-09')); - $shouldBe = '2024'; - $this->assertEquals($shouldBe, $year->getLocalizedLongString()); - } - - /** - * @group Core - */ - public function testGetPrettyString() - { - Translate::loadEnglishTranslation(); - $year = new Year(Date::factory('2024-10-09')); - $shouldBe = '2024'; - $this->assertEquals($shouldBe, $year->getPrettyString()); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/PeriodTest.php b/tests/PHPUnit/Core/PeriodTest.php deleted file mode 100644 index 8888c4c763..0000000000 --- a/tests/PHPUnit/Core/PeriodTest.php +++ /dev/null @@ -1,103 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Date; -use Piwik\Period\Day; -use Piwik\Period; -use Piwik\Period\Month; -use Piwik\Period\Week; -use Piwik\Period\Year; - -class PeriodTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testGetId() - { - $period = new Day(Date::today()); - $this->assertNotEquals(0, $period->getId()); - $period = new Week(Date::today()); - $this->assertNotEquals(0, $period->getId()); - $period = new Month(Date::today()); - $this->assertNotEquals(0, $period->getId()); - $period = new Year(Date::today()); - $this->assertNotEquals(0, $period->getId()); - } - - /** - * @group Core - */ - public function testGetLabel() - { - $period = new Day(Date::today()); - $label = $period->getLabel(); - $this->assertInternalType('string', $label); - $this->assertNotEmpty($label); - $period = new Week(Date::today()); - $label = $period->getLabel(); - $this->assertInternalType('string', $label); - $this->assertNotEmpty($label); - $period = new Month(Date::today()); - $label = $period->getLabel(); - $this->assertInternalType('string', $label); - $this->assertNotEmpty($label); - $period = new Year(Date::today()); - $label = $period->getLabel(); - $this->assertInternalType('string', $label); - $this->assertNotEmpty($label); - } - - /** - * @group Core - */ - public function testFactoryDay() - { - $period = Period\Factory::build('day', Date::today()); - $this->assertInstanceOf('\Piwik\Period\Day', $period); - } - - /** - * @group Core - */ - public function testFactoryMonth() - { - $period = Period\Factory::build('month', Date::today()); - $this->assertInstanceOf('\Piwik\Period\Month', $period); - } - - /** - * @group Core - */ - public function testFactoryWeek() - { - $period = Period\Factory::build('week', Date::today()); - $this->assertInstanceOf('\Piwik\Period\Week', $period); - } - - /** - * @group Core - */ - public function testFactoryYear() - { - $period = Period\Factory::build('year', Date::today()); - $this->assertInstanceOf('\Piwik\Period\Year', $period); - } - - /** - * @group Core - */ - public function testFactoryInvalid() - { - try { - Period\Factory::build('inValid', Date::today()); - } catch (Exception $e) { - return; - } - $this->fail('Expected Exception not raised'); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/Plugin/ComponentFactoryTest.php b/tests/PHPUnit/Core/Plugin/ComponentFactoryTest.php deleted file mode 100644 index b7b0f30fc3..0000000000 --- a/tests/PHPUnit/Core/Plugin/ComponentFactoryTest.php +++ /dev/null @@ -1,143 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -namespace Piwik\Tests\Core\Plugin; - -use PHPUnit_Framework_TestCase; -use Piwik\Config; -use Piwik\Plugin\ComponentFactory; -use Piwik\Plugin\Manager as PluginManager; -use Piwik\Plugin\Report; - -/** - * @group Core - */ -class ComponentFactoryTest extends PHPUnit_Framework_TestCase -{ - const REPORT_CLASS_NAME = 'Piwik\\Plugin\\Report'; - - public function setUp() - { - parent::setUp(); - - Config::getInstance()->setTestEnvironment(); - Config::getInstance()->Plugins['Plugins'] = array(); - - $this->unloadAllPlugins(); - } - - public function test_factory_shouldNotFindAComponentIfComponentExistsButPluginIsNotLoaded() - { - $this->unloadAllPlugins(); - - $report = ComponentFactory::factory('ExampleReport', 'GetExampleReport', self::REPORT_CLASS_NAME); - - $this->assertNull($report); - } - - public function test_factory_shouldFindAComponent_ThatExists() - { - $this->loadExampleReportPlugin(); - - $module = 'ExampleReport'; - $action = 'GetExampleReport'; - - $report = ComponentFactory::factory($module, $action, self::REPORT_CLASS_NAME); - - $this->assertInstanceOf('Piwik\Plugins\ExampleReport\Reports\GetExampleReport', $report); - } - - public function test_factory_shouldNotFindAComponent_IfPluginIsActivatedButComponentNotExists() - { - $this->loadExampleReportPlugin(); - - $module = 'ExampleReport'; - $action = 'NotExistingReport'; - - $report = ComponentFactory::factory($module, $action, self::REPORT_CLASS_NAME); - - $this->assertNull($report); - } - - public function test_factory_shouldNotFindAComponent_IfPluginIsLoadedButNotActivated() - { - PluginManager::getInstance()->loadPlugin('ExampleReport'); - - $module = 'ExampleReport'; - $action = 'GetExampleReport'; - - $report = ComponentFactory::factory($module, $action, self::REPORT_CLASS_NAME); - - $this->assertNull($report); - } - - public function test_getComponentIf_shouldNotFindAComponentIfComponentExistsButPluginIsNotLoaded() - { - $this->unloadAllPlugins(); - - $report = ComponentFactory::getComponentIf(self::REPORT_CLASS_NAME, 'ExampleReport', function (Report $report) { - return $report->getAction() == 'getExampleReport'; - }); - - $this->assertNull($report); - } - - public function test_getComponentIf_shouldFindAComponent_ThatExists() - { - $this->loadExampleReportPlugin(); - - $report = ComponentFactory::getComponentIf(self::REPORT_CLASS_NAME, 'ExampleReport', function (Report $report) { - return $report->getAction() == 'getExampleReport'; - }); - - $this->assertInstanceOf('Piwik\Plugins\ExampleReport\Reports\GetExampleReport', $report); - } - - public function test_getComponentIf_shouldNotFindAComponent_IfPluginIsActivatedButComponentNotExists() - { - $this->loadExampleReportPlugin(); - - $report = ComponentFactory::getComponentIf(self::REPORT_CLASS_NAME, 'ExampleReport', function (Report $report) { - return false; - }); - - $this->assertNull($report); - } - - public function test_getComponentIf_shouldNotFindAComponent_IfPluginIsLoadedButNotActivated() - { - PluginManager::getInstance()->loadPlugin('ExampleReport'); - - $report = ComponentFactory::getComponentIf(self::REPORT_CLASS_NAME, 'ExampleReport', function (Report $report) { - return $report->getAction() == 'getExampleReport'; - }); - - $this->assertNull($report); - } - - public function test_getComponentIf_shouldSearchThroughAllPlugins_IfNoPluginNameIsSupplied() - { - PluginManager::getInstance()->loadPlugins(array('ExampleReport', 'Referrers')); - - $reports = array(); - ComponentFactory::getComponentIf(self::REPORT_CLASS_NAME, null, function (Report $report) use (&$reports) { - $reports[] = $report; - }); - - $this->assertGreaterThan(1, count($reports)); - } - - private function unloadAllPlugins() - { - PluginManager::getInstance()->loadPlugins(array()); - } - - private function loadExampleReportPlugin() - { - PluginManager::getInstance()->loadPlugins(array('ExampleReport')); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/Plugin/Dimension/ActionDimensionTest.php b/tests/PHPUnit/Core/Plugin/Dimension/ActionDimensionTest.php deleted file mode 100644 index 5ea77cca84..0000000000 --- a/tests/PHPUnit/Core/Plugin/Dimension/ActionDimensionTest.php +++ /dev/null @@ -1,161 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -namespace Piwik\Plugins\Test; -// there is a test that requires the class to be defined in a plugin - -use Piwik\Plugin\Dimension\ActionDimension; -use Piwik\Plugin\Segment; -use Piwik\Plugin\Manager; - -class FakeActionDimension extends ActionDimension -{ - protected $columnName = 'fake_action_dimension_column'; - protected $columnType = 'INTEGER (10) DEFAULT 0'; - - public function set($param, $value) - { - $this->$param = $value; - } - - protected function configureSegments() - { - $segment = new Segment(); - $segment->setSegment('exitPageUrl'); - $segment->setName('Actions_ColumnExitPageURL'); - $segment->setCategory('General_Visit'); - $this->addSegment($segment); - - // custom type and sqlSegment - $segment = new Segment(); - $segment->setSegment('exitPageUrl'); - $segment->setSqlSegment('customValue'); - $segment->setType(Segment::TYPE_METRIC); - $segment->setName('Actions_ColumnExitPageURL'); - $segment->setCategory('General_Visit'); - $this->addSegment($segment); - } -} - -/** - * @group Core - */ -class Plugin_ActionDimensionTest extends \PHPUnit_Framework_TestCase -{ - /** - * @var FakeActionDimension - */ - private $dimension; - - public function setUp() - { - Manager::getInstance()->unloadPlugins(); - Manager::getInstance()->doNotLoadAlwaysActivatedPlugins(); - - $this->dimension = new FakeActionDimension(); - } - - public function tearDown() - { - Manager::unsetInstance(); - parent::tearDown(); - } - - public function test_install_shouldNotReturnAnything_IfColumnTypeNotSpecified() - { - $this->dimension->set('columnType', ''); - $this->assertEquals(array(), $this->dimension->install()); - } - - public function test_install_shouldNotReturnAnything_IfColumnNameNotSpecified() - { - $this->dimension->set('columnName', ''); - $this->assertEquals(array(), $this->dimension->install()); - } - - public function test_install_shouldAlwaysInstallLogAction_IfColumnNameAndTypeGiven() - { - $expected = array( - 'log_link_visit_action' => array( - "ADD COLUMN `fake_action_dimension_column` INTEGER (10) DEFAULT 0" - ) - ); - - $this->assertEquals($expected, $this->dimension->install()); - } - - public function test_update_shouldAlwaysUpdateLogVisit_IfColumnNameAndTypeGiven() - { - $expected = array( - 'log_link_visit_action' => array( - "MODIFY COLUMN `fake_action_dimension_column` INTEGER (10) DEFAULT 0" - ) - ); - - $this->assertEquals($expected, $this->dimension->update(array())); - } - - public function test_getVersion_shouldUseColumnTypeAsVersion() - { - $this->assertEquals('INTEGER (10) DEFAULT 0', $this->dimension->getVersion()); - } - - public function test_getSegment_ShouldReturnConfiguredSegments() - { - $segments = $this->dimension->getSegments(); - - $this->assertCount(2, $segments); - $this->assertInstanceOf('\Piwik\Plugin\Segment', $segments[0]); - $this->assertInstanceOf('\Piwik\Plugin\Segment', $segments[1]); - } - - public function test_addSegment_ShouldPrefilSomeSegmentValuesIfNotDefinedYet() - { - $segments = $this->dimension->getSegments(); - - $this->assertEquals('log_link_visit_action.fake_action_dimension_column', $segments[0]->getSqlSegment()); - $this->assertEquals(Segment::TYPE_DIMENSION, $segments[0]->getType()); - } - - public function test_addSegment_ShouldNotOverwritePreAssignedValues() - { - $segments = $this->dimension->getSegments(); - - $this->assertEquals('customValue', $segments[1]->getSqlSegment()); - $this->assertEquals(Segment::TYPE_METRIC, $segments[1]->getType()); - } - - public function test_getDimensions_shouldOnlyLoadAllActionDimensionsFromACertainPlugin() - { - Manager::getInstance()->loadPlugins(array('Actions')); - $plugin = Manager::getInstance()->loadPlugin('Actions'); - - $dimensions = ActionDimension::getDimensions($plugin); - - $this->assertGreaterThan(5, count($dimensions)); - - foreach ($dimensions as $dimension) { - $this->assertInstanceOf('\Piwik\Plugin\Dimension\ActionDimension', $dimension); - $this->assertStringStartsWith('Piwik\Plugins\Actions\Columns', get_class($dimension)); - } - } - - public function test_getAllDimensions_shouldLoadAllDimensionsButOnlyIfLoadedPlugins() - { - Manager::getInstance()->loadPlugins(array('Actions', 'Events')); - - $dimensions = ActionDimension::getAllDimensions(); - - $this->assertGreaterThan(8, count($dimensions)); - - foreach ($dimensions as $dimension) { - $this->assertInstanceOf('\Piwik\Plugin\Dimension\ActionDimension', $dimension); - $this->assertRegExp('/Piwik.Plugins.(Actions|Events).Columns/', get_class($dimension)); - } - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/Plugin/Dimension/ConversionDimensionTest.php b/tests/PHPUnit/Core/Plugin/Dimension/ConversionDimensionTest.php deleted file mode 100644 index 38b2e4856f..0000000000 --- a/tests/PHPUnit/Core/Plugin/Dimension/ConversionDimensionTest.php +++ /dev/null @@ -1,161 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -namespace Piwik\Plugins\Test; -// there is a test that requires the class to be defined in a plugin - -use Piwik\Plugin\Dimension\ConversionDimension; -use Piwik\Plugin\Segment; -use Piwik\Plugin\Manager; - -class FakeConversionDimension extends ConversionDimension -{ - protected $columnName = 'fake_conversion_dimension_column'; - protected $columnType = 'INTEGER (10) DEFAULT 0'; - - public function set($param, $value) - { - $this->$param = $value; - } - - protected function configureSegments() - { - $segment = new Segment(); - $segment->setSegment('exitPageUrl'); - $segment->setName('Actions_ColumnExitPageURL'); - $segment->setCategory('General_Visit'); - $this->addSegment($segment); - - // custom type and sqlSegment - $segment = new Segment(); - $segment->setSegment('exitPageUrl'); - $segment->setSqlSegment('customValue'); - $segment->setType(Segment::TYPE_METRIC); - $segment->setName('Actions_ColumnExitPageURL'); - $segment->setCategory('General_Visit'); - $this->addSegment($segment); - } -} - -/** - * @group Core - */ -class Plugin_ConversionDimensionTest extends \PHPUnit_Framework_TestCase -{ - /** - * @var FakeConversionDimension - */ - private $dimension; - - public function setUp() - { - Manager::getInstance()->unloadPlugins(); - Manager::getInstance()->doNotLoadAlwaysActivatedPlugins(); - - $this->dimension = new FakeConversionDimension(); - } - - public function tearDown() - { - Manager::unsetInstance(); - parent::tearDown(); - } - - public function test_install_shouldNotReturnAnything_IfColumnTypeNotSpecified() - { - $this->dimension->set('columnType', ''); - $this->assertEquals(array(), $this->dimension->install()); - } - - public function test_install_shouldNotReturnAnything_IfColumnNameNotSpecified() - { - $this->dimension->set('columnName', ''); - $this->assertEquals(array(), $this->dimension->install()); - } - - public function test_install_shouldAlwaysInstallLogAction_IfColumnNameAndTypeGiven() - { - $expected = array( - 'log_conversion' => array( - "ADD COLUMN `fake_conversion_dimension_column` INTEGER (10) DEFAULT 0" - ) - ); - - $this->assertEquals($expected, $this->dimension->install()); - } - - public function test_update_shouldAlwaysUpdateLogVisit_IfColumnNameAndTypeGiven() - { - $expected = array( - 'log_conversion' => array( - "MODIFY COLUMN `fake_conversion_dimension_column` INTEGER (10) DEFAULT 0" - ) - ); - - $this->assertEquals($expected, $this->dimension->update(array())); - } - - public function test_getVersion_shouldUseColumnTypeAsVersion() - { - $this->assertEquals('INTEGER (10) DEFAULT 0', $this->dimension->getVersion()); - } - - public function test_getSegment_ShouldReturnConfiguredSegments() - { - $segments = $this->dimension->getSegments(); - - $this->assertCount(2, $segments); - $this->assertInstanceOf('\Piwik\Plugin\Segment', $segments[0]); - $this->assertInstanceOf('\Piwik\Plugin\Segment', $segments[1]); - } - - public function test_addSegment_ShouldPrefilSomeSegmentValuesIfNotDefinedYet() - { - $segments = $this->dimension->getSegments(); - - $this->assertEquals('log_conversion.fake_conversion_dimension_column', $segments[0]->getSqlSegment()); - $this->assertEquals(Segment::TYPE_DIMENSION, $segments[0]->getType()); - } - - public function test_addSegment_ShouldNotOverwritePreAssignedValues() - { - $segments = $this->dimension->getSegments(); - - $this->assertEquals('customValue', $segments[1]->getSqlSegment()); - $this->assertEquals(Segment::TYPE_METRIC, $segments[1]->getType()); - } - - public function test_getDimensions_shouldOnlyLoadAllConversionDimensionsFromACertainPlugin() - { - Manager::getInstance()->loadPlugins(array('ExampleTracker')); - $plugin = Manager::getInstance()->loadPlugin('ExampleTracker'); - - $dimensions = ConversionDimension::getDimensions($plugin); - - $this->assertGreaterThanOrEqual(1, count($dimensions)); - - foreach ($dimensions as $dimension) { - $this->assertInstanceOf('\Piwik\Plugin\Dimension\ConversionDimension', $dimension); - $this->assertStringStartsWith('Piwik\Plugins\ExampleTracker\Columns', get_class($dimension)); - } - } - - public function test_getAllDimensions_shouldLoadAllDimensionsButOnlyIfLoadedPlugins() - { - Manager::getInstance()->loadPlugins(array('Goals', 'ExampleTracker')); - - $dimensions = ConversionDimension::getAllDimensions(); - - $this->assertGreaterThan(5, count($dimensions)); - - foreach ($dimensions as $dimension) { - $this->assertInstanceOf('\Piwik\Plugin\Dimension\ConversionDimension', $dimension); - $this->assertRegExp('/Piwik.Plugins.(ExampleTracker|Goals).Columns/', get_class($dimension)); - } - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/Plugin/Dimension/VisitDimensionTest.php b/tests/PHPUnit/Core/Plugin/Dimension/VisitDimensionTest.php deleted file mode 100644 index e34806371e..0000000000 --- a/tests/PHPUnit/Core/Plugin/Dimension/VisitDimensionTest.php +++ /dev/null @@ -1,261 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -namespace Piwik\Plugins\Test; -// there is a test that requires the class to be defined in a plugin - -use Piwik\Plugin\Dimension\VisitDimension; -use Piwik\Plugin\Segment; -use Piwik\Plugin\Manager; -use Piwik\Tracker\Request; -use Piwik\Tracker\Visitor; - -class FakeVisitDimension extends VisitDimension -{ - protected $columnName = 'fake_visit_dimension_column'; - protected $columnType = 'INTEGER (10) DEFAULT 0'; - public $requiredFields = array(); - - public function set($param, $value) - { - $this->$param = $value; - } - - public function getRequiredVisitFields() - { - return $this->requiredFields; - } -} - -class FakeConversionVisitDimension extends FakeVisitDimension -{ - public function onAnyGoalConversion(Request $request, Visitor $visitor, $action) - { - return false; - } - - protected function configureSegments() - { - $segment = new Segment(); - $segment->setSegment('exitPageUrl'); - $segment->setName('Actions_ColumnExitPageURL'); - $segment->setCategory('General_Visit'); - $this->addSegment($segment); - - // custom type and sqlSegment - $segment = new Segment(); - $segment->setSegment('exitPageUrl'); - $segment->setSqlSegment('customValue'); - $segment->setType(Segment::TYPE_METRIC); - $segment->setName('Actions_ColumnExitPageURL'); - $segment->setCategory('General_Visit'); - $this->addSegment($segment); - } -} - -/** - * @group Core - */ -class Plugin_VisitDimensionTest extends \PHPUnit_Framework_TestCase -{ - /** - * @var FakeVisitDimension - */ - private $dimension; - - /** - * @var FakeConversionVisitDimension - */ - private $conversionDimension; - - public function setUp() - { - Manager::getInstance()->unloadPlugins(); - Manager::getInstance()->doNotLoadAlwaysActivatedPlugins(); - - $this->dimension = new FakeVisitDimension(); - $this->conversionDimension = new FakeConversionVisitDimension(); - } - - public function tearDown() - { - Manager::unsetInstance(); - parent::tearDown(); - } - - public function test_install_shouldNotReturnAnything_IfColumnTypeNotSpecified() - { - $this->dimension->set('columnType', ''); - $this->assertEquals(array(), $this->dimension->install()); - } - - public function test_install_shouldNotReturnAnything_IfColumnNameNotSpecified() - { - $this->dimension->set('columnName', ''); - $this->assertEquals(array(), $this->dimension->install()); - } - - public function test_install_shouldAlwaysInstallLogVisit_IfColumnNameAndTypeGiven() - { - $expected = array( - 'log_visit' => array( - "ADD COLUMN `fake_visit_dimension_column` INTEGER (10) DEFAULT 0" - ) - ); - - $this->assertEquals($expected, $this->dimension->install()); - } - - public function test_install_shouldInstallLogVisitAndConversion_IfConversionMethodIsImplemented() - { - $expected = array( - 'log_visit' => array( - "ADD COLUMN `fake_visit_dimension_column` INTEGER (10) DEFAULT 0" - ), - 'log_conversion' => array( - "ADD COLUMN `fake_visit_dimension_column` INTEGER (10) DEFAULT 0" - ) - ); - - $this->assertEquals($expected, $this->conversionDimension->install()); - } - - public function test_update_shouldAlwaysUpdateLogVisit_IfColumnNameAndTypeGiven() - { - $expected = array( - 'log_visit' => array( - "MODIFY COLUMN `fake_visit_dimension_column` INTEGER (10) DEFAULT 0" - ) - ); - - $this->assertEquals($expected, $this->dimension->update(array())); - } - - public function test_update_shouldUpdateLogVisitAndAddConversion_IfConversionMethodIsImplementedButNotInstalledYet() - { - $expected = array( - 'log_visit' => array( - "MODIFY COLUMN `fake_visit_dimension_column` INTEGER (10) DEFAULT 0" - ), - 'log_conversion' => array( - "ADD COLUMN `fake_visit_dimension_column` INTEGER (10) DEFAULT 0" - ) - ); - - $this->assertEquals($expected, $this->conversionDimension->update(array())); - } - - public function test_update_shouldUpdateLogVisitAndConversion_IfConversionMethodIsImplementedAndInstalled() - { - $expected = array( - 'log_visit' => array( - "MODIFY COLUMN `fake_visit_dimension_column` INTEGER (10) DEFAULT 0" - ), - 'log_conversion' => array( - "MODIFY COLUMN `fake_visit_dimension_column` INTEGER (10) DEFAULT 0" - ) - ); - - $this->assertEquals($expected, $this->conversionDimension->update(array('fake_visit_dimension_column' => array()))); - } - - public function test_getVersion_shouldUseColumnTypeAsVersion() - { - $this->assertEquals('INTEGER (10) DEFAULT 0', $this->dimension->getVersion()); - } - - public function test_getVersion_shouldIncludeConversionMethodIntoVersionNumber_ToMakeSureUpdateMethodWillBeTriggeredWhenPluginAddedConversionMethodInNewVersion() - { - $this->assertEquals('INTEGER (10) DEFAULT 01', $this->conversionDimension->getVersion()); - } - - public function test_getSegment_ShouldReturnNoSegments_IfNoneConfigured() - { - $this->assertEquals(array(), $this->dimension->getSegments()); - } - - public function test_getSegment_ShouldReturnConfiguredSegments() - { - $segments = $this->conversionDimension->getSegments(); - - $this->assertCount(2, $segments); - $this->assertInstanceOf('\Piwik\Plugin\Segment', $segments[0]); - $this->assertInstanceOf('\Piwik\Plugin\Segment', $segments[1]); - } - - public function test_addSegment_ShouldPrefilSomeSegmentValuesIfNotDefinedYet() - { - $segments = $this->conversionDimension->getSegments(); - - $this->assertEquals('log_visit.fake_visit_dimension_column', $segments[0]->getSqlSegment()); - $this->assertEquals(Segment::TYPE_DIMENSION, $segments[0]->getType()); - } - - public function test_addSegment_ShouldNotOverwritePreAssignedValues() - { - $segments = $this->conversionDimension->getSegments(); - - $this->assertEquals('customValue', $segments[1]->getSqlSegment()); - $this->assertEquals(Segment::TYPE_METRIC, $segments[1]->getType()); - } - - public function test_sortByRequiredFields_ShouldResolveDependencies() - { - $dimension1 = new FakeVisitDimension(); - $dimension1->set('columnName', 'column1'); - $dimension1->requiredFields = array('column2'); - - $dimension2 = new FakeVisitDimension(); - $dimension2->set('columnName', 'column2'); - $dimension2->requiredFields = array('column3', 'column4'); - - $dimension3 = new FakeVisitDimension(); - $dimension3->set('columnName', 'column3'); - $dimension3->requiredFields = array(); - - $dimension4 = new FakeVisitDimension(); - $dimension4->set('columnName', 'column4'); - $dimension4->requiredFields = array('column3'); - - $instances = array($dimension1, $dimension2, $dimension3, $dimension4); - - usort($instances, array('\Piwik\Plugin\Dimension\VisitDimension', 'sortByRequiredFields')); - - $this->assertSame(array($dimension3, $dimension4, $dimension2, $dimension1), $instances); - } - - public function test_getDimensions_shouldOnlyLoadAllVisitDimensionsFromACertainPlugin() - { - Manager::getInstance()->loadPlugins(array('Actions')); - $plugin = Manager::getInstance()->loadPlugin('Actions'); - - $dimensions = VisitDimension::getDimensions($plugin); - - $this->assertGreaterThan(5, count($dimensions)); - - foreach ($dimensions as $dimension) { - $this->assertInstanceOf('\Piwik\Plugin\Dimension\VisitDimension', $dimension); - $this->assertStringStartsWith('Piwik\Plugins\Actions\Columns', get_class($dimension)); - } - } - - - public function test_getAllDimensions_shouldLoadAllDimensionsButOnlyIfLoadedPlugins() - { - Manager::getInstance()->loadPlugins(array('Actions', 'DevicesDetection')); - - $dimensions = VisitDimension::getAllDimensions(); - - $this->assertGreaterThan(10, count($dimensions)); - - foreach ($dimensions as $dimension) { - $this->assertInstanceOf('\Piwik\Plugin\Dimension\VisitDimension', $dimension); - $this->assertRegExp('/Piwik.Plugins.(DevicesDetection|Actions).Columns/', get_class($dimension)); - } - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/RankingQueryTest.php b/tests/PHPUnit/Core/RankingQueryTest.php deleted file mode 100644 index 7941c25d35..0000000000 --- a/tests/PHPUnit/Core/RankingQueryTest.php +++ /dev/null @@ -1,150 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -use Piwik\RankingQuery; - -class RankingQueryTest extends PHPUnit_Framework_TestCase -{ - - /** - * @group Core - */ - public function testBasic() - { - $query = new RankingQuery(); - $query->addLabelColumn('label'); - $query->addColumn('column'); - $query->addColumn('columnSum', 'sum'); - $query->setLimit(10); - - $innerQuery = "SELECT label, column, columnSum FROM myTable"; - - $expected = " - SELECT - CASE - WHEN counter = 11 THEN 'Others' - ELSE `label` - END AS `label`, - `column`, - sum(`columnSum`) AS `columnSum` - FROM ( - SELECT - `label`, - CASE - WHEN @counter = 11 THEN 11 - ELSE @counter:=@counter+1 - END AS counter, - `column`, - `columnSum` - FROM - ( SELECT @counter:=0 ) initCounter, - ( SELECT label, column, columnSum FROM myTable ) actualQuery - ) AS withCounter - GROUP BY counter - "; - - $this->checkQuery($query, $innerQuery, $expected); - } - - /** - * @group Core - */ - public function testExcludeRows() - { - $query = new RankingQuery(20); - $query->addLabelColumn('label'); - $query->setColumnToMarkExcludedRows('exclude_marker'); - - $innerQuery = "SELECT label, 1 AS exclude_marker FROM myTable"; - - $expected = " - SELECT - CASE - WHEN counter = 21 THEN 'Others' - ELSE `label` - END AS `label`, - `exclude_marker` - FROM ( - SELECT - `label`, - CASE - WHEN exclude_marker != 0 THEN -1 * exclude_marker - WHEN @counter = 21 THEN 21 - ELSE @counter:=@counter+1 - END AS counter, - `exclude_marker` - FROM - ( SELECT @counter:=0 ) initCounter, - ( SELECT label, 1 AS exclude_marker FROM myTable ) actualQuery - ) AS withCounter - GROUP BY counter - "; - - $this->checkQuery($query, $innerQuery, $expected); - } - - /** - * @group Core - */ - public function testPartitionResult() - { - $query = new RankingQuery(1000); - $query->addLabelColumn('label'); - $query->partitionResultIntoMultipleGroups('partition', array(1, 2, 3)); - - $innerQuery = "SELECT label, partition FROM myTable"; - - $expected = " - SELECT - CASE - WHEN counter = 1001 THEN 'Others' - ELSE `label` - END AS `label`, - `partition` - FROM ( - SELECT - `label`, - CASE - WHEN `partition` = 1 AND @counter1 = 1001 THEN 1001 - WHEN `partition` = 1 THEN @counter1:=@counter1+1 - WHEN `partition` = 2 AND @counter2 = 1001 THEN 1001 - WHEN `partition` = 2 THEN @counter2:=@counter2+1 - WHEN `partition` = 3 AND @counter3 = 1001 THEN 1001 - WHEN `partition` = 3 THEN @counter3:=@counter3+1 - ELSE 0 - END AS counter, - `partition` - FROM - ( SELECT @counter1:=0 ) initCounter1, - ( SELECT @counter2:=0 ) initCounter2, - ( SELECT @counter3:=0 ) initCounter3, - ( SELECT label, partition FROM myTable ) actualQuery - ) AS withCounter - GROUP BY counter, `partition` - "; - - $this->checkQuery($query, $innerQuery, $expected); - } - - /** - * @param RankingQuery $rankingQuery - * @param string $innerQuerySql - * @param string $expected - */ - private function checkQuery($rankingQuery, $innerQuerySql, $expected) - { - $query = $rankingQuery->generateQuery($innerQuerySql); - - $queryNoWhitespace = preg_replace("/\s+/", "", $query); - $expectedNoWhitespace = preg_replace("/\s+/", "", $expected); - - $message = 'Unexpected query: ' . $query; - $this->assertEquals($queryNoWhitespace, $expectedNoWhitespace, $message); - } - -} diff --git a/tests/PHPUnit/Core/RegistryTest.php b/tests/PHPUnit/Core/RegistryTest.php deleted file mode 100644 index c6c2aff894..0000000000 --- a/tests/PHPUnit/Core/RegistryTest.php +++ /dev/null @@ -1,37 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Registry; - -class RegistryTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testGetInstance() - { - $instance = Registry::getInstance(); - - $this->assertInstanceOf('\Piwik\Registry', $instance); - - // check singleton - $this->assertSame(Registry::getInstance(), $instance); - } - - /** - * @group Core - */ - public function testFuncionality() - { - $value = 'newValue'; - $key = 'newKey'; - - Registry::set($key, $value); - $this->assertEquals($value, Registry::get($key)); - $this->assertTrue(Registry::isRegistered($key)); - } -} diff --git a/tests/PHPUnit/Core/ReleaseCheckListTest.php b/tests/PHPUnit/Core/ReleaseCheckListTest.php deleted file mode 100644 index ba70ff9410..0000000000 --- a/tests/PHPUnit/Core/ReleaseCheckListTest.php +++ /dev/null @@ -1,391 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Filesystem; -use Piwik\Plugin\Manager; -use Piwik\SettingsServer; - -/** - * @group ReleaseCheckListTest - */ -class ReleaseCheckListTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - $this->globalConfig = _parse_ini_file(PIWIK_PATH_TEST_TO_ROOT . '/config/global.ini.php', true); - - parent::setUp(); - } - - /** - * @group Core - */ - public function test_icoFilesIconsShouldBeInPngFormat() - { - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/plugins', '*.ico'); - $this->checkFilesAreInPngFormat($files); - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/core', '*.ico'); - $this->checkFilesAreInPngFormat($files); - } - - /** - * @group Core - */ - public function test_pngFilesIconsShouldBeInPngFormat() - { - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/plugins', '*.png'); - $this->checkFilesAreInPngFormat($files); - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/core', '*.png'); - $this->checkFilesAreInPngFormat($files); - } - - /** - * @group Core - */ - public function test_gifFilesIconsShouldBeInGifFormat() - { - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/plugins', '*.gif'); - $this->checkFilesAreInGifFormat($files); - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/core', '*.gif'); - $this->checkFilesAreInGifFormat($files); - } - - /** - * @group Core - */ - public function test_jpgImagesShouldBeInJpgFormat() - { - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/plugins', '*.jpg'); - $this->checkFilesAreInJpgFormat($files); - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/core', '*.jpg'); - $this->checkFilesAreInJpgFormat($files); - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/plugins', '*.jpeg'); - $this->checkFilesAreInJpgFormat($files); - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/core', '*.jpeg'); - $this->checkFilesAreInJpgFormat($files); - } - - /** - * @group Core - */ - public function testCheckThatConfigurationValuesAreProductionValues() - { - $this->_checkEqual(array('Debug' => 'always_archive_data_day'), '0'); - $this->_checkEqual(array('Debug' => 'always_archive_data_period'), '0'); - $this->_checkEqual(array('Debug' => 'enable_sql_profiler'), '0'); - $this->_checkEqual(array('General' => 'time_before_today_archive_considered_outdated'), '150'); - $this->_checkEqual(array('General' => 'enable_browser_archiving_triggering'), '1'); - $this->_checkEqual(array('General' => 'default_language'), 'en'); - $this->_checkEqual(array('Tracker' => 'record_statistics'), '1'); - $this->_checkEqual(array('Tracker' => 'visit_standard_length'), '1800'); - $this->_checkEqual(array('Tracker' => 'trust_visitors_cookies'), '0'); - // logging messages are disabled - $this->_checkEqual(array('log' => 'log_level'), 'WARN'); - $this->_checkEqual(array('log' => 'log_writers'), array('screen')); - $this->_checkEqual(array('log' => 'logger_api_call'), null); - - require_once PIWIK_INCLUDE_PATH . "/core/TaskScheduler.php"; - $this->assertFalse(DEBUG_FORCE_SCHEDULED_TASKS); - - // Check the index.php has "backtrace disabled" - $content = file_get_contents(PIWIK_INCLUDE_PATH . "/index.php"); - $expected = "define('PIWIK_PRINT_ERROR_BACKTRACE', false);"; - $this->assertTrue( false !== strpos($content, $expected), 'index.php should contain: ' . $expected); - } - - private function _checkEqual($key, $valueExpected) - { - $section = key($key); - $optionName = current($key); - $value = null; - if (isset($this->globalConfig[$section][$optionName])) { - $value = $this->globalConfig[$section][$optionName]; - } - $this->assertEquals($valueExpected, $value, "$section -> $optionName was '" . var_export($value, true) . "', expected '" . var_export($valueExpected, true) . "'"); - } - - /** - * @group Core - */ - public function testTemplatesDontContainDebug() - { - $patternFailIfFound = 'dump('; - $files = Filesystem::globr(PIWIK_INCLUDE_PATH . '/plugins', '*.twig'); - foreach ($files as $file) { - if ($file == PIWIK_INCLUDE_PATH . '/plugins/CoreConsole/templates/travis.yml.twig') { - continue; - } - - $content = file_get_contents($file); - $this->assertFalse(strpos($content, $patternFailIfFound), 'found in ' . $file); - } - } - - /** - * @group Core - */ - public function testCheckThatGivenPluginsAreDisabledByDefault() - { - $pluginsShouldBeDisabled = array( - 'DBStats' - ); - foreach ($pluginsShouldBeDisabled as $pluginName) { - if (in_array($pluginName, $this->globalConfig['Plugins']['Plugins'])) { - throw new Exception("Plugin $pluginName is enabled by default but shouldn't."); - } - } - - } - - /** - * test that the profiler is disabled (mandatory on a production server) - * @group Core - */ - public function testProfilingDisabledInProduction() - { - require_once 'Tracker/Db.php'; - $this->assertTrue(\Piwik\Tracker\Db::isProfilingEnabled() === false, 'SQL profiler should be disabled in production! See Db::$profiling'); - } - - /** - * @group Core - */ - public function testPiwikTrackerDebugIsOff() - { - $this->assertTrue(!isset($GLOBALS['PIWIK_TRACKER_DEBUG'])); - $this->assertEquals(0, $this->globalConfig['Tracker']['debug']); - } - - /** - * This tests that all PHP files start with <?php - * This would help detect errors such as a php file starting with spaces - * @group Core - */ - public function test_phpFilesStartWithRightCharacter() - { - $files = Filesystem::globr(PIWIK_INCLUDE_PATH, '*.php'); - - foreach($files as $file) { - $handle = fopen($file, "r"); - $expectedStart = "<?php"; - - $isIniFile = strpos($file, ".ini.php") !== false || strpos($file, ".ini.travis.php") !== false; - if($isIniFile) { - $expectedStart = "; <?php exit;"; - } - - $skipStartFileTest = $this->isSkipPhpFileStartWithPhpBlock($file, $isIniFile); - - if($skipStartFileTest) { - continue; - } - - $start = fgets($handle, strlen($expectedStart) + 1 ); - $this->assertEquals($start, $expectedStart, "File $file does not start with $expectedStart"); - } - } - - /** - * @group Core - */ - public function test_directoriesShouldBeChmod755() - { - $pluginsPath = realpath(PIWIK_INCLUDE_PATH . '/plugins/'); - - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pluginsPath), RecursiveIteratorIterator::SELF_FIRST); - $paths = array(); - foreach($objects as $name => $object){ - if (is_dir($name) - && strpos($name, "/.") === false) { - $paths[] = $name; - } - } - - $this->assertGreaterThan(50, count($paths), 'test at latest 50 directories, got ' . count($paths)); - - // to prevent errors with un-readable assets, - // we ensure all directories in plugins/* are added to git with CHMOD 755 - foreach($paths as $pathToTest) { - - $chmod = substr(decoct(fileperms($pathToTest)), -3); - $valid = array('777', '775', '755'); - $command = "find $pluginsPath -type d -exec chmod 755 {} +"; - $this->assertTrue(in_array($chmod, $valid), - "Some directories within plugins/ are not chmod 755 \n\nGot: $chmod for : $pathToTest \n\n". - "Run this command to set all directories to 755: \n$command\n");; - } - } - - /** - * Check that directories in plugins/ folder are specifically either enabled or disabled. - * - * This fails when a new folder is added to plugins/* and forgot to enable or mark as disabled in Manager.php. - * - * @group Core - */ - public function test_DirectoriesInPluginsFolder_areKnown() - { - $pluginsBundledWithPiwik = \Piwik\Config::getInstance()->getFromGlobalConfig('Plugins'); - $pluginsBundledWithPiwik = $pluginsBundledWithPiwik['Plugins']; - $magicPlugins = 42; - $this->assertTrue(count($pluginsBundledWithPiwik) > $magicPlugins); - - $plugins = _glob(\Piwik\Plugin\Manager::getPluginsDirectory() . '*', GLOB_ONLYDIR); - $count = 1; - foreach($plugins as $pluginPath) { - $pluginName = basename($pluginPath); - - $addedToGit = $this->isPathAddedToGit($pluginPath); - - if(!$addedToGit) { - // if not added to git, then it is not part of the release checklist. - continue; - } - $manager = \Piwik\Plugin\Manager::getInstance(); - $isGitSubmodule = $manager->isPluginOfficialAndNotBundledWithCore($pluginName); - $disabled = in_array($pluginName, $manager->getCorePluginsDisabledByDefault()) || $isGitSubmodule; - - $enabled = in_array($pluginName, $pluginsBundledWithPiwik); - - $this->assertTrue( $enabled + $disabled === 1, - "Plugin $pluginName should be either enabled (in global.ini.php) or disabled (in Piwik\\Plugin\\Manager). - It is currently (enabled=".(int)$enabled. ", disabled=" . (int)$disabled . ")" - ); - $count++; - } - $this->assertTrue($count > $magicPlugins); - } - - /** - * @group Core - */ - public function testEndOfLines() - { - foreach (Filesystem::globr(PIWIK_DOCUMENT_ROOT, '*') as $file) { - // skip files in these folders - if (strpos($file, '/.git/') !== false || - strpos($file, '/documentation/') !== false || - strpos($file, '/tests/') !== false || - strpos($file, '/lang/') !== false || - strpos($file, 'yuicompressor') !== false || - strpos($file, '/tmp/') !== false - ) { - continue; - } - - // skip files with these file extensions - if (preg_match('/\.(bmp|fdf|gif|deb|deflate|exe|gz|ico|jar|jpg|p12|pdf|png|rar|swf|vsd|z|zip|ttf|so|dat|eps|phar|pyc)$/', $file)) { - continue; - } - - if (!is_dir($file)) { - $contents = file_get_contents($file); - - // expect CRLF - if (preg_match('/\.(bat|ps1)$/', $file)) { - $contents = str_replace("\r\n", '', $contents); - $this->assertTrue(strpos($contents, "\n") === false, 'Incorrect line endings in ' . $file); - } else { - // expect native - $hasWindowsEOL = strpos($contents, "\r\n"); - - // overwrite translations files with incorrect line endings - $this->assertTrue($hasWindowsEOL === false, 'Incorrect line endings \r\n found in ' . $file); - } - } - } - } - - /** - * @group Core - */ - public function testPiwikJavaScript() - { - // check source against Snort rule 8443 - // @see https://github.com/piwik/piwik/issues/2203 - $pattern = '/\x5b\x5c{2}.*\x5c{2}[\x22\x27]/'; - $contents = file_get_contents(PIWIK_DOCUMENT_ROOT . '/js/piwik.js'); - - $this->assertTrue(preg_match($pattern, $contents) == 0); - - $contents = file_get_contents(PIWIK_DOCUMENT_ROOT . '/piwik.js'); - $this->assertTrue(preg_match($pattern, $contents) == 0); - } - - /** - * @param $files - */ - private function checkFilesAreInPngFormat($files) - { - $this->checkFilesAreInFormat($files, "png"); - } - private function checkFilesAreInJpgFormat($files) - { - $this->checkFilesAreInFormat($files, "jpeg"); - } - - private function checkFilesAreInGifFormat($files) - { - $this->checkFilesAreInFormat($files, "gif"); - } - - /** - * @param $files - * @param $format - */ - private function checkFilesAreInFormat($files, $format) - { - $errors = array(); - foreach ($files as $file) { - $function = "imagecreatefrom" . $format; - if (!function_exists($function)) { - throw new \Exception("Unexpected error: $function function does not exist!"); - } - - $handle = @$function($file); - if (empty($handle)) { - $errors[] = $file; - } - } - - if (!empty($errors)) { - $icons = var_export($errors, true); - $icons = "gimp " . implode(" ", $errors); - $this->fail("$format format failed for following icons $icons \n"); - } - } - - /** - * @param $file - * @param $isIniFile - * @return bool - */ - protected function isSkipPhpFileStartWithPhpBlock($file, $isIniFile) - { - $isIniFileInTests = strpos($file, "/tests/") !== false; - $isTestResultFile = strpos($file, "/Integration/expected") !== false - || strpos($file, "/Integration/processed") !== false - || strpos($file, "tests/resources/Updater/") !== false - || strpos($file, "Twig/Tests/") !== false - || strpos($file, "/vendor/") !== false; - $isLib = strpos($file, "lib/xhprof") !== false || strpos($file, "phpunit/phpunit") !== false; - - return ($isIniFile && $isIniFileInTests) || $isTestResultFile || $isLib; - } - - /** - * @param $pluginPath - * @return bool - */ - protected function isPathAddedToGit($pluginPath) - { - $gitOutput = shell_exec('git ls-files ' . $pluginPath . ' --error-unmatch 2>&1'); - $addedToGit = (strlen($gitOutput) > 0) && strpos($gitOutput, 'error: pathspec') === false; - return $addedToGit; - } - -} diff --git a/tests/PHPUnit/Core/ScheduledTaskTest.php b/tests/PHPUnit/Core/ScheduledTaskTest.php deleted file mode 100644 index 5a131521ff..0000000000 --- a/tests/PHPUnit/Core/ScheduledTaskTest.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\Plugins\ScheduledReports\ScheduledReports; -use Piwik\ScheduledTask; - -require_once PIWIK_INCLUDE_PATH . '/plugins/ScheduledReports/ScheduledReports.php'; - -class ScheduledTaskTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testGetClassName() - { - $scheduledTask = new ScheduledTask (new ScheduledReports(), null, null, null); - $this->assertEquals('Piwik\Plugins\ScheduledReports\ScheduledReports', $scheduledTask->getClassName()); - } - - /** - * Dataprovider for testGetTaskName - */ - public function getTaskNameTestCases() - { - return array( - array('CoreAdminHome.purgeOutdatedArchives', 'CoreAdminHome', 'purgeOutdatedArchives', null), - array('CoreAdminHome.purgeOutdatedArchives_previous30', 'CoreAdminHome', 'purgeOutdatedArchives', 'previous30'), - array('ScheduledReports.weeklySchedule', 'ScheduledReports', 'weeklySchedule', null), - array('ScheduledReports.weeklySchedule_1', 'ScheduledReports', 'weeklySchedule', 1), - ); - } - - /** - * @group Core - * - * @dataProvider getTaskNameTestCases - */ - public function testGetTaskName($expectedTaskName, $className, $methodName, $methodParameter) - { - $this->assertEquals($expectedTaskName, ScheduledTask::getTaskName($className, $methodName, $methodParameter)); - } - -} diff --git a/tests/PHPUnit/Core/ScheduledTime/DailyTest.php b/tests/PHPUnit/Core/ScheduledTime/DailyTest.php deleted file mode 100644 index 1a62019392..0000000000 --- a/tests/PHPUnit/Core/ScheduledTime/DailyTest.php +++ /dev/null @@ -1,170 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ - -/** - * @group Core - */ -class ScheduledTime_DailyTest extends PHPUnit_Framework_TestCase -{ - private static $_JANUARY_01_1971_09_00_00; - private static $_JANUARY_01_1971_09_10_00; - private static $_JANUARY_01_1971_12_10_00; - private static $_JANUARY_02_1971_00_00_00; - private static $_JANUARY_02_1971_09_00_00; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - self::$_JANUARY_01_1971_09_00_00 = mktime(9, 00, 00, 1, 1, 1971); - self::$_JANUARY_01_1971_09_10_00 = mktime(9, 10, 00, 1, 1, 1971); - self::$_JANUARY_01_1971_12_10_00 = mktime(12, 10, 00, 1, 1, 1971); - self::$_JANUARY_02_1971_00_00_00 = mktime(0, 00, 00, 1, 2, 1971); - self::$_JANUARY_02_1971_09_00_00 = mktime(9, 00, 00, 1, 2, 1971); - } - - /** - * Tests invalid call to setHour on Daily - */ - public function testSetHourScheduledTimeDailyNegative() - { - try { - $dailySchedule = \Piwik\ScheduledTime::factory('daily'); - $dailySchedule->setHour(-1); - - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Tests invalid call to setHour on Daily - */ - public function testSetHourScheduledTimeDailyOver24() - { - try { - $dailySchedule = \Piwik\ScheduledTime::factory('daily'); - $dailySchedule->setHour(25); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Tests forbidden call to setDay on Daily - */ - public function testSetDayScheduledTimeDaily() - { - try { - $dailySchedule = \Piwik\ScheduledTime::factory('daily'); - $dailySchedule->setDay(1); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Tests getRescheduledTime on Daily with unspecified hour - */ - public function testGetRescheduledTimeDailyUnspecifiedHour() - { - /* - * Test 1 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 09:10:00 UTC - * - setHour is not called, defaulting to midnight - * - * Expected : - * getRescheduledTime returns Saturday January 2 1971 00:00:00 UTC - */ - $mock = $this->getDailyMock(self::$_JANUARY_01_1971_09_10_00); - $this->assertEquals(self::$_JANUARY_02_1971_00_00_00, $mock->getRescheduledTime()); - } - - public function test_setTimezone_ShouldConvertRescheduledTime() - { - $oneHourInSeconds = 3600; - - $mock = $this->getDailyMock(self::$_JANUARY_01_1971_09_10_00); - $timeUTC = $mock->getRescheduledTime(); - $this->assertEquals(self::$_JANUARY_02_1971_00_00_00, $timeUTC); - - $mock->setTimezone('Pacific/Auckland'); - $timeAuckland = $mock->getRescheduledTime(); - $this->assertEquals(-13 * $oneHourInSeconds, $timeAuckland - $timeUTC); - - $mock->setTimezone('America/Los_Angeles'); - $timeLosAngeles = $mock->getRescheduledTime(); - $this->assertEquals(8 * $oneHourInSeconds, $timeLosAngeles - $timeUTC); - } - - /** - * Tests getRescheduledTime on Daily with specified hour - */ - public function testGetRescheduledTimeDailySpecifiedHour() - { - /* - * Test 1 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 09:00:00 UTC - * - setHour is set to 9 - * - * Expected : - * getRescheduledTime returns Saturday January 2 1971 09:00:00 UTC - */ - $mock = $this->getDailyMock(self::$_JANUARY_01_1971_09_00_00); - $mock->setHour(9); - $this->assertEquals(self::$_JANUARY_02_1971_09_00_00, $mock->getRescheduledTime()); - - /* - * Test 2 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 12:10:00 UTC - * - setHour is set to 9 - * - * Expected : - * getRescheduledTime returns Saturday January 2 1971 09:00:00 UTC - */ - - $mock = $this->getDailyMock(self::$_JANUARY_01_1971_12_10_00); - $mock->setHour(9); - $this->assertEquals(self::$_JANUARY_02_1971_09_00_00, $mock->getRescheduledTime()); - - /* - * Test 3 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 12:10:00 UTC - * - setHour is set to 0 - * - * Expected : - * getRescheduledTime returns Saturday January 2 1971 00:00:00 UTC - */ - $mock = $this->getDailyMock(self::$_JANUARY_01_1971_12_10_00); - $mock->setHour(0); - $this->assertEquals(self::$_JANUARY_02_1971_00_00_00, $mock->getRescheduledTime()); - } - - /** - * @param $currentTime - * @return \Piwik\ScheduledTime\Daily - */ - private function getDailyMock($currentTime) - { - $mock = $this->getMock('\Piwik\ScheduledTime\Daily', array('getTime')); - $mock->expects($this->any()) - ->method('getTime') - ->will($this->returnValue($currentTime)); - return $mock; - } -} diff --git a/tests/PHPUnit/Core/ScheduledTime/HourlyTest.php b/tests/PHPUnit/Core/ScheduledTime/HourlyTest.php deleted file mode 100644 index 14f4ce3c0e..0000000000 --- a/tests/PHPUnit/Core/ScheduledTime/HourlyTest.php +++ /dev/null @@ -1,90 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\ScheduledTime\Hourly; - -class ScheduledTime_HourlyTest extends PHPUnit_Framework_TestCase -{ - private static $_JANUARY_01_1971_09_00_00; - private static $_JANUARY_01_1971_09_10_00; - private static $_JANUARY_01_1971_10_00_00; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - self::$_JANUARY_01_1971_09_00_00 = mktime(9, 00, 00, 1, 1, 1971); - self::$_JANUARY_01_1971_09_10_00 = mktime(9, 10, 00, 1, 1, 1971); - self::$_JANUARY_01_1971_10_00_00 = mktime(10, 00, 00, 1, 1, 1971); - } - - /** - * Tests forbidden call to setHour on Hourly - * @group Core - */ - public function testSetHourScheduledTimeHourly() - { - try { - $hourlySchedule = new Hourly(); - $hourlySchedule->setHour(0); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Tests forbidden call to setDay on Hourly - * @group Core - */ - public function testSetDayScheduledTimeHourly() - { - try { - $hourlySchedule = new Hourly(); - $hourlySchedule->setDay(1); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Tests getRescheduledTime on Hourly - * @group Core - */ - public function testGetRescheduledTimeHourly() - { - /* - * Test 1 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 09:00:00 GMT - * - * Expected : - * getRescheduledTime returns Friday January 1 1971 10:00:00 GMT - */ - $mock = $this->getMock('\Piwik\ScheduledTime\Hourly', array('getTime')); - $mock->expects($this->any()) - ->method('getTime') - ->will($this->returnValue(self::$_JANUARY_01_1971_09_00_00)); - $this->assertEquals(self::$_JANUARY_01_1971_10_00_00, $mock->getRescheduledTime()); - - /* - * Test 2 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 09:10:00 GMT - * - * Expected : - * getRescheduledTime returns Friday January 1 1971 10:00:00 GMT - */ - $mock = $this->getMock('\Piwik\ScheduledTime\Hourly', array('getTime')); - $mock->expects($this->any()) - ->method('getTime') - ->will($this->returnValue(self::$_JANUARY_01_1971_09_10_00)); - $this->assertEquals(self::$_JANUARY_01_1971_10_00_00, $mock->getRescheduledTime()); - } -} diff --git a/tests/PHPUnit/Core/ScheduledTime/MonthlyTest.php b/tests/PHPUnit/Core/ScheduledTime/MonthlyTest.php deleted file mode 100644 index 17bde4ee6d..0000000000 --- a/tests/PHPUnit/Core/ScheduledTime/MonthlyTest.php +++ /dev/null @@ -1,288 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\ScheduledTime\Monthly; - -/** - * @group Core - */ -class ScheduledTime_MonthlyTest extends PHPUnit_Framework_TestCase -{ - public static $_JANUARY_01_1971_09_00_00; // initialized below class definition - public static $_JANUARY_02_1971_09_00_00; - public static $_JANUARY_05_1971_09_00_00; - public static $_JANUARY_15_1971_09_00_00; - public static $_FEBRUARY_01_1971_00_00_00; - public static $_FEBRUARY_02_1971_00_00_00; - public static $_FEBRUARY_03_1971_09_00_00; - public static $_FEBRUARY_21_1971_09_00_00; - public static $_FEBRUARY_28_1971_00_00_00; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - } - - /** - * Tests invalid call to setHour on Monthly - * @expectedException \Exception - */ - public function testSetHourScheduledTimeMonthlyNegative() - { - $monthlySchedule = new Monthly(); - $monthlySchedule->setHour(-1); - } - - /** - * Tests invalid call to setHour on Monthly - * @expectedException \Exception - */ - public function testSetHourScheduledTimMonthlyOver24() - { - $monthlySchedule = new Monthly(); - $monthlySchedule->setHour(25); - } - - /** - * Tests invalid call to setDay on Monthly - * @expectedException \Exception - */ - public function testSetDayScheduledTimeMonthlyDay0() - { - $monthlySchedule = new Monthly(); - $monthlySchedule->setDay(0); - } - - /** - * Tests invalid call to setDay on Monthly - * @expectedException \Exception - */ - public function testSetDayScheduledTimeMonthlyOver31() - { - $monthlySchedule = new Monthly(); - $monthlySchedule->setDay(32); - } - - /** - * Tests getRescheduledTime on Monthly with unspecified hour and unspecified day - */ - public function testGetRescheduledTimeMonthlyUnspecifiedHourUnspecifiedDay() - { - /* - * Test 1 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 09:00:00 UTC - * - setHour is not called, defaulting to midnight - * - setDay is not called, defaulting to first day of the month - * - * Expected : - * getRescheduledTime returns Monday February 1 1971 00:00:00 UTC - */ - $mock = $this->getMonthlyMock(self::$_JANUARY_01_1971_09_00_00); - $this->assertEquals(self::$_FEBRUARY_01_1971_00_00_00, $mock->getRescheduledTime()); - - /* - * Test 2 - * - * Context : - * - getRescheduledTime called Tuesday January 5 1971 09:00:00 UTC - * - setHour is not called, defaulting to midnight - * - setDay is not called, defaulting to first day of the month - * - * Expected : - * getRescheduledTime returns Monday February 1 1971 00:00:00 UTC - */ - $mock = $this->getMonthlyMock(self::$_JANUARY_05_1971_09_00_00); - $this->assertEquals(self::$_FEBRUARY_01_1971_00_00_00, $mock->getRescheduledTime()); - } - - public function test_setTimezone_ShouldConvertRescheduledTime() - { - $oneHourInSeconds = 3600; - - $mock = $this->getMonthlyMock(self::$_JANUARY_05_1971_09_00_00); - $timeUTC = $mock->getRescheduledTime(); - $this->assertEquals(self::$_FEBRUARY_01_1971_00_00_00, $timeUTC); - - $mock->setTimezone('Pacific/Auckland'); - $timeAuckland = $mock->getRescheduledTime(); - $this->assertEquals(-13 * $oneHourInSeconds, $timeAuckland - $timeUTC); - - $mock->setTimezone('America/Los_Angeles'); - $timeLosAngeles = $mock->getRescheduledTime(); - $this->assertEquals(8 * $oneHourInSeconds, $timeLosAngeles - $timeUTC); - } - - /** - * Tests getRescheduledTime on Monthly with unspecified hour and specified day - * - * _Monthly - * - * @dataProvider getSpecifiedDayData - */ - public function testGetRescheduledTimeMonthlyUnspecifiedHourSpecifiedDay($currentTime, $day, $expected) - { - $mock = $this->getMonthlyMock(self::$$currentTime); - $mock->setDay($day); - $this->assertEquals(self::$$expected, $mock->getRescheduledTime()); - } - - /** - * DataProvider for testGetRescheduledTimeMonthlyUnspecifiedHourSpecifiedDay - * @return array - */ - public function getSpecifiedDayData() - { - return array( - /* - * Test 1 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 09:00:00 UTC - * - setHour is not called, defaulting to midnight - * - setDay is set to 1 - * - * Expected : - * getRescheduledTime returns Monday February 1 1971 00:00:00 UTC - */ - array('_JANUARY_01_1971_09_00_00', 1, '_FEBRUARY_01_1971_00_00_00'), - /* - * Test 2 - * - * Context : - * - getRescheduledTime called Saturday January 2 1971 09:00:00 UTC - * - setHour is not called, defaulting to midnight - * - setDay is set to 2 - * - * Expected : - * getRescheduledTime returns Tuesday February 2 1971 00:00:00 UTC - */ - array('_JANUARY_02_1971_09_00_00', 2, '_FEBRUARY_02_1971_00_00_00'), - /* - * Test 3 - * - * Context : - * - getRescheduledTime called Friday January 15 1971 09:00:00 UTC - * - setHour is not called, defaulting to midnight - * - setDay is set to 2 - * - * Expected : - * getRescheduledTime returns Tuesday February 1 1971 00:00:00 UTC - */ - array('_JANUARY_15_1971_09_00_00', 2, '_FEBRUARY_02_1971_00_00_00'), - /* - * Test 4 - * - * Context : - * - getRescheduledTime called Friday January 15 1971 09:00:00 UTC - * - setHour is not called, defaulting to midnight - * - setDay is set to 31 - * - * Expected : - * getRescheduledTime returns Sunday February 28 1971 00:00:00 UTC - */ - array('_JANUARY_15_1971_09_00_00', 31, '_FEBRUARY_28_1971_00_00_00') - ); - } - - /** - * Returns the data used to test the setDayOfWeek method. - */ - public function getValuesToTestSetDayOfWeek() - { - return array( - array(3, 0, self::$_FEBRUARY_03_1971_09_00_00), - array(0, 2, self::$_FEBRUARY_21_1971_09_00_00), - ); - } - - /** - * Returns the data used to test the setDayOfWeekFromString method. - */ - public function getValuesToTestSetDayOfWeekByString() - { - return array( - array('first wednesday', self::$_FEBRUARY_03_1971_09_00_00), - array('ThIrD sUnDaY', self::$_FEBRUARY_21_1971_09_00_00) - ); - } - - /** - * @dataProvider getValuesToTestSetDayOfWeek - */ - public function testMonthlyDayOfWeek($day, $week, $expectedTime) - { - $mock = $this->getMonthlyMock(self::$_JANUARY_15_1971_09_00_00); - $mock->setDayOfWeek($day, $week); - $this->assertEquals($expectedTime, $mock->getRescheduledTime()); - } - - /** - * @dataProvider getValuesToTestSetDayOfWeekByString - */ - public function testMonthlyDayOfWeekByString($dayOfWeekStr, $expectedTime) - { - $mock = $this->getMonthlyMock(self::$_JANUARY_15_1971_09_00_00); - $mock->setDayOfWeekFromString($dayOfWeekStr); - $this->assertEquals($expectedTime, $mock->getRescheduledTime()); - } - - /** - * _Monthly - * - * @dataProvider getInvalidDayOfWeekData - * @expectedException \Exception - */ - public function testMonthlyDayOfWeekInvalid($day, $week) - { - $mock = $this->getMonthlyMock(self::$_JANUARY_15_1971_09_00_00); - $mock->setDayOfWeek($day, $week); - } - - /** - * DataProvider for testMonthlyDayOfWeekInvalid - * @return array - */ - public function getInvalidDayOfWeekData() - { - return array( - array(-4, 0), - array(8, 0), - array(0x8, 0), - array('9dd', 0), - array(1, -5), - array(1, 5), - array(1, 0x8), - array(1, '9ff'), - ); - } - - /** - * @param $currentTime - * @return \Piwik\ScheduledTime\Monthly - */ - private function getMonthlyMock($currentTime) - { - $mock = $this->getMock('\Piwik\ScheduledTime\Monthly', array('getTime')); - $mock->expects($this->any()) - ->method('getTime') - ->will($this->returnValue($currentTime)); - - return $mock; - } -} - -ScheduledTime_MonthlyTest::$_JANUARY_01_1971_09_00_00 = mktime(9, 00, 00, 1, 1, 1971); -ScheduledTime_MonthlyTest::$_JANUARY_02_1971_09_00_00 = mktime(9, 00, 00, 1, 2, 1971); -ScheduledTime_MonthlyTest::$_JANUARY_05_1971_09_00_00 = mktime(9, 00, 00, 1, 5, 1971); -ScheduledTime_MonthlyTest::$_JANUARY_15_1971_09_00_00 = mktime(9, 00, 00, 1, 15, 1971); -ScheduledTime_MonthlyTest::$_FEBRUARY_01_1971_00_00_00 = mktime(0, 00, 00, 2, 1, 1971); -ScheduledTime_MonthlyTest::$_FEBRUARY_02_1971_00_00_00 = mktime(0, 00, 00, 2, 2, 1971); -ScheduledTime_MonthlyTest::$_FEBRUARY_03_1971_09_00_00 = mktime(0, 00, 00, 2, 3, 1971); -ScheduledTime_MonthlyTest::$_FEBRUARY_21_1971_09_00_00 = mktime(0, 00, 00, 2, 21, 1971); -ScheduledTime_MonthlyTest::$_FEBRUARY_28_1971_00_00_00 = mktime(0, 00, 00, 2, 28, 1971);
\ No newline at end of file diff --git a/tests/PHPUnit/Core/ScheduledTime/WeeklyTest.php b/tests/PHPUnit/Core/ScheduledTime/WeeklyTest.php deleted file mode 100644 index 62b6fce8ed..0000000000 --- a/tests/PHPUnit/Core/ScheduledTime/WeeklyTest.php +++ /dev/null @@ -1,195 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\ScheduledTime\Weekly; - -/** - * @group Core - */ -class ScheduledTime_WeeklyTest extends PHPUnit_Framework_TestCase -{ - public static $_JANUARY_01_1971_09_10_00; // initialized below class declaration - public static $_JANUARY_04_1971_00_00_00; - public static $_JANUARY_04_1971_09_00_00; - public static $_JANUARY_05_1971_09_00_00; - public static $_JANUARY_11_1971_00_00_00; - public static $_JANUARY_15_1971_00_00_00; - public static $_JANUARY_08_1971_00_00_00; - - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - } - - /** - * Tests invalid call to setHour on Weekly - */ - public function testSetHourScheduledTimeWeeklyNegative() - { - try { - $weeklySchedule = new Weekly(); - $weeklySchedule->setHour(-1); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Tests invalid call to setHour on Weekly - */ - public function testSetHourScheduledTimeWeeklyOver24() - { - try { - $weeklySchedule = new Weekly(); - $weeklySchedule->setHour(25); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Tests invalid call to setDay on Weekly - */ - public function testSetDayScheduledTimeWeeklyDay0() - { - try { - $weeklySchedule = new Weekly(); - $weeklySchedule->setDay(0); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Tests invalid call to setDay on Weekly - */ - public function testSetDayScheduledTimeWeeklyOver7() - { - try { - $weeklySchedule = new Weekly(); - $weeklySchedule->setDay(8); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised'); - } - - /** - * Tests getRescheduledTime on Weekly with unspecified hour and unspecified day - */ - public function testGetRescheduledTimeWeeklyUnspecifiedHourUnspecifiedDay() - { - /* - * Test 1 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 09:10:00 UTC - * - setHour is not called, defaulting to midnight - * - setDay is not called, defaulting to monday - * - * Expected : - * getRescheduledTime returns Monday January 4 1971 00:00:00 UTC - */ - $mock = $this->getWeeklyMock(self::$_JANUARY_01_1971_09_10_00); - $this->assertEquals(self::$_JANUARY_04_1971_00_00_00, $mock->getRescheduledTime()); - } - - /** - * Tests getRescheduledTime on Weekly with specified hour and unspecified day - */ - public function testGetRescheduledTimeWeeklySpecifiedHourUnspecifiedDay() - { - /* - * Test 1 - * - * Context : - * - getRescheduledTime called Friday January 1 1971 09:10:00 UTC - * - setHour is set to 9 - * - setDay is not called, defaulting to monday - * - * Expected : - * getRescheduledTime returns Monday January 4 1971 09:00:00 UTC - */ - $mock = $this->getWeeklyMock(self::$_JANUARY_01_1971_09_10_00); - $mock->setHour(9); - $this->assertEquals(self::$_JANUARY_04_1971_09_00_00, $mock->getRescheduledTime()); - } - - /** - * Returns data used in testGetRescheduledTimeWeeklyUnspecifiedHourSpecifiedDay test. - */ - public function getSetDayParametersToTest() - { - return array( - array(1, self::$_JANUARY_11_1971_00_00_00), - array(5, self::$_JANUARY_08_1971_00_00_00), - array('monday', self::$_JANUARY_11_1971_00_00_00), - array('Monday', self::$_JANUARY_11_1971_00_00_00), - array('FRIDAY', self::$_JANUARY_08_1971_00_00_00), - array('FrIdAy', self::$_JANUARY_08_1971_00_00_00) - ); - } - - public function test_setTimezone_ShouldConvertRescheduledTime() - { - $oneHourInSeconds = 3600; - - $mock = $this->getWeeklyMock(self::$_JANUARY_01_1971_09_10_00); - $timeUTC = $mock->getRescheduledTime(); - $this->assertEquals(self::$_JANUARY_04_1971_00_00_00, $timeUTC); - - $mock->setTimezone('Pacific/Auckland'); - $timeAuckland = $mock->getRescheduledTime(); - $this->assertEquals(-13 * $oneHourInSeconds, $timeAuckland - $timeUTC); - - $mock->setTimezone('America/Los_Angeles'); - $timeLosAngeles = $mock->getRescheduledTime(); - $this->assertEquals(8 * $oneHourInSeconds, $timeLosAngeles - $timeUTC); - } - - /** - * Tests getRescheduledTime on Weekly with unspecified hour and specified day - * - * Context : - * - getRescheduledTime called Monday January 4 1971 09:00:00 UTC - * - setHour is not called, defaulting to midnight - * - setDay is set to $dayToSet - * - * @dataProvider getSetDayParametersToTest - */ - public function testGetRescheduledTimeWeeklyUnspecifiedHourSpecifiedDay($dayToSet, $expectedRescheduledTime) - { - $mock = $this->getWeeklyMock(self::$_JANUARY_04_1971_09_00_00); - $mock->setDay($dayToSet); - - $this->assertEquals($expectedRescheduledTime, $mock->getRescheduledTime()); - } - - /** - * @param $currentTime - * @return \Piwik\ScheduledTime\Weekly - */ - private function getWeeklyMock($currentTime) - { - $mock = $this->getMock('\Piwik\ScheduledTime\Weekly', array('getTime')); - $mock->expects($this->any()) - ->method('getTime') - ->will($this->returnValue($currentTime)); - return $mock; - } -} - -ScheduledTime_WeeklyTest::$_JANUARY_01_1971_09_10_00 = mktime(9, 10, 00, 1, 1, 1971); -ScheduledTime_WeeklyTest::$_JANUARY_04_1971_00_00_00 = mktime(0, 00, 00, 1, 4, 1971); -ScheduledTime_WeeklyTest::$_JANUARY_04_1971_09_00_00 = mktime(9, 00, 00, 1, 4, 1971); -ScheduledTime_WeeklyTest::$_JANUARY_05_1971_09_00_00 = mktime(9, 00, 00, 1, 5, 1971); -ScheduledTime_WeeklyTest::$_JANUARY_11_1971_00_00_00 = mktime(0, 00, 00, 1, 11, 1971); -ScheduledTime_WeeklyTest::$_JANUARY_15_1971_00_00_00 = mktime(0, 00, 00, 1, 15, 1971); -ScheduledTime_WeeklyTest::$_JANUARY_08_1971_00_00_00 = mktime(0, 00, 00, 1, 8, 1971);
\ No newline at end of file diff --git a/tests/PHPUnit/Core/SegmentExpressionTest.php b/tests/PHPUnit/Core/SegmentExpressionTest.php deleted file mode 100644 index 874df9e2d1..0000000000 --- a/tests/PHPUnit/Core/SegmentExpressionTest.php +++ /dev/null @@ -1,129 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\SegmentExpression; - -class SegmentExpressionTest extends PHPUnit_Framework_TestCase -{ - /** - * Dataprovider for testSegmentSqlSimpleNoOperation - * @return array - */ - public function getSimpleSegmentExpressions() - { - return array( - // classic expressions - array('A', " A "), - array('A,B', " (A OR B )"), - array('A;B', " A AND B "), - array('A;B;C', " A AND B AND C "), - array('A,B;C,D;E,F,G', " (A OR B) AND (C OR D) AND (E OR F OR G )"), - - // unescape the backslash - array('A\,B\,C,D', " (A,B,C OR D )"), - array('\,A', ' ,A '), - // unescape only when it was escaping a known delimiter - array('\\\A', ' \\\A '), - // unescape at the end - array('\,\;\A\B,\,C,D\;E\,', ' (,;\A\B OR ,C OR D;E, )'), - - // only replace when a following expression is detected - array('A,', ' A, '), - array('A;', ' A; '), - array('A;B;', ' A AND B; '), - array('A,B,', ' (A OR B, )'), - ); - } - - /** - * @dataProvider getSimpleSegmentExpressions - * @group Core - */ - public function testSegmentSqlSimpleNoOperation($expression, $expectedSql) - { - $segment = new SegmentExpression($expression); - $expected = array('where' => $expectedSql, 'bind' => array(), 'join' => ''); - $processed = $segment->getSql(); - $this->assertEquals($expected, $processed); - } - - /** - * Dataprovider for testSegmentSqlWithOperations - * @return array - */ - public function getOperationSegmentExpressions() - { - // Filter expression => SQL string + Bind values - return array( - array('A==B%', array('where' => " A = ? ", 'bind' => array('B%'))), - array('ABCDEF====B===', array('where' => " ABCDEF = ? ", 'bind' => array('==B==='))), - array('A===B;CDEF!=C!=', array('where' => " A = ? AND ( CDEF IS NULL OR CDEF <> ? ) ", 'bind' => array('=B', 'C!='))), - array('A==B,C==D', array('where' => " (A = ? OR C = ? )", 'bind' => array('B', 'D'))), - array('A!=B;C==D', array('where' => " ( A IS NULL OR A <> ? ) AND C = ? ", 'bind' => array('B', 'D'))), - array('A!=B;C==D,E!=Hello World!=', array('where' => " ( A IS NULL OR A <> ? ) AND (C = ? OR ( E IS NULL OR E <> ? ) )", 'bind' => array('B', 'D', 'Hello World!='))), - - array('A>B', array('where' => " A > ? ", 'bind' => array('B'))), - array('A<B', array('where' => " A < ? ", 'bind' => array('B'))), - array('A<=B', array('where' => " A <= ? ", 'bind' => array('B'))), - array('A>=B', array('where' => " A >= ? ", 'bind' => array('B'))), - array('ABCDEF>=>=>=B===', array('where' => " ABCDEF >= ? ", 'bind' => array('>=>=B==='))), - array('A>=<=B;CDEF>G;H>=I;J<K;L<=M', array('where' => " A >= ? AND CDEF > ? AND H >= ? AND J < ? AND L <= ? ", 'bind' => array('<=B', 'G', 'I', 'K', 'M'))), - array('A>=B;C>=D,E<w_ow great!', array('where' => " A >= ? AND (C >= ? OR E < ? )", 'bind' => array('B', 'D', 'w_ow great!'))), - - array('A=@B_', array('where' => " A LIKE ? ", 'bind' => array('%B\_%'))), - array('A!@B%', array('where' => " ( A IS NULL OR A NOT LIKE ? ) ", 'bind' => array('%B\%%'))), - ); - } - - /** - * @dataProvider getOperationSegmentExpressions - * @group Core - */ - public function testSegmentSqlWithOperations($expression, $expectedSql) - { - $segment = new SegmentExpression($expression); - $segment->parseSubExpressions(); - $segment->parseSubExpressionsIntoSqlExpressions(); - $processed = $segment->getSql(); - $expectedSql['join'] = ''; - $this->assertEquals($expectedSql, $processed); - } - - /** - * Dataprovider for testBogusFiltersExpectExceptionThrown - * @return array - */ - public function getBogusFilters() - { - return array( - array('A=B'), - array('C!D'), - array(''), - array(' '), - array(',;,'), - array(','), - array(',,'), - array('!='), - ); - } - - /** - * @dataProvider getBogusFilters - * @group Core - */ - public function testBogusFiltersExpectExceptionThrown($bogus) - { - try { - $segment = new SegmentExpression($bogus); - $segment->parseSubExpressions(); - $segment->getSql(); - } catch (Exception $e) { - return; - } - $this->fail('Expected exception not raised for:' . var_export($segment->getSql(), true)); - } -} diff --git a/tests/PHPUnit/Core/ServeStaticFileTest.php b/tests/PHPUnit/Core/ServeStaticFileTest.php deleted file mode 100644 index 588c1b8c25..0000000000 --- a/tests/PHPUnit/Core/ServeStaticFileTest.php +++ /dev/null @@ -1,589 +0,0 @@ -<?php -/** - * This php file is used to unit test Piwik::serverStaticFile() - * Unit tests for this method should normally be located in /tests/core/Piwik.test.php - * To make a comprehensive test suit for Piwik::serverStaticFile() (ie. being able to test combinations of request - * headers, being able to test response headers and so on) we need to simulate static file requests in a controlled - * environment - * The php code which simulates requests using Piwik::serverStaticFile() is provided in the same file (ie. this one) - * as the unit testing code for Piwik::serverStaticFile() - * This decision has a structural impact on the usual unit test file structure - * serverStaticFile.test.php has been created to avoid making too many modifications to /tests/core/Piwik.test.php - */ - -// This is Piwik logo, the static file used in this test suit - -use Piwik\ProxyHttp; -use Piwik\SettingsServer; -use Piwik\Tests\Fixture; - -define("TEST_FILE_LOCATION", realpath(dirname(__FILE__) . "/../../resources/lipsum.txt")); -define("TEST_FILE_CONTENT_TYPE", "text/plain"); - -// Defines http request parameters -define("FILE_MODE_REQUEST_VAR", "fileMode"); -define("SRV_MODE_REQUEST_VAR", "serverMode"); -define("ZLIB_OUTPUT_REQUEST_VAR", "zlibOutput"); - -/** - * These constants define the mode in which this php file is used : - * - for unit testing Piwik::serverStaticFile() or - * - as a static file server - */ -define("STATIC_SERVER_MODE", "staticServerMode"); -define("UNIT_TEST_MODE", "unitTestMode"); - -// These constants define which action will be performed by the static server. -define("NULL_FILE_SRV_MODE", "nullFile"); -define("GHOST_FILE_SRV_MODE", "ghostFile"); -define("TEST_FILE_SRV_MODE", "testFile"); -define("PARTIAL_TEST_FILE_SRV_MODE", "partialTestFile"); -define("WHOLE_TEST_FILE_WITH_RANGE_SRV_MODE", "wholeTestFileWithRange"); - -define("PARTIAL_BYTE_START", 1204); -define("PARTIAL_BYTE_END", 14724); - -// If the static file server has not been requested, the standard unit test case class is defined -class Test_Piwik_ServeStaticFile extends PHPUnit_Framework_TestCase -{ - public function tearDown() - { - parent::tearDown(); - chmod(TEST_FILE_LOCATION, 0644); - } - - /** - * Test that php compression isn't enabled ... otherwise, lots of tests will fail - * - * @group Core - */ - public function test_phpOutputCompression() - { - $this->assertFalse(ProxyHttp::isPhpOutputCompressed()); - } - - /** - * Checks that "HTTP/1.0 404 Not Found" is returned when Piwik::serverStaticFile is called with a null file - * - * @group Core - */ - public function test_nullFile() - { - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getNullFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_exec($curlHandle); - $responseInfo = curl_getinfo($curlHandle); - curl_close($curlHandle); - - $this->assertEquals($responseInfo["http_code"], 404); - } - - /** - * Checks that "HTTP/1.0 404 Not Found" is returned when Piwik::serverStaticFile is called with a non existing file - * - * - * @group Core - */ - public function test_ghostFile() - { - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getGhostFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_exec($curlHandle); - $responseInfo = curl_getinfo($curlHandle); - curl_close($curlHandle); - - $this->assertEquals($responseInfo["http_code"], 404); - } - - /** - * Checks that "HTTP/1.0 505 Internal server error" is returned when Piwik::serverStaticFile is called with a - * non-readable file - * - * @group Core - */ - public function test_nonReadableFile() - { - /** - * This test would fail on a windows environment because it is not possible to remove reading rights on a - * windows file using PHP. - */ - if (SettingsServer::isWindows()) { - return; - } - - // Setting mode so the testing file is non-readable - chmod(TEST_FILE_LOCATION, 0200); - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $url = $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_exec($curlHandle); - $responseInfo = curl_getinfo($curlHandle); - curl_close($curlHandle); - - // Restoring file mode - chmod(TEST_FILE_LOCATION, 0644); - - $this->assertEquals($responseInfo["http_code"], 505); - } - - /** - * Context : - * - First access to test file - * - zlib.output_compression = 0 - * - no compression - * Expected : - * - file is send back without compression - * - cache control headers are correctly set - * - * @group Core - */ - public function test_firstAccessNoCompression() - { - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_HEADER, true); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - $fullResponse = curl_exec($curlHandle); - $responseInfo = curl_getinfo($curlHandle); - curl_close($curlHandle); - - // Tests returned code equals 200 - $this->assertEquals(200, $responseInfo["http_code"]); - - // Tests content type - $this->assertContains(TEST_FILE_CONTENT_TYPE, $responseInfo["content_type"]); - - // Tests no compression has been applied - $this->assertNull($this->getContentEncodingValue($fullResponse)); - - // Tests returned size - $this->assertEquals(filesize(TEST_FILE_LOCATION), $responseInfo["size_download"]); - - // Tests if returned modified date is correctly set - $this->assertEquals(gmdate('D, d M Y H:i:s', filemtime(TEST_FILE_LOCATION)) . ' GMT', - $this->getLastModifiedValue($fullResponse)); - - // Tests if cache control headers are correctly set - $this->assertEquals("public, must-revalidate", $this->getCacheControlValue($fullResponse)); - $pragma = $this->getPragma($fullResponse); - $this->assertTrue($pragma == null || $pragma == 'Pragma:'); - $expires = $this->getExpires($fullResponse); - $this->assertTrue(strtotime($expires) > time() + 99 * 86400); - } - - /** - * Context : - * - Second access to test file - * - If-Modified-Since set to test file modification date - * Expected : - * - "HTTP/1.1 304 Not Modified" sent back to client - * - * @group Core - */ - public function test_secondAccessNoCompression() - { - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_TIMECONDITION, 1); - curl_setopt($curlHandle, CURLOPT_TIMEVALUE, filemtime(TEST_FILE_LOCATION)); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_exec($curlHandle); - $responseInfo = curl_getinfo($curlHandle); - curl_close($curlHandle); - - $this->assertEquals($responseInfo["http_code"], 304); - } - - /** - * Context : - * - Second access to test file - * - If-Modified-Since set to test file modification date minus 1 second - * Expected : - * - http return code 200 sent back to client - * - * @group Core - */ - public function test_secondAccessNoCompressionExpiredFile() - { - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_TIMECONDITION, 1); - curl_setopt($curlHandle, CURLOPT_TIMEVALUE, filemtime(TEST_FILE_LOCATION) - 1); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_exec($curlHandle); - $responseInfo = curl_getinfo($curlHandle); - curl_close($curlHandle); - - $this->assertEquals($responseInfo["http_code"], 200); - } - - /** - * Context : - * - First access to file - * - zlib output compression is on - * Expected : - * - the response has to be readable, it tests the proxy doesn't compress the file when compression - * is enabled in php. - * - * @group Core - */ - public function test_responseReadableWithPhpCompression() - { - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->setZlibOutputRequest(($this->getTestFileSrvModeUrl()))); - - // The "" parameter sets all compatible content encodings - curl_setopt($curlHandle, CURLOPT_ENCODING, ""); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - $fullResponse = curl_exec($curlHandle); - curl_close($curlHandle); - - // Tests response content, it has to be equal to the test file. If not equal, double compression occurred - $this->assertEquals($fullResponse, file_get_contents(TEST_FILE_LOCATION)); - } - - /** - * Context : - * - First access to file - * - Content-Encoding: deflate - * Expected : - * - the response has to be readable - * - the compression method used must be gzdeflate and not gzcompression to be IE compatible - * - * @group Core - */ - public function test_deflateCompression() - { - $this->removeCompressedFiles(); - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate"); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - $fullResponse = curl_exec($curlHandle); - curl_close($curlHandle); - - // Tests response content, it has to be equal to the test file - $this->assertEquals($fullResponse, file_get_contents(TEST_FILE_LOCATION)); - - // Tests deflate compression has been used - $deflateFileLocation = $this->getCompressedFileLocation() . ".deflate"; - $this->assertTrue(file_exists($deflateFileLocation)); - - // Tests gzdeflate has been used for IE compatibility - $this->assertEquals(gzinflate(file_get_contents($deflateFileLocation)), file_get_contents(TEST_FILE_LOCATION)); - - $this->removeCompressedFiles(); - } - - /** - * Context : - * - First access to file - * - Content-Encoding: gzip - * Expected : - * - the response has to be readable - * - the compression method used is gzip - * - * @group Core - */ - public function test_gzipCompression() - { - $this->removeCompressedFiles(); - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_ENCODING, "gzip"); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - $fullResponse = curl_exec($curlHandle); - curl_close($curlHandle); - - // Tests response content, it has to be equal to the test file - $this->assertEquals($fullResponse, file_get_contents(TEST_FILE_LOCATION)); - - // Tests gzip compression has been used - $gzipFileLocation = $this->getCompressedFileLocation() . ".gz"; - $this->assertTrue(file_exists($gzipFileLocation)); - - $this->removeCompressedFiles(); - } - - /** - * Context : - * - First access to file - * - Content-Encoding: deflate - * - Repeat twice - * Expected : - * - the compressed file cache mechanism works file, ie. the .deflate file is not generated twice - * - * @group Core - */ - public function test_compressionCache() - { - $this->removeCompressedFiles(); - $deflateFileLocation = $this->getCompressedFileLocation() . ".deflate"; - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate"); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_exec($curlHandle); - curl_close($curlHandle); - - $firstAccessModificationTime = filemtime($deflateFileLocation); - - // Requests made to the static file have to be executed at different times for the test to be valid. - sleep(1); - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate"); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_exec($curlHandle); - curl_close($curlHandle); - - // Tests the .deflate file has not been generated twice - clearstatcache(); - $this->assertEquals($firstAccessModificationTime, filemtime($deflateFileLocation)); - - $this->removeCompressedFiles(); - } - - /** - * Context : - * - First access to file - * - Content-Encoding: deflate - * - Repeat twice, in between: update the modification date of the test file - * Expected : - * - the test file has been updated, the cached compressed file should be regenerated - * - * @group Core - */ - public function test_compressionCacheInvalidation() - { - $this->removeCompressedFiles(); - $deflateFileLocation = $this->getCompressedFileLocation() . ".deflate"; - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate"); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_exec($curlHandle); - curl_close($curlHandle); - - $firstAccessModificationTime = filemtime($deflateFileLocation); - - // Requests made to the static file have to be executed at different times for the test to be valid. - sleep(1); - - // We update the test file modification date - touch(TEST_FILE_LOCATION); - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate"); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_exec($curlHandle); - curl_close($curlHandle); - - clearstatcache(); - $this->assertNotEquals($firstAccessModificationTime, filemtime($deflateFileLocation)); - - $this->removeCompressedFiles(); - } - - /** - * @group Core - */ - public function test_partialFileServeNoCompression() - { - $this->removeCompressedFiles(); - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getPartialTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - $partialResponse = curl_exec($curlHandle); - $responseInfo = curl_getinfo($curlHandle); - curl_close($curlHandle); - - clearstatcache(); - - // check no compressed files created - $this->assertFalse(file_exists($this->getCompressedFileLocation() . ".deflate")); - $this->assertFalse(file_exists($this->getCompressedFileLocation() . ".gz")); - - // check $partialResponse - $this->assertEquals(PARTIAL_BYTE_END - PARTIAL_BYTE_START, $responseInfo["size_download"]); - - $expectedPartialContents = substr(file_get_contents(TEST_FILE_LOCATION), PARTIAL_BYTE_START, - PARTIAL_BYTE_END - PARTIAL_BYTE_START); - $this->assertEquals($expectedPartialContents, $partialResponse); - } - - /** - * @group Core - * @group TestToExec - */ - public function test_partialFileServeWithCompression() - { - $this->removeCompressedFiles(); - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getPartialTestFileSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate"); - $partialResponse = curl_exec($curlHandle); - curl_getinfo($curlHandle); - curl_close($curlHandle); - - clearstatcache(); - - // check the correct compressed file is created - $this->assertTrue(file_exists($this->getCompressedFileLocation() . '.' . PARTIAL_BYTE_START . '.' . PARTIAL_BYTE_END . ".deflate")); - $this->assertFalse(file_exists($this->getCompressedFileLocation() . ".gz")); - - // check $partialResponse - $expectedPartialContents = substr(file_get_contents(TEST_FILE_LOCATION), PARTIAL_BYTE_START, - PARTIAL_BYTE_END - PARTIAL_BYTE_START); - $this->assertEquals($expectedPartialContents, $partialResponse); - - $this->removeCompressedFiles(); - } - - /** - * @group Core - */ - public function test_wholeFileServeWithByteRange() - { - $this->removeCompressedFiles(); - - $curlHandle = curl_init(); - curl_setopt($curlHandle, CURLOPT_URL, $this->getWholeTestFileWithRangeSrvModeUrl()); - curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate"); - $fullResponse = curl_exec($curlHandle); - curl_getinfo($curlHandle); - curl_close($curlHandle); - - clearstatcache(); - - // check the correct compressed file is created - $this->assertTrue(file_exists($this->getCompressedFileLocation() . ".deflate")); - $this->assertFalse(file_exists($this->getCompressedFileLocation() . ".gz")); - - // check $fullResponse - $this->assertEquals(file_get_contents(TEST_FILE_LOCATION), $fullResponse); - - $this->removeCompressedFiles(); - } - - /** - * Helper methods - */ - private function getStaticSrvUrl() - { - $url = Fixture::getRootUrl(); - $url .= '/tests/resources/'; - - return $url . "staticFileServer.php?" . FILE_MODE_REQUEST_VAR . "=" . STATIC_SERVER_MODE . - "&" . SRV_MODE_REQUEST_VAR . "="; - } - - private function getNullFileSrvModeUrl() - { - return $this->getStaticSrvUrl() . NULL_FILE_SRV_MODE; - } - - private function getGhostFileSrvModeUrl() - { - return $this->getStaticSrvUrl() . GHOST_FILE_SRV_MODE; - } - - private function getTestFileSrvModeUrl() - { - return $this->getStaticSrvUrl() . TEST_FILE_SRV_MODE; - } - - private function getPartialTestFileSrvModeUrl() - { - return $this->getStaticSrvUrl() . PARTIAL_TEST_FILE_SRV_MODE; - } - - private function getWholeTestFileWithRangeSrvModeUrl() - { - return $this->getStaticSrvUrl() . WHOLE_TEST_FILE_WITH_RANGE_SRV_MODE; - } - - private function setZlibOutputRequest($url) - { - return $url . "&" . ZLIB_OUTPUT_REQUEST_VAR . "=1"; - } - - private function getContentEncodingValue($fullResponse) - { - preg_match_all('/Content-Encoding:[\s*]([[:print:]]*)/', $fullResponse, $matches); - - if (isset($matches[1][0])) { - return $matches[1][0]; - } - - return null; - } - - private function getCacheControlValue($fullResponse) - { - preg_match_all('/Cache-Control:[\s*]([[:print:]]*)/', $fullResponse, $matches); - - if (isset($matches[1][0])) { - return $matches[1][0]; - } - - return null; - } - - private function getPragma($fullResponse) - { - preg_match_all('/(Pragma:[[:print:]]*)/', $fullResponse, $matches); - - if (isset($matches[1][0])) { - return trim($matches[1][0]); - } - - return null; - } - - private function getExpires($fullResponse) - { - preg_match_all('/Expires: ([[:print:]]*)/', $fullResponse, $matches); - - if (isset($matches[1][0])) { - return trim($matches[1][0]); - } - - return null; - } - - private function getLastModifiedValue($fullResponse) - { - preg_match_all('/Last-Modified:[\s*]([[:print:]]*)/', $fullResponse, $matches); - - if (isset($matches[1][0])) { - return $matches[1][0]; - } - - return null; - } - - private function getCompressedFileLocation() - { - return \Piwik\AssetManager::getInstance()->getAssetDirectory() . '/' . basename(TEST_FILE_LOCATION); - } - - private function removeCompressedFiles() - { - @unlink($this->getCompressedFileLocation() . ".deflate"); - @unlink($this->getCompressedFileLocation() . ".gz"); - } -} diff --git a/tests/PHPUnit/Core/TaskSchedulerTest.php b/tests/PHPUnit/Core/TaskSchedulerTest.php deleted file mode 100644 index 3ec8781df7..0000000000 --- a/tests/PHPUnit/Core/TaskSchedulerTest.php +++ /dev/null @@ -1,330 +0,0 @@ -<?php -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -use Piwik\EventDispatcher; -use Piwik\ScheduledTask; -use Piwik\ScheduledTaskTimetable; -use Piwik\TaskScheduler; - -class TaskSchedulerTest extends PHPUnit_Framework_TestCase -{ - private static function getTestTimetable() - { - return array( - 'CoreAdminHome.purgeOutdatedArchives' => 1355529607, - 'PrivacyManager.deleteReportData_1' => 1322229607, - ); - } - - /** - * Dataprovider for testGetTimetableFromOptionValue - */ - public function getTimetableFromOptionValueTestCases() - { - return array( - - // invalid option values should return a fresh array - array(array(), false), - array(array(), null), - array(array(), 1), - array(array(), ''), - array(array(), 'test'), - - // valid serialized array - array( - array( - 'CoreAdminHome.purgeOutdatedArchives' => 1355529607, - 'PrivacyManager.deleteReportData' => 1355529607, - ), - 'a:2:{s:35:"CoreAdminHome.purgeOutdatedArchives";i:1355529607;s:31:"PrivacyManager.deleteReportData";i:1355529607;}' - ), - ); - } - - /** - * @group Core - * @dataProvider getTimetableFromOptionValueTestCases - */ - public function testGetTimetableFromOptionValue($expectedTimetable, $option) - { - self::stubPiwikOption($option); - - $timetable = new ScheduledTaskTimetable(); - $this->assertEquals($expectedTimetable, $timetable->getTimetable()); - } - - /** - * Dataprovider for testTaskHasBeenScheduledOnce - */ - public function taskHasBeenScheduledOnceTestCases() - { - $timetable = self::getTestTimetable(); - - return array( - array(true, 'CoreAdminHome.purgeOutdatedArchives', $timetable), - array(true, 'PrivacyManager.deleteReportData_1', $timetable), - array(false, 'ScheduledReports.weeklySchedule"', $timetable) - ); - } - - /** - * @group Core - * - * @dataProvider taskHasBeenScheduledOnceTestCases - */ - public function testTaskHasBeenScheduledOnce($expectedDecision, $taskName, $timetable) - { - $timetableObj = new ScheduledTaskTimetable(); - $timetableObj->setTimetable($timetable); - $this->assertEquals($expectedDecision, $timetableObj->taskHasBeenScheduledOnce($taskName)); - } - - /** - * Dataprovider for testGetScheduledTimeForMethod - */ - public function getScheduledTimeForMethodTestCases() - { - $timetable = serialize(self::getTestTimetable()); - - return array( - array(1355529607, 'CoreAdminHome', 'purgeOutdatedArchives', null, $timetable), - array(1322229607, 'PrivacyManager', 'deleteReportData', 1, $timetable), - array(false, 'ScheduledReports', 'weeklySchedule', null, $timetable) - ); - } - - /** - * @group Core - * @dataProvider getScheduledTimeForMethodTestCases - */ - public function testGetScheduledTimeForMethod($expectedTime, $className, $methodName, $methodParameter, $timetable) - { - self::stubPiwikOption($timetable); - - $this->assertEquals($expectedTime, TaskScheduler::getScheduledTimeForMethod($className, $methodName, $methodParameter)); - - self::resetPiwikOption(); - } - - /** - * Dataprovider for testTaskShouldBeExecuted - */ - public function taskShouldBeExecutedTestCases() - { - $timetable = self::getTestTimetable(); - - // set a date in the future (should not run) - $timetable['CoreAdminHome.purgeOutdatedArchives'] = time() + 60000; - - // set now (should run) - $timetable['PrivacyManager.deleteReportData_1'] = time(); - - return array( - array(false, 'CoreAdminHome.purgeOutdatedArchives', $timetable), - array(true, 'PrivacyManager.deleteReportData_1', $timetable), - array(false, 'ScheduledReports.weeklySchedule"', $timetable) - ); - } - - /** - * @group Core - * - * @dataProvider taskShouldBeExecutedTestCases - */ - public function testTaskShouldBeExecuted($expectedDecision, $taskName, $timetable) - { - self::stubPiwikOption(serialize($timetable)); - - $timetable = new ScheduledTaskTimetable(); - $this->assertEquals($expectedDecision, $timetable->shouldExecuteTask($taskName)); - } - - /** - * Dataprovider for testExecuteTask - */ - public function executeTaskTestCases() - { - return array( - array('scheduledTaskOne', null), - array('scheduledTaskTwo', 'parameterValue'), - array('scheduledTaskTwo', 1), - ); - } - - /** - * @group Core - * - * @dataProvider executeTaskTestCases - */ - public function testExecuteTask($methodName, $parameterValue) - { - // assert the scheduled method is executed once with the correct parameter - $mock = $this->getMock('TaskSchedulerTest', array($methodName)); - $mock->expects($this->once())->method($methodName)->with($this->equalTo($parameterValue)); - - $executeTask = new ReflectionMethod('\Piwik\TaskScheduler', 'executeTask'); - $executeTask->setAccessible(true); - - $this->assertNotEmpty($executeTask->invoke( - new TaskScheduler(), - new ScheduledTask ($mock, $methodName, $parameterValue, \Piwik\ScheduledTime::factory('daily')) - )); - } - - /** - * @group Core - * - * Dataprovider for testRunTasks - */ - public function testRunTasksTestCases() - { - $systemTime = time(); - - $dailySchedule = $this->getMock('\Piwik\ScheduledTime\Daily', array('getTime')); - $dailySchedule->expects($this->any()) - ->method('getTime') - ->will($this->returnValue($systemTime)); - - $scheduledTaskOne = new ScheduledTask ($this, 'scheduledTaskOne', null, $dailySchedule); - $scheduledTaskTwo = new ScheduledTask ($this, 'scheduledTaskTwo', 1, $dailySchedule); - $scheduledTaskThree = new ScheduledTask ($this, 'scheduledTaskThree', null, $dailySchedule); - - $caseOneExpectedTable = array( - 'TaskSchedulerTest.scheduledTaskOne' => $scheduledTaskOne->getRescheduledTime(), - 'TaskSchedulerTest.scheduledTaskTwo_1' => $systemTime + 60000, - 'TaskSchedulerTest.scheduledTaskThree' => $scheduledTaskThree->getRescheduledTime(), - ); - - $caseTwoTimetableBeforeExecution = $caseOneExpectedTable; - $caseTwoTimetableBeforeExecution['TaskSchedulerTest.scheduledTaskThree'] = $systemTime; // simulate elapsed time between case 1 and 2 - - return array( - - // case 1) contains : - // - scheduledTaskOne: already scheduled before, should be executed and rescheduled - // - scheduledTaskTwo: already scheduled before, should not be executed and therefore not rescheduled - // - scheduledTaskThree: not already scheduled before, should be scheduled but not executed - array( - $caseOneExpectedTable, - - // methods that should be executed - array( - 'TaskSchedulerTest.scheduledTaskOne' - ), - - // timetable before task execution - array( - 'TaskSchedulerTest.scheduledTaskOne' => $systemTime, - 'TaskSchedulerTest.scheduledTaskTwo_1' => $systemTime + 60000, - ), - // configured tasks - array( - $scheduledTaskOne, - $scheduledTaskTwo, - $scheduledTaskThree, - ) - ), - - // case 2) follows case 1) with : - // - scheduledTaskOne: already scheduled before, should not be executed and therefore not rescheduled - // - scheduledTaskTwo: not configured for execution anymore, should be removed from the timetable - // - scheduledTaskThree: already scheduled before, should be executed and rescheduled - array( - // expected timetable - array( - 'TaskSchedulerTest.scheduledTaskOne' => $scheduledTaskOne->getRescheduledTime(), - 'TaskSchedulerTest.scheduledTaskThree' => $scheduledTaskThree->getRescheduledTime() - ), - - // methods that should be executed - array( - 'TaskSchedulerTest.scheduledTaskThree' - ), - - // timetable before task execution - $caseTwoTimetableBeforeExecution, - - // configured tasks - array( - $scheduledTaskOne, -// $scheduledTaskTwo, Not configured anymore (ie. not returned after TaskScheduler::GET_TASKS_EVENT is issued) - $scheduledTaskThree, - ) - ), - ); - } - - public function scheduledTaskOne() - { - } // nothing to do - public function scheduledTaskTwo($param) - { - } // nothing to do - public function scheduledTaskThree() - { - } // nothing to do - - /** - * @group Core - * - * @dataProvider testRunTasksTestCases - */ - public function testRunTasks($expectedTimetable, $expectedExecutedTasks, $timetableBeforeTaskExecution, $configuredTasks) - { - // temporarily unload plugins - $plugins = \Piwik\Plugin\Manager::getInstance()->getLoadedPlugins(); - $plugins = array_map(function ($p) { return $p->getPluginName(); }, $plugins); - - \Piwik\Plugin\Manager::getInstance()->unloadPlugins(); - - // make sure the get tasks event returns our configured tasks - \Piwik\Piwik::addAction(TaskScheduler::GET_TASKS_EVENT, function(&$tasks) use($configuredTasks) { - $tasks = $configuredTasks; - }); - - // stub the piwik option object to control the returned option value - self::stubPiwikOption(serialize($timetableBeforeTaskExecution)); - TaskScheduler::unsetInstance(); - - // execute tasks - $executionResults = TaskScheduler::runTasks(); - - // assert methods are executed - $executedTasks = array(); - foreach ($executionResults as $executionResult) { - $executedTasks[] = $executionResult['task']; - $this->assertNotEmpty($executionResult['output']); - } - $this->assertEquals($expectedExecutedTasks, $executedTasks); - - // assert the timetable is correctly updated - $timetable = new ScheduledTaskTimetable(); - $this->assertEquals($expectedTimetable, $timetable->getTimetable()); - - // restore loaded plugins & piwik options - EventDispatcher::getInstance()->clearObservers(TaskScheduler::GET_TASKS_EVENT); - \Piwik\Plugin\Manager::getInstance()->loadPlugins($plugins); - self::resetPiwikOption(); - } - - private static function stubPiwikOption($timetable) - { - self::getReflectedPiwikOptionInstance()->setValue(new MockPiwikOption($timetable)); - } - - private static function resetPiwikOption() - { - self::getReflectedPiwikOptionInstance()->setValue(null); - } - - private static function getReflectedPiwikOptionInstance() - { - $piwikOptionInstance = new ReflectionProperty('\Piwik\Option', 'instance'); - $piwikOptionInstance->setAccessible(true); - return $piwikOptionInstance; - } -} diff --git a/tests/PHPUnit/Core/Translate/Filter/ByBaseTranslationsTest.php b/tests/PHPUnit/Core/Translate/Filter/ByBaseTranslationsTest.php deleted file mode 100644 index 8ca2f09319..0000000000 --- a/tests/PHPUnit/Core/Translate/Filter/ByBaseTranslationsTest.php +++ /dev/null @@ -1,156 +0,0 @@ -<?php -use Piwik\Translate\Filter\ByBaseTranslations; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class ByBaseTranslationsTest extends PHPUnit_Framework_TestCase -{ - public function getFilterTestData() - { - return array( - // empty stays empty - array( - array(), - array(), - array(), - array() - ), - // empty plugin is removed - array( - array( - 'test' => array() - ), - array(), - array(), - array( - 'test' => array() - ), - ), - // not existing values/plugins are removed - array( - array( - 'test' => array( - 'key' => 'value', - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'key' => 'value', - 'x' => 'y' - ) - ), - array( - 'test' => array( - 'key' => 'value', - ) - ), - array( - 'test' => array( - 'test' => 'test', - ) - ), - ), - // no change if all exist - array( - array( - 'test' => array( - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'test' => 'test' - ) - ), - array() - ), - // unavailable removed, others stay - array( - array( - 'empty' => array( - 'test' => 'test' - ), - 'test' => array( - 'test' => 'test', - 'empty' => ' ', - ) - ), - array( - 'empty' => array( - 'test' => 'test' - ), - 'test' => array( - 'test' => 'test', - ) - ), - array( - 'empty' => array( - 'test' => 'test' - ), - 'test' => array( - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'empty' => ' ', - ) - ) - ), - array( - array( - 'empty' => array( - 'test' => 'test' - ), - 'test' => array( - 'test' => 'test', - 'empty' => ' ', - ) - ), - array( - 'empty' => array( - 'bla' => 'test' - ), - 'test' => array( - 'test' => 'test', - ) - ), - array( - 'test' => array( - 'test' => 'test' - ) - ), - array( - 'empty' => array( - 'test' => 'test' - ), - 'test' => array( - 'empty' => ' ', - ) - ) - ), - ); - } - - /** - * @dataProvider getFilterTestData - * @group Core - */ - public function testFilter($translations, $baseTranslations, $expected, $filteredData) - { - $filter = new ByBaseTranslations($baseTranslations); - $result = $filter->filter($translations); - $this->assertEquals($expected, $result); - $this->assertEquals($filteredData, $filter->getFilteredData()); - } -} diff --git a/tests/PHPUnit/Core/Translate/Filter/ByParameterCountTest.php b/tests/PHPUnit/Core/Translate/Filter/ByParameterCountTest.php deleted file mode 100644 index 06c72ed24f..0000000000 --- a/tests/PHPUnit/Core/Translate/Filter/ByParameterCountTest.php +++ /dev/null @@ -1,121 +0,0 @@ -<?php -use Piwik\Translate\Filter\ByParameterCount; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class ByParameterCountTest extends PHPUnit_Framework_TestCase -{ - public function getFilterTestData() - { - return array( - // empty stays empty - nothing to filter - array( - array(), - array(), - array(), - array() - ), - // empty plugin is removed - array( - array( - 'test' => array() - ), - array(), - array(), - array(), - ), - // value with %s will be removed, as it isn't there in base - array( - array( - 'test' => array( - 'key' => 'val%sue', - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'key' => 'value', - ) - ), - array( - 'test' => array( - 'test' => 'test', - ) - ), - array( - 'test' => array( - 'key' => 'val%sue', - ) - ), - ), - // no change if placeholder count is the same - array( - array( - 'test' => array( - 'test' => 'te%sst' - ) - ), - array( - 'test' => array( - 'test' => 'test%s' - ) - ), - array( - 'test' => array( - 'test' => 'te%sst' - ) - ), - array() - ), - // missing placeholder will be removed - array( - array( - 'empty' => array( - 'test' => 't%1$sest' - ), - 'test' => array( - 'test' => '%1$stest', - 'empty' => ' ', - ) - ), - array( - 'empty' => array( - 'test' => 'test%1$s' - ), - 'test' => array( - 'test' => '%1$stest%2$s', - ) - ), - array( - 'empty' => array( - 'test' => 't%1$sest' - ), - 'test' => array( - 'empty' => ' ', - ) - ), - array( - 'test' => array( - 'test' => '%1$stest', - ) - ) - ), - ); - } - - /** - * @dataProvider getFilterTestData - * @group Core - */ - public function testFilter($translations, $baseTranslations, $expected, $filteredData) - { - $filter = new ByParameterCount($baseTranslations); - $result = $filter->filter($translations); - $this->assertEquals($expected, $result); - $this->assertEquals($filteredData, $filter->getFilteredData()); - } -} diff --git a/tests/PHPUnit/Core/Translate/Filter/EmptyTranslationsTest.php b/tests/PHPUnit/Core/Translate/Filter/EmptyTranslationsTest.php deleted file mode 100644 index a083e50a43..0000000000 --- a/tests/PHPUnit/Core/Translate/Filter/EmptyTranslationsTest.php +++ /dev/null @@ -1,93 +0,0 @@ -<?php -use Piwik\Translate\Filter\EmptyTranslations; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class EmptyTranslationsTest extends PHPUnit_Framework_TestCase -{ - public function getFilterTestData() - { - return array( - // empty stays empty - array( - array(), - array(), - array() - ), - // empty plugin is removed - array( - array( - 'test' => array() - ), - array(), - array(), - ), - // empty values/plugins are removed - array( - array( - 'test' => array( - 'empty' => '', - 'whitespace' => ' ' - ) - ), - array(), - array( - 'test' => array( - 'empty' => '', - 'whitespace' => ' ' - ) - ), - ), - // no change if no empty value - array( - array( - 'test' => array( - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'test' => 'test' - ) - ), - array() - ), - // empty values are removed, others stay - array( - array( - 'empty' => array(), - 'test' => array( - 'test' => 'test', - 'empty' => ' ', - ) - ), - array( - 'test' => array( - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'empty' => ' ', - ) - ) - ), - ); - } - - /** - * @dataProvider getFilterTestData - * @group Core - */ - public function testFilter($translations, $expected, $filteredData) - { - $filter = new EmptyTranslations(); - $result = $filter->filter($translations); - $this->assertEquals($expected, $result); - $this->assertEquals($filteredData, $filter->getFilteredData()); - } -} diff --git a/tests/PHPUnit/Core/Translate/Filter/EncodedEntitiesTest.php b/tests/PHPUnit/Core/Translate/Filter/EncodedEntitiesTest.php deleted file mode 100644 index cfad46387b..0000000000 --- a/tests/PHPUnit/Core/Translate/Filter/EncodedEntitiesTest.php +++ /dev/null @@ -1,107 +0,0 @@ -<?php -use Piwik\Translate\Filter\EncodedEntities; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class EncodedEntitiesTest extends PHPUnit_Framework_TestCase -{ - public function getFilterTestData() - { - return array( - // empty stays empty - nothing to filter - array( - array(), - array(), - array() - ), - // empty plugin is removed - array( - array( - 'test' => array() - ), - array( - 'test' => array() - ), - array(), - ), - // no entites - nothing to filter - array( - array( - 'test' => array( - 'key' => 'val%sue', - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'key' => 'val%sue', - 'test' => 'test' - ) - ), - array(), - ), - // entities needs to be decodded - array( - array( - 'test' => array( - 'test' => 'te&st' - ) - ), - array( - 'test' => array( - 'test' => 'te&st' - ) - ), - array( - 'test' => array( - 'test' => 'te&st' - ) - ), - ), - array( - array( - 'empty' => array( - 'test' => 'tüsest' - ), - 'test' => array( - 'test' => '%1$stest', - 'empty' => '˜', - ) - ), - array( - 'empty' => array( - 'test' => 'tüsest' - ), - 'test' => array( - 'test' => '%1$stest', - 'empty' => '˜', - ) - ), - array( - 'empty' => array( - 'test' => 'tüsest' - ), - 'test' => array( - 'empty' => '˜', - ) - ), - ), - ); - } - - /** - * @dataProvider getFilterTestData - * @group Core - */ - public function testFilter($translations, $expected, $filteredData) - { - $filter = new EncodedEntities(); - $result = $filter->filter($translations); - $this->assertEquals($expected, $result); - $this->assertEquals($filteredData, $filter->getFilteredData()); - } -} diff --git a/tests/PHPUnit/Core/Translate/Filter/UnnecassaryWhitespacesTest.php b/tests/PHPUnit/Core/Translate/Filter/UnnecassaryWhitespacesTest.php deleted file mode 100644 index 3f86b97a0d..0000000000 --- a/tests/PHPUnit/Core/Translate/Filter/UnnecassaryWhitespacesTest.php +++ /dev/null @@ -1,152 +0,0 @@ -<?php -use Piwik\Translate\Filter\UnnecassaryWhitespaces; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class UnnecassaryWhitepsacesTest extends PHPUnit_Framework_TestCase -{ - public function getFilterTestData() - { - return array( - // empty stays empty - nothing to filter - array( - array(), - array(), - array(), - array() - ), - // no entites - nothing to filter - array( - array( - 'test' => array( - 'key' => "val\n\n\r\n\nue", - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'key' => "base val\n\nue", - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'key' => "val\n\nue", - 'test' => 'test' - ) - ), - array( - 'test' => array( - 'key' => "val\n\n\r\n\nue", - ) - - ), - ), - // entities needs to be decodded - array( - array( - 'test' => array( - 'test' => 'test palim' - ) - ), - array( - 'test' => array( - 'test' => 'no line breaks' - ) - ), - array( - 'test' => array( - 'test' => 'test palim' - ) - ), - array( - 'test' => array( - 'test' => 'test palim' - ) - ), - ), - array( - array( - 'empty' => array( - 'test' => "test\n\n\ntest" - ), - ), - array( - 'empty' => array( - 'test' => 'no line break' - ), - ), - array( - 'empty' => array( - 'test' => 'test test' - ), - ), - array( - 'empty' => array( - 'test' => "test\n\n\ntest" - ), - ), - ), - array( - array( - 'empty' => array( - 'test' => "test\n \n\n test" - ), - ), - array( - 'empty' => array( - 'test' => 'no line break' - ), - ), - array( - 'empty' => array( - 'test' => 'test test' - ), - ), - array( - 'empty' => array( - 'test' => "test\n \n\n test" - ), - ), - ), - array( - array( - 'empty' => array( - 'test' => "test\n \n\n test" - ), - ), - array( - 'empty' => array( - 'test' => "line\n break" - ), - ), - array( - 'empty' => array( - 'test' => "test\n\ntest" - ), - ), - array( - 'empty' => array( - 'test' => "test\n \n\n test" - ), - ), - ), - ); - } - - /** - * @dataProvider getFilterTestData - * @group Core - */ - public function testFilter($translations, $baseTranslations, $expected, $filteredData) - { - $filter = new UnnecassaryWhitespaces($baseTranslations); - $result = $filter->filter($translations); - $this->assertEquals($expected, $result); - $this->assertEquals($filteredData, $filter->getFilteredData()); - } -} diff --git a/tests/PHPUnit/Core/Translate/Validate/CoreTranslationsTest.php b/tests/PHPUnit/Core/Translate/Validate/CoreTranslationsTest.php deleted file mode 100644 index 3cde1e42c8..0000000000 --- a/tests/PHPUnit/Core/Translate/Validate/CoreTranslationsTest.php +++ /dev/null @@ -1,131 +0,0 @@ -<?php -use Piwik\Translate\Validate\CoreTranslations; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class CoreTranslationsTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - include PIWIK_INCLUDE_PATH . '/core/DataFiles/Languages.php'; - include PIWIK_INCLUDE_PATH . '/core/DataFiles/Countries.php'; - } - - public function getFilterTestDataValid() - { - return array( - array( - array( - 'General' => array_merge(array_fill(0, 251, 'test'), array( - 'Locale' => 'de_DE.UTF-8', - 'TranslatorName' => 'name', - 'TranslatorEmail' => 'email', - ) - ) - ), - ) - ); - } - - /** - * @dataProvider getFilterTestDataValid - * @group Core - */ - public function testFilterValid($translations) - { - $filter = new CoreTranslations(); - $result = $filter->isValid($translations); - $this->assertTrue($result); - } - - public function getFilterTestDataInvalid() - { - return array( - array( - array( - 'General' => array( - 'bla' => 'test text' - ) - ), - CoreTranslations::ERRORSTATE_LOCALEREQUIRED - ), - array( - array( - 'General' => array( - 'Locale' => 'de_DE.UTF-8' - ) - ), - CoreTranslations::ERRORSTATE_TRANSLATORINFOREQUIRED - ), - array( - array( - 'General' => array( - 'Locale' => 'de_DE.UTF-8', - 'TranslatorName' => 'name', - ) - ), - CoreTranslations::ERRORSTATE_TRANSLATOREMAILREQUIRED - ), - array( - array( - 'General' => array( - 'Locale' => 'de_DE.UTF-8', - 'TranslatorName' => 'name', - 'TranslatorEmail' => 'emails', - 'LayoutDirection' => 'afd' - ) - ), - CoreTranslations::ERRORSTATE_LAYOUTDIRECTIONINVALID - ), - array( - array( - 'General' => array( - 'Locale' => 'invalid', - 'TranslatorName' => 'name', - 'TranslatorEmail' => 'emails', - 'LayoutDirection' => 'ltr' - ) - ), - CoreTranslations::ERRORSTATE_LOCALEINVALID - ), - array( - array( - 'General' => array( - 'Locale' => 'xx_DE.UTF-8', - 'TranslatorName' => 'name', - 'TranslatorEmail' => 'emails', - 'LayoutDirection' => 'ltr' - ) - ), - CoreTranslations::ERRORSTATE_LOCALEINVALIDLANGUAGE - ), - array( - array( - 'General' => array( - 'Locale' => 'de_XX.UTF-8', - 'TranslatorName' => 'name', - 'TranslatorEmail' => 'emails', - 'LayoutDirection' => 'ltr' - ) - ), - CoreTranslations::ERRORSTATE_LOCALEINVALIDCOUNTRY - ), - ); - } - - /** - * @dataProvider getFilterTestDataInvalid - * @group Core - */ - public function testFilterInvalid($translations, $msg) - { - $filter = new CoreTranslations(); - $result = $filter->isValid($translations); - $this->assertFalse($result); - $this->assertEquals($msg, $filter->getMessage()); - } -} diff --git a/tests/PHPUnit/Core/Translate/Validate/NoScriptsTest.php b/tests/PHPUnit/Core/Translate/Validate/NoScriptsTest.php deleted file mode 100644 index e0a8f27b80..0000000000 --- a/tests/PHPUnit/Core/Translate/Validate/NoScriptsTest.php +++ /dev/null @@ -1,107 +0,0 @@ -<?php -use Piwik\Translate\Validate\NoScripts; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class NoScriptsTest extends PHPUnit_Framework_TestCase -{ - public function getFilterTestDataValid() - { - return array( - array( - array(), - ), - array( - array( - 'test' => array() - ), - ), - array( - array( - 'test' => array( - 'key' => 'val%sue', - 'test' => 'test' - ) - ), - ), - ); - } - - /** - * @dataProvider getFilterTestDataValid - * @group Core - */ - public function testFilterValid($translations) - { - $filter = new NoScripts(); - $result = $filter->isValid($translations); - $this->assertTrue($result); - } - - public function getFilterTestDataInvalid() - { - return array( - array( - array( - 'test' => array( - 'test' => 'test text <script' - ) - ), - ), - array( - array( - 'empty' => array( - 'test' => 'tüsest' - ), - 'test' => array( - 'test' => 'bla <a href="javascript:alert();"> link </a>', - 'empty' => '˜', - ) - ), - ), - array( - array( - 'test' => array( - 'test' => 'bla <a onload="alert(\'test\');">link</a>' - ) - ), - ), - array( - array( - 'test' => array( - 'test' => 'no <img src="test" />' - ) - ), - ), - array( - array( - 'test' => array( - 'test' => 'that will fail on document. or not?' - ) - ), - ), - array( - array( - 'test' => array( - 'test' => 'bla <a background="yellow">link</a>' - ) - ), - ), - ); - } - - /** - * @dataProvider getFilterTestDataInvalid - * @group Core - */ - public function testFilterInvalid($translations) - { - $filter = new NoScripts(); - $result = $filter->isValid($translations); - $this->assertFalse($result); - } -} diff --git a/tests/PHPUnit/Core/Translate/WriterTest.php b/tests/PHPUnit/Core/Translate/WriterTest.php deleted file mode 100644 index 500009941a..0000000000 --- a/tests/PHPUnit/Core/Translate/WriterTest.php +++ /dev/null @@ -1,275 +0,0 @@ -<?php - -use Piwik\Translate\Filter\ByBaseTranslations; -use Piwik\Translate\Filter\ByParameterCount; -use Piwik\Translate\Filter\UnnecassaryWhitespaces; -use Piwik\Translate\Validate\CoreTranslations; -use Piwik\Translate\Validate\NoScripts; -use Piwik\Translate\Writer; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class WriterTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - parent::setUp(); - include PIWIK_INCLUDE_PATH . '/core/DataFiles/Languages.php'; - include PIWIK_INCLUDE_PATH . '/core/DataFiles/Countries.php'; - } - - /** - * @group Core - * - * @dataProvider getValidConstructorData - */ - public function testConstructorValid($language, $plugin) - { - $translationWriter = new Writer($language, $plugin); - $this->assertEquals($language, $translationWriter->getLanguage()); - $this->assertFalse($translationWriter->hasTranslations()); - } - - public function getValidConstructorData() - { - return array( - array('en', ''), - array('de', ''), - array('en', 'ExamplePlugin'), - ); - } - - /** - * @group Core - * - * @expectedException Exception - */ - public function testConstructorInvalid() - { - new Writer('en', 'InValIdPlUGin'); - } - - /** - * @group Core - */ - public function testHasTranslations() - { - $writer = new Writer('de'); - $writer->setTranslations(array('General' => array('test' => 'test'))); - $this->assertTrue($writer->hasTranslations()); - } - - /** - * @group Core - */ - public function testHasNoTranslations() - { - $writer = new Writer('de'); - $this->assertFalse($writer->hasTranslations()); - } - - /** - * @group Core - */ - public function testSetTranslationsEmpty() - { - $writer = new Writer('de'); - $writer->setTranslations(array()); - $this->assertTrue($writer->isValid()); - $this->assertFalse($writer->hasTranslations()); - } - - /** - * @group Core - * - * @dataProvider getInvalidTranslations - */ - public function testSetTranslationsInvalid($translations, $error) - { - $writer = new Writer('de'); - $writer->setTranslations($translations); - $writer->addValidator(new NoScripts()); - $writer->addValidator(new CoreTranslations()); - $this->assertFalse($writer->isValid()); - $this->assertEquals($error, $writer->getValidationMessage()); - } - - public function getInvalidTranslations() - { - $translations = json_decode(file_get_contents(PIWIK_INCLUDE_PATH.'/lang/de.json'), true); - return array( - array(array('General' => array('Locale' => '')) + $translations, CoreTranslations::ERRORSTATE_LOCALEREQUIRED), - array(array('General' => array('Locale' => 'de_DE.UTF-8')) + $translations, CoreTranslations::ERRORSTATE_TRANSLATORINFOREQUIRED), - array(array('General' => array('Locale' => 'de_DE.UTF-8', - 'TranslatorName' => 'name')) + $translations, CoreTranslations::ERRORSTATE_TRANSLATOREMAILREQUIRED), - array(array('General' => array('Locale' => 'de_DE.UTF-8', - 'TranslatorName' => 'name', - 'TranslatorEmail' => 'name@domain.com', - 'LayoutDirection' => 'fail')) + $translations, CoreTranslations::ERRORSTATE_LAYOUTDIRECTIONINVALID), - array(array('General' => array('Locale' => 'invalid', - 'TranslatorName' => 'name', - 'TranslatorEmail' => 'name@domain.com')) + $translations, CoreTranslations::ERRORSTATE_LOCALEINVALID), - array(array('General' => array('Locale' => 'xx_DE.UTF-8', - 'TranslatorName' => 'name', - 'TranslatorEmail' => 'name@domain.com',)) + $translations, CoreTranslations::ERRORSTATE_LOCALEINVALIDLANGUAGE), - array(array('General' => array('Locale' => 'de_XX.UTF-8', - 'TranslatorName' => 'name', - 'TranslatorEmail' => 'name@domain.com',)) + $translations, CoreTranslations::ERRORSTATE_LOCALEINVALIDCOUNTRY), - array(array('General' => array('Locale' => '<script>')) + $translations, 'script tags restricted for language files'), - ); - } - - /** - * @group Core - * - * @expectedException Exception - */ - public function testSaveException() - { - $writer = new Writer('it'); - $writer->save(); - } - - /** - * @group Core - * - * @expectedException Exception - */ - public function testSaveTemporaryException() - { - $writer = new Writer('it'); - $writer->saveTemporary(); - } - - /** - * @group Core - */ - public function testSaveTranslation() - { - $translations = json_decode(file_get_contents(PIWIK_INCLUDE_PATH.'/lang/en.json'), true); - - $translationsToWrite = array(); - $translationsToWrite['General'] = $translations['General']; - $translationsToWrite['Mobile'] = $translations['Mobile']; - - $translationsToWrite['General']['Yes'] = 'string with %1$s'; - $translationsToWrite['Plugin'] = array( - 'Body' => "Message\nBody" - ); - - $translationWriter = new Writer('fr'); - - $translationWriter->addFilter(new UnnecassaryWhitespaces($translations)); - $translationWriter->addFilter(new ByBaseTranslations($translations)); - $translationWriter->addFilter(new ByParameterCount($translations)); - - $translationWriter->setTranslations($translationsToWrite); - - $rc = $translationWriter->saveTemporary(); - - @unlink(PIWIK_INCLUDE_PATH.'/tmp/fr.json'); - - $this->assertGreaterThan(25000, $rc); - - $this->assertCount(4, $translationWriter->getFilterMessages()); - } - - /** - * @group Core - * - * @dataProvider getTranslationPathTestData - */ - public function testGetTranslationsPath($language, $plugin, $path) - { - $writer = new Writer($language, $plugin); - $this->assertEquals($path, $writer->getTranslationPath()); - } - - public function getTranslationPathTestData() - { - return array( - array('de', null, PIWIK_INCLUDE_PATH . '/lang/de.json'), - array('te', null, PIWIK_INCLUDE_PATH . '/lang/te.json'), - array('de', 'CoreHome', PIWIK_INCLUDE_PATH . '/plugins/CoreHome/lang/de.json'), - array('pt-br', 'Actions', PIWIK_INCLUDE_PATH . '/plugins/Actions/lang/pt-br.json'), - ); - } - - /** - * @group Core - * - * @dataProvider getTranslationPathTemporaryTestData - */ - public function testGetTemporaryTranslationPath($language, $plugin, $path) - { - $writer = new Writer($language, $plugin); - $this->assertEquals($path, $writer->getTemporaryTranslationPath()); - } - - public function getTranslationPathTemporaryTestData() - { - return array( - array('de', null, PIWIK_INCLUDE_PATH . '/tmp/de.json'), - array('te', null, PIWIK_INCLUDE_PATH . '/tmp/te.json'), - array('de', 'CoreHome', PIWIK_INCLUDE_PATH . '/tmp/plugins/CoreHome/lang/de.json'), - array('pt-br', 'Actions', PIWIK_INCLUDE_PATH . '/tmp/plugins/Actions/lang/pt-br.json'), - ); - } - - /** - * @group Core - * - * @dataProvider getValidLanguages - */ - public function testSetLanguageValid($language) - { - $writer = new Writer('en', null); - $writer->setLanguage($language); - $this->assertEquals(strtolower($language), $writer->getLanguage()); - } - - public function getValidLanguages() - { - return array( - array('de'), - array('te'), - array('pt-br'), - array('tzm'), - array('abc'), - array('de-de'), - array('DE'), - array('DE-DE'), - array('DE-de'), - ); - } - /** - * @group Core - * - * @expectedException Exception - * @dataProvider getInvalidLanguages - */ - public function testSetLanguageInvalid($language) - { - $writer = new Writer('en', null); - $writer->setLanguage($language); - } - - public function getInvalidLanguages() - { - return array( - array(''), - array('abcd'), - array('pt-brfr'), - array('00'), - array('a-b'), - array('x3'), - array('X4-fd'), - array('12-34'), - array('$§'), - ); - } -} diff --git a/tests/PHPUnit/Core/TranslateTest.php b/tests/PHPUnit/Core/TranslateTest.php deleted file mode 100644 index b7a99f70ee..0000000000 --- a/tests/PHPUnit/Core/TranslateTest.php +++ /dev/null @@ -1,42 +0,0 @@ -<?php - -use Piwik\Translate; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class TranslateTest extends PHPUnit_Framework_TestCase -{ - /** - * Dataprovider for testClean - */ - public function getCleanTestData() - { - return array( - // empty string - array("", ''), - // newline - array("\n", ''), - // leading and trailing whitespace - array(" a \n", 'a'), - // single / double quotes - array(" "it's" ", '"it\'s"'), - // html special characters - array("<tag>", '<tag>'), - // other html entities - array("…", '…'), - ); - } - - /** - * @group Core - * @dataProvider getCleanTestData - */ - public function testClean($data, $expected) - { - $this->assertEquals($expected, Translate::clean($data)); - } -}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/UrlHelperTest.php b/tests/PHPUnit/Core/UrlHelperTest.php deleted file mode 100644 index 79ba4fbecd..0000000000 --- a/tests/PHPUnit/Core/UrlHelperTest.php +++ /dev/null @@ -1,229 +0,0 @@ -<?php
-use Piwik\UrlHelper;
-
-/**
- * Piwik - free/libre analytics platform
- *
- * @link http://piwik.org
- * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
- */
-class Core_UrlHelperTest extends PHPUnit_Framework_TestCase
-{
- /**
- * Dataprovider for testIsUrl
- */
- public function getUrls()
- {
- return array(
- // valid urls
- array('http://piwik.org', true),
- array('http://www.piwik.org', true),
- array('https://piwik.org', true),
- array('https://piwik.org/dir/dir2/?oeajkgea7aega=&ge=a', true),
- array('ftp://www.pi-wik.org', true),
- array('news://www.pi-wik.org', true),
- array('https://www.tëteâ.org', true),
- array('http://汉语/漢語.cn', true), //chinese
- // invalid urls
- array('it doesnt look like url', false),
- array('/index?page=test', false),
- array('test.html', false),
- array('/\/\/\/\/\/\\\http://test.com////', false),
- array('jmleslangues.php', false),
- array('http://', false),
- array(' http://', false),
- array('testhttp://test.com', false),
- );
- }
-
- /**
- * @dataProvider getUrls
- * @group Core
- */
- public function testIsUrl($url, $isValid)
- {
- $this->assertEquals($isValid, UrlHelper::isLookLikeUrl($url));
- }
-
- /**
- * Dataprovider for testGetParameterFromQueryString
- */
- public function getQueryStrings()
- {
- return array( // querystring, parameter, expected value
- array('x=1', 'x', '1'),
- array('?x=1', 'x', '1'),
- array('?x=y==1', 'x', 'y==1'),
- array('x[]=', 'x', array('')),
- array('x[]=1', 'x', array('1')),
- array('x[]=y==1', 'x', array('y==1')),
- array('?x[]=1&x[]=2', 'x', array('1', '2')),
- array('?x%5b%5d=3&x[]=4', 'x', array('3', '4')),
- array('?x%5B]=5&x[%5D=6', 'x', array('5', '6')),
- array('toto=mama&mama=&tuytyt=teaoi&toto=mama second value', 'tuytyt', 'teaoi'),
-
- // don't unescape the value, otherwise it becomes
- // ?x[]=A&y=1
- array('?x%5B%5D=A%26y%3D1', 'x', array('A%26y%3D1')),
- // ?z=y&x[]=1
- array('?z=y%26x%5b%5d%3d1', 'x', null),
-
- // strange characters
- array('toto=mama&mama=&tuytyt=Поиск в Интернете Поиск страниц на русском _*()!$!£$^!£$%&toto=mama second value', 'tuytyt', 'Поиск в Интернете Поиск страниц на русском _*()!$!£$^!£$%'),
-
- // twice the parameter => returns the last value in the url
- array('toto=mama&mama=&tuytyt=teaoi&toto=mama second value', 'toto', 'mama second value'),
-
- // empty param
- array('toto=mama&mama=&tuytyt=teaoi', 'mama', ''),
-
- // missing parameter value => returns false
- array('x', 'x', false),
- array('toto=mama&mama&tuytyt=teaoi', 'mama', false),
-
- // param not found => null
- array('toto=mama&mama=titi', 'tot', null),
-
- // empty query string => null
- array('', 'test', null),
- );
- }
-
- /**
- * @dataProvider getQueryStrings
- * @group Core
- */
- public function testGetParameterFromQueryString($queryString, $parameter, $expected)
- {
- $this->assertSame($expected, UrlHelper::getParameterFromQueryString($queryString, $parameter));
- }
-
- /**
- * @group Core
- */
- public function testGetPathAndQueryFromUrl()
- {
- $this->assertEquals('test/index.php?module=CoreHome', UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php?module=CoreHome'));
- }
-
- /**
- * @group Core
- */
- public function testGetArrayFromQueryString()
- {
- $expected = array(
- 'a' => false,
- 'b' => '',
- 'c' => '1',
- 'd' => array(false),
- 'e' => array(''),
- 'f' => array('a'),
- 'g' => array('b', 'c'),
- );
- $this->assertEquals(serialize($expected), serialize(UrlHelper::getArrayFromQueryString('a&b=&c=1&d[]&e[]=&f[]=a&g[]=b&g[]=c')));
- }
-
- /**
- * Dataprovider for testExtractSearchEngineInformationFromUrl
- */
- public function getSearchEngineUrls()
- {
- return Spyc::YAMLLoad(PIWIK_PATH_TEST_TO_ROOT .'/tests/resources/extractSearchEngineInformationFromUrlTests.yml');
- }
-
- /**
- * @dataProvider getSearchEngineUrls
- * @group Core
- */
- public function testExtractSearchEngineInformationFromUrl($url, $engine, $keywords)
- {
- $this->includeDataFilesForSearchEngineTest();
- $returnedValue = UrlHelper::extractSearchEngineInformationFromUrl($url);
-
- $exptectedValue = false;
-
- if (!empty($engine)) {
- $exptectedValue = array('name' => $engine, 'keywords' => $keywords);
- }
-
- $this->assertEquals($exptectedValue, $returnedValue);
- }
-
- /**
- * Dataprovider for testGetLossyUrl
- */
- public function getLossyUrls()
- {
- return array(
- array('example.com', 'example.com'),
- array('m.example.com', 'example.com'),
- array('www.example.com', 'example.com'),
- array('search.example.com', 'example.com'),
- array('example.ca', 'example.{}'),
- array('us.example.com', '{}.example.com'),
- array('www.m.example.ca', 'example.{}'),
- array('www.google.com.af', 'google.{}'),
- array('www.google.co.uk', 'google.{}'),
- array('images.de.ask.com', 'images.{}.ask.com'),
- );
- }
-
- /**
- * @dataProvider getLossyUrls
- * @group Core
- */
- public function testGetLossyUrl($input, $expected)
- {
- $this->assertEquals($expected, UrlHelper::getLossyUrl($input));
- }
- - private function includeDataFilesForSearchEngineTest()
- {
- include "DataFiles/SearchEngines.php";
- include "DataFiles/Countries.php";
- }
- - /**
- * @group Core
- */
- public function test_getHostFromUrl()
- {
- $this->assertEquals('', UrlHelper::getHostFromUrl(''));
- $this->assertEquals('', UrlHelper::getHostFromUrl(null));
- $this->assertEquals('localhost', UrlHelper::getHostFromUrl('http://localhost'));
- $this->assertEquals('localhost', UrlHelper::getHostFromUrl('http://localhost/path'));
- $this->assertEquals('localhost', UrlHelper::getHostFromUrl('localhost/path'));
- $this->assertEquals('sub.localhost', UrlHelper::getHostFromUrl('sub.localhost/path'));
- $this->assertEquals('sub.localhost', UrlHelper::getHostFromUrl('http://sub.localhost/path/?query=test'));
- }
-
- /**
- * @group Core
- */
- public function test_getQueryFromUrl_ShouldReturnEmtpyString_IfNoQuery()
- {
- $this->assertEquals('', UrlHelper::getQueryFromUrl('', array()));
- $this->assertEquals('', UrlHelper::getQueryFromUrl(null, array()));
- $this->assertEquals('', UrlHelper::getQueryFromUrl('http://localhost/path', array()));
- }
-
- /**
- * @group Core
- */
- public function test_getQueryFromUrl_ShouldReturnOnlyTheQueryPartOfTheUrl_IfNoAdditionalParamsGiven()
- {
- $this->assertEquals('foo=bar&foo2=bar2&test[]=1', UrlHelper::getQueryFromUrl('http://example.com/?foo=bar&foo2=bar2&test[]=1', array()));
- $this->assertEquals('foo=bar&foo2=bar2&test[]=1', UrlHelper::getQueryFromUrl('/?foo=bar&foo2=bar2&test[]=1', array()));
- $this->assertEquals('segment=pageTitle!@%40Hello%20World;pageTitle!@Peace%20Love%20', UrlHelper::getQueryFromUrl('/?segment=pageTitle!@%40Hello%20World;pageTitle!@Peace%20Love%20', array()));
- }
-
- /**
- * @group Core
- */
- public function test_getQueryFromUrl_ShouldAddAdditionalParams_IfGiven()
- {
- $this->assertEquals('foo=bar&foo2=bar2&test[]=1&add=foo', UrlHelper::getQueryFromUrl('http://example.com/?foo=bar&foo2=bar2&test[]=1', array('add' => 'foo')));
- $this->assertEquals('add=foo', UrlHelper::getQueryFromUrl('/', array('add' => 'foo')));
- $this->assertEquals('add[]=foo&add[]=test', UrlHelper::getQueryFromUrl('/', array('add' => array('foo', 'test'))));
- }
-}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/UrlTest.php b/tests/PHPUnit/Core/UrlTest.php deleted file mode 100644 index c77907ee04..0000000000 --- a/tests/PHPUnit/Core/UrlTest.php +++ /dev/null @@ -1,338 +0,0 @@ -<?php -use Piwik\Config; -use Piwik\Url; - -/** - * Piwik - free/libre analytics platform - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - */ -class UrlTest extends PHPUnit_Framework_TestCase -{ - /** - * @group Core - */ - public function testAllMethods() - { - $this->assertEquals(Url::getCurrentQueryStringWithParametersModified(array()), Url::getCurrentQueryString()); - $this->assertEquals(Url::getCurrentUrl(), Url::getCurrentUrlWithoutQueryString()); - $this->assertEquals(Url::getCurrentUrl(), Url::getCurrentScheme() . '://' . Url::getCurrentHost() . Url::getCurrentScriptName()); - - $_SERVER['QUERY_STRING'] = 'q=test'; - - $parameters = array_keys(Url::getArrayFromCurrentQueryString()); - $parametersNameToValue = array(); - foreach ($parameters as $name) { - $parametersNameToValue[$name] = null; - } - $this->assertEquals('', Url::getCurrentQueryStringWithParametersModified($parametersNameToValue)); - } - - /** - * Dataprovider for testGetCurrentHost() - */ - public function getCurrentHosts() - { - return array( - array('localhost IPv4', array('127.0.0.1', null, null, null, '127.0.0.1')), - array('localhost IPv6', array('[::1]', null, null, null, '[::1]')), - array('localhost name', array('localhost', null, null, null, 'localhost')), - - array('IPv4 without proxy', array('128.1.2.3', null, null, null, '128.1.2.3')), - array('IPv6 without proxy', array('[2001::b0b]', null, null, null, '[2001::b0b]')), - array('name without proxy', array('example.com', null, null, null, 'example.com')), - - array('IPv4 with one proxy', array('127.0.0.1', '128.1.2.3', 'HTTP_X_FORWARDED_HOST', null, '128.1.2.3')), - array('IPv6 with one proxy', array('[::1]', '[2001::b0b]', 'HTTP_X_FORWARDED_HOST', null, '[2001::b0b]')), - array('name with one IPv4 proxy', array('192.168.1.10', 'example.com', 'HTTP_X_FORWARDED_HOST', null, 'example.com')), - array('name with one IPv6 proxy', array('[::10]', 'www.example.com', 'HTTP_X_FORWARDED_HOST', null, 'www.example.com')), - array('name with one named proxy', array('dmz.example.com', 'www.example.com', 'HTTP_X_FORWARDED_HOST', null, 'www.example.com')), - - array('IPv4 with multiple proxies', array('127.0.0.1', '128.1.2.3, 192.168.1.10', 'HTTP_X_FORWARDED_HOST', '192.168.1.*', '128.1.2.3')), - array('IPv6 with multiple proxies', array('[::1]', '[2001::b0b], [::ffff:192.168.1.10]', 'HTTP_X_FORWARDED_HOST', '::ffff:192.168.1.0/124', '[2001::b0b]')), - array('name with multiple proxies', array('dmz.example.com', 'www.example.com, dmz.example.com', 'HTTP_X_FORWARDED_HOST', 'dmz.example.com', 'www.example.com')), - ); - } - - /** - * @dataProvider getCurrentHosts - * @group Core - */ - public function testGetCurrentHost($description, $test) - { - $_SERVER['HTTP_HOST'] = $test[0]; - $_SERVER['HTTP_X_FORWARDED_HOST'] = $test[1]; - Config::getInstance()->General['proxy_host_headers'] = array($test[2]); - Config::getInstance()->General['proxy_ips'] = array($test[3]); - Config::getInstance()->General['enable_trusted_host_check'] = 0; - $this->assertEquals($test[4], Url::getCurrentHost(), $description); - } - - /** - * Dataprovider for testIsLocalUrl - */ - public function getLocalUrls() - { - return array( - // simple cases - array('www.example.com', 'http://www.example.com/path/index.php', '/path/index.php', 'http://www.example.com/path/index.php', true), - array('www.example.com', 'http://www.example.com/path/index.php?module=X', '/path/index.php', 'http://www.example.com/path/', true), - array('www.example.com', 'http://www.example.com/path/', '/path/index.php', 'http://www.example.com/path/index.php?module=Y', true), - array('www.example.com', 'http://www.example.com/path/#anchor', '/path/index.php', 'http://www.example.com/path/?query', true), - array('localhost:8080', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true), - array('www.example.com', 'http://www.example.com/path/', '/path/', 'http://www.example.com/path2/', true), - - // ignore port - array('www.example.com', 'http://www.example.com:80/path/index.php', '/path/index.php', 'http://www.example.com/path/index.php', true), - array('www.example.com', 'http://www.example.com/path/index.php', '/path/index.php', 'http://www.example.com:80/path/index.php', true), - - array('localhost', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true), - array('localhost', 'http://localhost/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true), - array('localhost', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost/path/index.php', true), - - array('localhost:8080', 'http://localhost/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true), - array('localhost:8080', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost/path/index.php', true), - array('localhost:8080', 'http://localhost/path/index.php', '/path/index.php', 'http://localhost/path/index.php', true), - array('localhost:8080', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true), - - // IPv6 - array('[::1]', 'http://[::1]/path/index.php', '/path/index.php', 'http://[::1]/path/index.php', true), - array('[::1]:8080', 'http://[::1]:8080/path/index.php', '/path/index.php', 'http://[::1]/path/index.php', true), - array('[::1]:8080', 'http://[::1]/path/index.php', '/path/index.php', 'http://[::1]:8080/path/index.php', true), - - // undefined SCRIPT URI - array('www.example.com', null, '/path/index.php', 'http://www.example.com/path/index.php', true), - array('localhost:8080', null, '/path/index.php', 'http://localhost:8080/path/index.php', true), - array('127.0.0.1:8080', null, '/path/index.php', 'http://127.0.0.1:8080/path/index.php', true), - array('[::1]', null, '/path/index.php', 'http://[::1]/path/index.php', true), - array('[::1]:8080', null, '/path/index.php', 'http://[::1]:8080/path/index.php', true), - - // Apache+Rails anomaly in SCRIPT_URI - array('www.example.com', 'http://www.example.com/path/#anchor', 'http://www.example.com/path/index.php', 'http://www.example.com/path/?query', true), - - // mangled HTTP_HOST - array('www.example.com', 'http://example.com/path/#anchor', '/path/index.php', 'http://example.com/path/referrer', true), - - // suppressed Referrer - array('www.example.com', 'http://www.example.com/path/#anchor', '/path/index.php', null, true), - array('www.example.com', 'http://www.example.com/path/#anchor', '/path/index.php', '', true), - - // mismatched scheme or host - array('www.example.com', 'http://www.example.com/path/?module=X', '/path/index.php', 'ftp://www.example.com/path/index.php', false), - array('www.example.com', 'http://www.example.com/path/?module=X', '/path/index.php', 'http://example.com/path/index.php', false), - array('www.example.com', 'http://www.example.com/path/', '/path/', 'http://crsf.example.com/path/', false), - ); - } - - /** - * @dataProvider getLocalUrls - * @group Core - */ - public function testIsLocalUrl($httphost, $scripturi, $requesturi, $testurl, $result) - { - $_SERVER['HTTP_HOST'] = $httphost; - $_SERVER['SCRIPT_URI'] = $scripturi; - $_SERVER['REQUEST_URI'] = $requesturi; - Config::getInstance()->General['enable_trusted_host_check'] = 1; - Config::getInstance()->General['trusted_hosts'] = array($httphost); - $urlToTest = $testurl; - $this->assertEquals($result, Url::isLocalUrl($urlToTest)); - } - - /** - * Dataprovider for testGetCurrentUrlWithoutFilename - */ - public function getCurrentUrlWithoutFilename() - { - return array( - array('http://example.com/', false, 'example.com', '/'), - array('https://example.org/', true, 'example.org', '/'), - array('https://example.net/piwik/', 'on', 'example.net', '/piwik/'), - ); - - } - - /** - * @dataProvider getCurrentUrlWithoutFilename - * @group Core - */ - public function testGetCurrentUrlWithoutFilename($expected, $https, $host, $path) - { - $names = array('PATH_INFO', 'REQUEST_URI', 'SCRIPT_NAME', 'SCRIPT_FILENAME', 'argv', 'HTTPS', 'HTTP_HOST', 'QUERY_STRING', 'HTTP_REFERER'); - - foreach ($names as $name) { - unset($_SERVER[$name]); - } - - if ($https) { - $_SERVER['HTTPS'] = $https; - } else { - unset($_SERVER['HTTPS']); - } - - $_SERVER['REQUEST_URI'] = $path; - $_SERVER['HTTP_HOST'] = $host; - - Config::getInstance()->General['trusted_hosts'] = array($host); - - $url = Url::getCurrentUrlWithoutFilename(); - $this->assertEquals($expected, $url); - } - - /** - * @group Core - */ - public function test_getCurrentScriptName() - { - $names = array('PATH_INFO', 'REQUEST_URI', 'SCRIPT_NAME', 'SCRIPT_FILENAME', 'argv', 'HTTPS', 'HTTP_HOST', 'QUERY_STRING', 'HTTP_REFERER'); - - foreach ($names as $name) { - unset($_SERVER[$name]); - } - - $tests = array( - array('/', 'http://example.com/', null), - array('/', '/', null), - array('/index.php', '/index.php', null), - array('/index.php', '/index.php?module=Foo', null), - array('/index.php', '/index.php/route/1', '/route/1'), - array('/index.php', '/index.php/route/2?module=Bar', '/route/2'), - array('/path/index.php', '/path/index.php/route/3/?module=Fu&action=Bar#Hash', '/route/3/'), - ); - - foreach ($tests as $test) { - list($expected, $uri, $pathInfo) = $test; - - $_SERVER['REQUEST_URI'] = $uri; - $_SERVER['PATH_INFO'] = $pathInfo; - - $scriptPathName = Url::getCurrentScriptName(); - $this->assertEquals($expected, $scriptPathName); - } - } - - /** - * Dataprovider for valid hosts - */ - public function getValidHostData() - { - return array( - // $expected, $host, $trustedHosts, $description - array(true, 'example.com', array('example.com'), 'Naked domain'), - array(true, 'example.net', array('example.com', 'example.net'), 'Multiple domains'), - array(true, 'piwik.example.com', array('piwik.example.com'), 'Fully qualified domain name'), - array(true, 'piwik.example.com', array('example.com'), 'Valid subdomain'), - array(false, 'example.net', array('example.com'), 'Invalid domain'), - array(false, '.example.com', array('piwik.example.com'), 'Invalid subdomain'), - array(false, 'example-com', array('example.com'), 'Regex should match . literally'), - array(false, 'www.attacker.com?example.com', array('example.com'), 'Spoofed host'), - array(false, 'example.com.attacker.com', array('example.com'), 'Spoofed subdomain'), - array(true, 'example.com.', array('example.com'), 'Trailing . on host is actually valid'), - array(true, 'www-dev.example.com', array('example.com'), 'host with dashes is valid'), - array(false, 'www.example.com:8080', array('example.com'), 'host:port is valid'), - array(true, 'www.example.com:8080', array('example.com:8080'), 'host:port is valid'), - array(false, 'www.whatever.com', array('*.whatever.com'), 'regex char is escaped'), - ); - } - - /** - * @dataProvider getValidHostData - * @group Core - */ - public function testIsValidHost($expected, $host, $trustedHosts, $description) - { - Config::getInstance()->General['enable_trusted_host_check'] = 1; - Config::getInstance()->General['trusted_hosts'] = $trustedHosts; - $this->assertEquals($expected, Url::isValidHost($host), $description); - } - - /** - * @group Core - */ - public function testGetReferrer() - { - $_SERVER['HTTP_REFERER'] = 'http://www.piwik.org'; - $this->assertEquals('http://www.piwik.org', Url::getReferrer()); - } - - /** - * @group Core - * - * @dataProvider getQueryParameters - */ - public function testGetQueryStringFromParameters($params, $queryString) - { - $this->assertEquals($queryString, Url::getQueryStringFromParameters($params)); - } - - public function getQueryParameters() - { - return array( - array(array(), ''), - array(array('v1', 'v2'), '0=v1&1=v2'), - array(array('key' => 'val'), 'key=val'), - array(array('key' => 'val', 'k2' => 'v2'), 'key=val&k2=v2'), - array(array('key' => 'val', 'k2' => false), 'key=val'), // remove false values - array(array('key' => 'val', 'k2' => null), 'key=val'), // remove null values - array(array('key' => 'val', 'k2' => array('v1', 'v2')), 'key=val&k2[]=v1&k2[]=v2'), - array(array('key' => 'val', 'k2' => array('k1' => 'v1', 'k2' => 'v2')), 'key=val&k2[]=v1&k2[]=v2'), - ); - } - - /** - * @group Core - * - * @dataProvider getHostsFromUrl - */ - public function testGetHostsFromUrl($url, $expectedHost) - { - $this->assertEquals($expectedHost, Url::getHostFromUrl($url)); - } - - public function getHostsFromUrl() - { - return array( - array(null, null), - array('http://', null), - array('http://www.example.com', 'www.example.com'), - array('http://www.ExaMplE.cOm', 'www.example.com'), - array('http://www.example.com/test/foo?bar=xy', 'www.example.com'), - array('http://127.0.0.1', '127.0.0.1'), - array('example.com', null), - ); - } - - /** - * @group Core - * - * @dataProvider getIsHostInUrls - */ - public function testIsHostInUrlsl($isHost, $host, $urls) - { - $this->assertEquals($isHost, Url::isHostInUrls($host, $urls)); - } - - public function getIsHostInUrls() - { - return array( - array(false, null, null), - array(false, 'http://', array()), - array(false, 'example.com', array()), - array(false, 'www.example.com', array()), - array(false, 'example.com', array('www.example.com')), // not a domain so no "host" - array(true, 'example.com', array('example.com')), - array(true, 'eXamPle.com', array('exaMple.com')), - array(true, 'eXamPle.com', array('http://exaMple.com')), - array(true, 'eXamPle.com', array('http://piwik.org', 'http://www.exaMple.com', 'http://exaMple.com')), // multiple urls one or more are valid but not first one - array(true, 'example.com', array('http://example.com/test')), // url with path but correct host - array(true, 'example.com', array('http://www.example.com')), // subdomains are allowed - array(false, 'example.com', array('http://wwwexample.com')), // it should not be possible to create a similar host and make redirects work again. we allow only subdomains - array(true, 'example.com', array('http://ftp.exAmple.com/test')), - array(true, 'example.com', array('http://www.exAmple.com/test')), - array(false, 'ftp.example.com', array('http://www.example.com/test')), - array(true, '127.0.0.1', array()), // always trusted host - ); - } - -} |