Prune remote files part 39
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tests/PHPUnit/Unit/Translation/Loader/LoaderCacheTest.phpDeleted-73
- tests/PHPUnit/Unit/Translation/Loader/fixtures/dir1/en.jsonDeleted-6
- tests/PHPUnit/Unit/Translation/Loader/fixtures/dir1/fr.jsonDeleted-5
- tests/PHPUnit/Unit/Translation/Loader/fixtures/dir2/en.jsonDeleted-6
- tests/PHPUnit/Unit/Translation/TranslatorTest.phpDeleted-157
- tests/PHPUnit/Unit/TwigTest.phpDeleted-65
- tests/PHPUnit/Unit/UpdateCheckTest.phpDeleted-240
- tests/PHPUnit/Unit/UrlHelperTest.phpDeleted-371
- tests/PHPUnit/Unit/UrlTest.phpDeleted-684
- tests/PHPUnit/Unit/Validator/CharacterLengthTest.phpDeleted-58
- tests/PHPUnit/Unit/Validator/DateTimeTest.phpDeleted-76
- tests/PHPUnit/Unit/Validator/EmailTest.phpDeleted-69
- tests/PHPUnit/Unit/Validator/IpRangesTest.phpDeleted-48
- tests/PHPUnit/Unit/Validator/NotEmptyTest.phpDeleted-53
- tests/PHPUnit/Unit/Validator/NumberRangeTest.phpDeleted-77
- tests/PHPUnit/Unit/Validator/UrlLikeTest.phpDeleted-87
- tests/PHPUnit/Unit/Validator/WhiteListedValueTest.phpDeleted-64
- tests/PHPUnit/Unit/VersionTest.phpDeleted-210
- tests/PHPUnit/Unit/Visualization/SparklineTest.phpDeleted-191
- tests/PHPUnit/Unit/Widget/WidgetConfigTest.phpDeleted-236
- tests/PHPUnit/Unit/Widget/WidgetContainerConfigTest.phpDeleted-300
- tests/PHPUnit/Unit/Widget/WidgetsListTest.phpDeleted-177
- tests/PHPUnit/bootstrap.phpDeleted-170
- tests/PHPUnit/phpunit.xml.distDeleted-96
- tests/PHPUnit/proxy/archive.phpDeleted-13
- tests/PHPUnit/proxy/consoleDeleted-11
- tests/PHPUnit/proxy/includes.phpDeleted-23
- tests/PHPUnit/proxy/index.phpDeleted-15
- tests/PHPUnit/proxy/matomo.phpDeleted-9
- tests/PHPUnit/proxy/nodispatchnotinstalled.phpDeleted-20
- tests/PHPUnit/proxy/piwik.phpDeleted-48
- tests/README.mdDeleted-6
- tests/README.screenshots.mdDeleted-6
- tests/README.testing-data.mdDeleted-1
- tests/README.troubleshooting.mdDeleted-3
- tests/UI/.gitignoreDeleted-10
- tests/UI/config.dist.jsDeleted-76
- tests/UI/expected-screenshots/BarGraph_load.pngDeleted
- tests/UI/expected-screenshots/BarGraph_load_fail_when_token_used.pngDeleted
- tests/UI/expected-screenshots/BarGraph_metric_picker_shown.pngDeleted
- tests/UI/expected-screenshots/BarGraph_other_metric.pngDeleted
- tests/UI/expected-screenshots/Comparison_bar_graph.pngDeleted
- tests/UI/expected-screenshots/Comparison_dashboard_last_period.pngDeleted
- tests/UI/expected-screenshots/Comparison_dashboard_last_period_and_segment.pngDeleted
- tests/UI/expected-screenshots/Comparison_goals_table.pngDeleted
- tests/UI/expected-screenshots/Comparison_goals_table_specific.pngDeleted
- tests/UI/expected-screenshots/Comparison_multi_row_evolution.pngDeleted
- tests/UI/expected-screenshots/Comparison_normal_table.pngDeleted
- tests/UI/expected-screenshots/Comparison_normal_table_no_periods.pngDeleted
- tests/UI/expected-screenshots/Comparison_normal_table_no_segments.pngDeleted
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Translation\Loader;
use Matomo\Cache\Backend\ArrayCache;use Matomo\Cache\Lazy;use Piwik\Translation\Loader\LoaderCache;
/** * @group Translation */class LoaderCacheTest extends \PHPUnit\Framework\TestCase{ public function testShouldNotLoadIfInCache() { $cache = $this->getMockBuilder('Matomo\Cache\Lazy')->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('fetch') ->willReturn(array('translations!')); $wrappedLoader = $this->getMockForAbstractClass('Piwik\Translation\Loader\LoaderInterface'); $wrappedLoader->expects($this->never()) ->method('load');
$loader = new LoaderCache($wrappedLoader, $cache); $translations = $loader->load('en', array('foo'));
$this->assertEquals(array('translations!'), $translations); }
public function testShouldLoadIfNotInCache() { $cache = $this->getMockBuilder('Matomo\Cache\Lazy')->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('fetch') ->willReturn(null); $wrappedLoader = $this->getMockForAbstractClass('Piwik\Translation\Loader\LoaderInterface'); $wrappedLoader->expects($this->once()) ->method('load') ->with('en', array('foo')) ->willReturn(array('translations!'));
$loader = new LoaderCache($wrappedLoader, $cache); $translations = $loader->load('en', array('foo'));
$this->assertEquals(array('translations!'), $translations); }
public function testShouldReLoadIfDifferentDirectories() { $cache = new Lazy(new ArrayCache());
$wrappedLoader = $this->getMockForAbstractClass('Piwik\Translation\Loader\LoaderInterface'); $wrappedLoader->expects($this->exactly(2)) ->method('load') ->willReturn(array('translations!'));
$loader = new LoaderCache($wrappedLoader, $cache);
// Should call the wrapped loader only once $loader->load('en', array('foo')); $loader->load('en', array('foo'));
// Should call the wrapped loader a second time $loader->load('en', array('foo', 'bar')); }}123456{ "General": { "test1": "Hello", "test2": "Hello" }}12345{ "General": { "test1": "Bonjour" }}123456{ "General": { "test2": "Hello 2", "test3": "Hello 3" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Translation;
use Piwik\Translation\Loader\JsonFileLoader;use Piwik\Translation\Translator;
/** * @group Translation */class TranslatorTest extends \PHPUnit\Framework\TestCase{ public function testTranslateShouldReturnTranslationIdIfNoTranslationFound() { $loader = $this->createLoader(); $translator = new Translator($loader, array());
$this->assertEquals('General_foo', $translator->translate('General_foo')); }
public function testTranslateShouldReturnTranslation() { $loader = $this->createLoader(array( 'General' => array( 'foo' => 'Hello world', ), )); $translator = new Translator($loader, array());
$this->assertEquals('Hello world', $translator->translate('General_foo')); }
public function testTranslateShouldReplacePlaceholders() { $loader = $this->createLoader(array( 'General' => array( 'foo' => 'Hello %s', ), )); $translator = new Translator($loader, array());
$this->assertEquals('Hello John', $translator->translate('General_foo', 'John')); }
public function testTranslateWithADifferentLanguage() { $translator = new Translator(new JsonFileLoader(), array(__DIR__ . '/Loader/fixtures/dir1'));
$this->assertEquals('Hello', $translator->translate('General_test1'));
$translator->setCurrentLanguage('fr'); $this->assertEquals('fr', $translator->getCurrentLanguage()); $this->assertEquals('Bonjour', $translator->translate('General_test1')); }
public function testTranslateShouldFallbackIfTranslationNotFound() { $translator = new Translator(new JsonFileLoader(), array(__DIR__ . '/Loader/fixtures/dir1')); $translator->setCurrentLanguage('fr'); $this->assertEquals('Hello', $translator->translate('General_test2')); }
public function testAddDirectoryShouldImportNewTranslations() { $translator = new Translator(new JsonFileLoader(), array(__DIR__ . '/Loader/fixtures/dir1')); // translation not found $this->assertEquals('General_test3', $translator->translate('General_test3'));
$translator->addDirectory(__DIR__ . '/Loader/fixtures/dir2'); // translation is now found $this->assertEquals('Hello 3', $translator->translate('General_test3')); }
public function testAddDirectoryShouldImportOverExistingTranslations() { $translator = new Translator(new JsonFileLoader(), array(__DIR__ . '/Loader/fixtures/dir1')); $this->assertEquals('Hello', $translator->translate('General_test2'));
$translator->addDirectory(__DIR__ . '/Loader/fixtures/dir2'); $this->assertEquals('Hello 2', $translator->translate('General_test2')); }
/** * @dataProvider getAndListingData */ public function testCreateAndListing(array $items, string $language, string $expectedResult) { $translator = new Translator(new JsonFileLoader(), array(PIWIK_INCLUDE_PATH . '/plugins/Intl/lang'));
self::assertEquals($expectedResult, $translator->createAndListing($items, $language)); }
public function getAndListingData(): array { return [ [[], 'en', ''], [['1'], 'en', '1'], [['1', '2'], 'en', '1 and 2'], [['1', '2'], 'cs', '1 a 2'], [['1', '2'], 'de', '1 und 2'], // note: we currently use (american) english, so a comma before the and is correct // british english doesn't have that [['1', '2', '3'], 'en', '1, 2, and 3'], [['1', '2', '3', '4'], 'en', '1, 2, 3, and 4'], [['1', '2', '3'], 'cs', '1, 2 a 3'], [['1', '2', '3'], 'de', '1, 2 und 3'], [['1', '2', '3', '4'], 'de', '1, 2, 3 und 4'], [['1', '2', '3', '4'], 'am', '1፣ 2፣ 3 እና 4'], ]; }
/** * @dataProvider getOrListingData */ public function testCreateOrListing(array $items, string $language, string $expectedResult) { $translator = new Translator(new JsonFileLoader(), array(PIWIK_INCLUDE_PATH . '/plugins/Intl/lang'));
self::assertEquals($expectedResult, $translator->createOrListing($items, $language)); }
public function getOrListingData(): array { return [ [[], 'en', ''], [['1'], 'en', '1'], [['1', '2'], 'en', '1 or 2'], [['1', '2'], 'cs', '1 nebo 2'], [['1', '2'], 'de', '1 oder 2'], // note: we currently use (american) english, so a comma before the or is correct // british english doesn't have that [['1', '2', '3'], 'en', '1, 2, or 3'], [['1', '2', '3', '4'], 'en', '1, 2, 3, or 4'], [['1', '2', '3'], 'cs', '1, 2 nebo 3'], [['1', '2', '3'], 'de', '1, 2 oder 3'], [['1', '2', '3', '4'], 'de', '1, 2, 3 oder 4'], [['1', '2', '3', '4'], 'am', '1፣ 2፣ 3 ወይም 4'], ]; }
private function createLoader(array $translations = array()) { $loader = $this->getMockForAbstractClass('Piwik\Translation\Loader\LoaderInterface'); $loader->expects($this->any()) ->method('load') ->willReturn($translations);
return $loader; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit;
use Piwik\Twig;
require_once(PIWIK_INCLUDE_PATH . '/core/Twig.php');
/** * @group Twig */class TwigTest extends \PHPUnit\Framework\TestCase{ /** * @dataProvider getTruncateTests */ public function testPiwikFilterTruncate($in, $size, $out) { $truncated = \Piwik\piwik_filter_truncate($in, $size); $this->assertEquals($out, $truncated); }
public function getTruncateTests() { return [ ['abc', 4, 'abc'], ['abc"', 4, 'abc"'], ['abc ', 4, 'abc '], ['abcdef', 3, 'abc...'], ['ab&ef', 3, 'ab&...'], ['some▼thing', 5, 'some▼...'], ['ab&ef ;', 3, 'ab&...'], ['<>▼ ', 4, '<>▼ '], ]; }
/** * @dataProvider getPreventLinkingTests */ public function testFilterPreventLinking($in, $out) { $twig = new Twig(); $preventFilter = $twig->getTwigEnvironment()->getFilter('preventLinking'); $this->assertEquals($out, $preventFilter->getCallable()($in)); }
public function getPreventLinkingTests(): iterable { return [ ['abc<!$%&', 'abc<!$%&'], ['abc...', 'abc...'], ['abc. test;', 'abc. test;'], ['abc.fgh', 'abc.<!-- -->fgh'], ['www.google.com', 'www.<!-- -->google.<!-- -->com'], ['www..google.com', 'www..google.<!-- -->com'], ]; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
declare(strict_types=1);
namespace Piwik\Tests\Unit;
use Exception;use PHPUnit\Framework\MockObject\MockObject;use PHPUnit\Framework\TestCase;use Piwik\Config;use Piwik\Container\StaticContainer;use Piwik\EventDispatcher;use Piwik\Option;use Piwik\Plugin\ReleaseChannels;use Piwik\UpdateCheck;use Piwik\UpdateCheck\ReleaseChannel;use Piwik\Version;use stdClass;
/** * @group Core * @group UpdateCheck */class UpdateCheckTest extends TestCase{ private const RELEASE_VERSION = '1.2.3';
/** * @var MockObject&Option */ private $mockOptions;
/** * @var mixed */ private $originalAutoUpdateConfig;
/** * @var mixed */ private $originalReleaseChannels;
public function setUp(): void { parent::setUp();
$this->originalAutoUpdateConfig = Config::getInstance()->General['enable_auto_update'] ?? null; $this->originalReleaseChannels = StaticContainer::getContainer()->get('\Piwik\Plugin\ReleaseChannels');
Config::getInstance()->General['enable_auto_update'] = true;
$this->mockOptions = $this->getMockBuilder(stdClass::class) ->addMethods(['getValue', 'setValue']) ->getMock();
Option::setSingletonInstance($this->mockOptions);
$releaseChannel = $this->createConfiguredMock( ReleaseChannel::class, [ 'getUrlToCheckForLatestAvailableVersion' => 'https://matomo.org', ] );
$releaseChannels = $this->createconfiguredMock( ReleaseChannels::class, [ 'getActiveReleaseChannel' => $releaseChannel, ] );
StaticContainer::getContainer()->set('\Piwik\Plugin\ReleaseChannels', $releaseChannels); }
public function tearDown(): void { Option::setSingletonInstance(null); StaticContainer::getContainer()->set('\Piwik\Plugin\ReleaseChannels', $this->originalReleaseChannels);
Config::getInstance()->General['enable_auto_update'] = $this->originalAutoUpdateConfig;
parent::tearDown(); }
public function testCheckDoesNothingIfAutoUpdateIsNotEnabled(): void { Config::getInstance()->General['enable_auto_update'] = false;
$this->mockOptions ->expects(self::never()) ->method('getValue');
UpdateCheck::check(); }
public function testCheckDoesNothingIfInsideCheckIntervalAndNotForced(): void { $this->mockOptions ->expects(self::once()) ->method('getValue') ->with(UpdateCheck::LAST_TIME_CHECKED) ->willReturn((string) time());
$this->mockOptions ->expects(self::never()) ->method('setValue');
UpdateCheck::check(false, 86400); }
/** * @dataProvider dataCheckRunsIfForcedOrWithinInterval * * @param false|string $lastTimeChecked */ public function testCheckRunsIfForcedOrWithinInterval( bool $forced, $lastTimeChecked, int $interval ): void { $this->mockOptions ->expects(self::once()) ->method('getValue') ->with(UpdateCheck::LAST_TIME_CHECKED) ->willReturn($lastTimeChecked);
$this->mockOptions ->expects(self::exactly(3)) ->method('setValue') ->withConsecutive( [UpdateCheck::LAST_TIME_CHECKED, self::greaterThan(0)], [UpdateCheck::LAST_CHECK_FAILED, false], [UpdateCheck::LATEST_VERSION, self::RELEASE_VERSION] );
EventDispatcher::getInstance()->addObserver( 'Http.sendHttpRequest', static function ($aUrl, $httpEventParams, &$response) { $response = self::RELEASE_VERSION; } );
UpdateCheck::check($forced, $interval); }
/** * @return iterable<string, array{bool, false|string, int}> */ public function dataCheckRunsIfForcedOrWithinInterval(): iterable { yield 'forced' => [true, (string) time(), 86400]; yield 'never checked before' => [false, false, 86400]; yield 'interval exceeded' => [false, (string) (time() - 86400), 3600]; }
public function testCheckDoesNotSetNewLatestVersionIfHttpRequestFails(): void { $lastTimeChecked = 123456;
$this->mockOptions ->expects(self::once()) ->method('getValue') ->with(UpdateCheck::LAST_TIME_CHECKED) ->willReturn($lastTimeChecked);
$this->mockOptions ->expects(self::exactly(3)) ->method('setValue') ->withConsecutive( [UpdateCheck::LAST_TIME_CHECKED, self::greaterThan(0)], [UpdateCheck::LAST_CHECK_FAILED, true], [UpdateCheck::LAST_TIME_CHECKED, $lastTimeChecked] );
EventDispatcher::getInstance()->addObserver( 'Http.sendHttpRequest', static function () { throw new Exception('test'); } );
UpdateCheck::check(true); }
public function testGetLatestVersion(): void { $this->mockOptions ->expects(self::once()) ->method('getValue') ->with(UpdateCheck::LATEST_VERSION) ->willReturn(self::RELEASE_VERSION);
self::assertSame(self::RELEASE_VERSION, UpdateCheck::getLatestVersion()); }
public function testHasLastCheckFailed(): void { $this->mockOptions ->expects(self::once()) ->method('getValue') ->with(UpdateCheck::LAST_CHECK_FAILED) ->willReturn('1');
self::assertTrue(UpdateCheck::hasLastCheckFailed()); }
/** * @dataProvider dataIsNewestVersionAvailable * * @param false|string $expectedResult */ public function testIsNewestVersionAvailable($expectedResult, string $compareTo): void { $this->mockOptions ->expects(self::once()) ->method('getValue') ->with(UpdateCheck::LATEST_VERSION) ->willReturn($compareTo);
self::assertSame($expectedResult, UpdateCheck::isNewestVersionAvailable()); }
/** * @return iterable<string, array{bool, string}> */ public function dataIsNewestVersionAvailable(): iterable { yield 'empty version' => [false, '']; yield 'older version' => [false, '1.0.0']; yield 'same version' => [false, Version::VERSION]; yield 'newer version' => ['99.99.99', '99.99.99']; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit;
use Piwik\UrlHelper;
/** * @group UrlHelperTest */class 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 array('news://www.javascript.org', true),
array('rtp://whatever.com', true), array('testhttp://test.com', true), array('cylon://3.hmn', true), array('://something.com', true),
// valid network-path reference RFC3986 array('//piwik.org', true), array('//piwik/hello?world=test&test', true), array('//piwik.org/hello?world=test&test', true),
// invalid urls array('it doesnt look like url', false), array('/index?page=test', false), array('http:/index?page=test', false), array('http/index?page=test', false), array('test.html', false), array('/\/\/\/\/\/\\\http://test.com////', false), array('jmleslangues.php', false), array('http://', false), array(' http://', false), array('2fer://', false), array('javascript://test.com/test', false), array('javascript://alert', false), array('vbscript://alert', false), array('vbscript://alert', false), array('data://example.com/test', false), array('jaVascRipt://test.com/test', false), array('VBscrIpt://alert', false), array('dAtA://example.com/test', false), ); }
/** * @dataProvider getUrls * @group Core */ public function testIsUrl($url, $isValid) { $this->assertEquals($isValid, UrlHelper::isLookLikeUrl($url), "$url failed test"); }
/** * @dataProvider getTestDataForIsLookLikeSafeUrl */ public function testIsLookLikeSafeUrl($url, $isSafe) { $this->assertEquals($isSafe, UrlHelper::isLookLikeSafeUrl($url)); }
public function getTestDataForIsLookLikeSafeUrl() { return [ // valid 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('tel:12345', true), array('sms:456543', true),
// invalid array('rtp://whatever.com', false), array('testhttp://test.com', false), array('cylon://3.hmn', false), array('://something.com', false), array('data://example.com/test', false), array('jaVascRipt://test.com/test', false), array('VBscrIpt://alert', false), array('dAtA://example.com/test', false), array('data://tel.org/http', false), array('smstest:456543', false), array(urldecode('javascript://%0D%0Aalert(1)'), false), array(urldecode('http://%0D%0Aalert(1)'), false), ]; }
/** * 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'));
// Add parameters to existing params $this->assertEquals( 'test/index.php?module=CoreHome&abc=123&def=456', UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php?module=CoreHome', ['abc' => '123', 'def' => '456']) );
// Add parameters with no existing params $this->assertEquals( 'test/index.php?abc=123&def=456', UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php', ['abc' => '123', 'def' => '456']) );
// Preserve anchor $this->assertEquals( 'test/index.php#anchor', UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php#anchor', [], true) );
// Do not preserve anchor $this->assertEquals( 'test/index.php', UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php#anchor', [], false) );
// Add parameters with existing params, preserve anchor $this->assertEquals( 'test/index.php#anchor?abc=123&def=456', UrlHelper::getPathAndQueryFromUrl('http://piwik.org/test/index.php#anchor', ['abc' => '123', 'def' => '456'], true) ); }
/** * @group Core */ public function testGetPathAndQueryFromNonUrl() { $this->assertEquals('Others', UrlHelper::getPathAndQueryFromUrl('Others')); }
/** * @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 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)); }
/** * @group Core */ public function testGetHostFromUrl() { $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')); $this->assertEquals('localhost', UrlHelper::getHostFromUrl('//localhost/path')); $this->assertEquals('localhost', UrlHelper::getHostFromUrl('//localhost/path?test=test2')); $this->assertEquals('example.org', UrlHelper::getHostFromUrl('//example.org/path')); $this->assertEquals('example.org', UrlHelper::getHostFromUrl('//example.org/path?test=test2')); }
/** * @group Core */ public function testGetQueryFromUrlShouldReturnEmtpyStringIfNoQuery() { $this->assertEquals('', UrlHelper::getQueryFromUrl('', array())); $this->assertEquals('', UrlHelper::getQueryFromUrl(null, array())); $this->assertEquals('', UrlHelper::getQueryFromUrl('http://localhost/path', array())); }
/** * @group Core */ public function testGetQueryFromUrlShouldReturnOnlyTheQueryPartOfTheUrlIfNoAdditionalParamsGiven() { $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())); }
public function testGetQueryFromUrlWhenUrlParameterIsDuplicatedInQueryStringReturnsLastFoundValue() { // Currently when the same parameter is used several times in the query string, // only the last set value is returned by UrlHelper::getParameterFromQueryString // refs https://github.com/piwik/piwik/issues/9842#issue-136043409 $this->assertEquals('blue', UrlHelper::getParameterFromQueryString('selected_colors=red&selected_colors=blue&par3=1', 'selected_colors')); $this->assertEquals('selected_colors=red&selected_colors=blue&par3=1', UrlHelper::getQueryFromUrl('http:/mydomain.com?selected_colors=red&selected_colors=blue&par3=1', array())); }
/** * @group Core */ public function testGetQueryFromUrlShouldAddAdditionalParamsIfGiven() { $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')))); }
/** * Dataprovider for testGetQueryStringWithExcludedParameters */ public function getQueryParameters() { return array( array( 'p1=v1&p2=v2', //expected array('p1' => 'v1', 'p2' => 'v2'), //queryParameters array(), //parametersToExclude ), array( 'p2=v2', array('p1' => 'v1', 'p2' => 'v2'), array('p1'), ), array( 'p1=v1&p2=v2', array('p1' => 'v1', 'p2' => 'v2', 'sessionId' => 'HHSJHERTG'), array('sessionId'), ), array( 'p1=v1&p2=v2', array('p1' => 'v1', 'p2' => 'v2', 'sessionId' => 'HHSJHERTG'), array('/session/'), ), array( 'p1=v1&p2=v2', array('p1' => 'v1', 'sessionId' => 'HHSJHERTG', 'p2' => 'v2', 'token' => 'RYUN36HSAO'), array('/[session|token]/'), ), array( '', array('p1' => 'v1', 'p2' => 'v2', 'sessionId' => 'HHSJHERTG', 'token' => 'RYUN36HSAO'), array('/.*/'), ), array( 'p2=v2&p4=v4', array('p1' => 'v1', 'p2' => 'v2', 'p3' => 'v3', 'p4' => 'v4'), array('/p[1|3]/'), ), array( 'p2=v2&p4=v4', array('p1' => 'v1', 'p2' => 'v2', 'p3' => 'v3', 'p4' => 'v4', 'utm_source' => 'gekko', 'utm_medium' => 'email', 'utm_campaign' => 'daily'), array('/p[1|3]/', '/utm_/'), ), ); }
/** * @dataProvider getQueryParameters * @group Core */ public function testGetQueryStringWithExcludedParameters($expected, $queryParameters, $parametersToExclude) { $this->assertEquals($expected, UrlHelper::getQueryStringWithExcludedParameters($queryParameters, $parametersToExclude)); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit;
use Piwik\Config;use Piwik\Url;
/** * @backupGlobals enabled * @group Core * @group UrlTest */class UrlTest extends \PHPUnit\Framework\TestCase{ public function testAllMethods() { $this->assertEquals(Url::getCurrentQueryStringWithParametersModified([]), 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 = []; foreach ($parameters as $name) { $parametersNameToValue[$name] = null; } $this->assertEquals('', Url::getCurrentQueryStringWithParametersModified($parametersNameToValue)); }
/** * Dataprovider for testGetCurrentHost() */ public function getCurrentHosts() { return [ ['localhost IPv4', ['127.0.0.1', null, null, null, '127.0.0.1']], ['localhost IPv6', ['[::1]', null, null, null, '[::1]']], ['localhost name', ['localhost', null, null, null, 'localhost']],
['IPv4 without proxy', ['128.1.2.3', null, null, null, '128.1.2.3']], ['IPv6 without proxy', ['[2001::b0b]', null, null, null, '[2001::b0b]']], ['name without proxy', ['example.com', null, null, null, 'example.com']],
['IPv4 with one proxy', ['127.0.0.1', '128.1.2.3', 'HTTP_X_FORWARDED_HOST', null, '128.1.2.3']], ['IPv6 with one proxy', ['[::1]', '[2001::b0b]', 'HTTP_X_FORWARDED_HOST', null, '[2001::b0b]']], ['name with one IPv4 proxy', ['192.168.1.10', 'example.com', 'HTTP_X_FORWARDED_HOST', null, 'example.com']], ['name with one IPv6 proxy', ['[::10]', 'www.example.com', 'HTTP_X_FORWARDED_HOST', null, 'www.example.com']], ['name with one named proxy', ['dmz.example.com', 'www.example.com', 'HTTP_X_FORWARDED_HOST', null, 'www.example.com']],
['IPv4 with multiple proxies', ['127.0.0.1', '128.1.2.3, 192.168.1.10', 'HTTP_X_FORWARDED_HOST', '192.168.1.*', '128.1.2.3']], ['IPv6 with multiple proxies', ['[::1]', '[2001::b0b], [::ffff:192.168.1.10]', 'HTTP_X_FORWARDED_HOST', '::ffff:192.168.1.0/124', '[2001::b0b]']], ['name with multiple proxies', ['dmz.example.com', 'www.example.com, dmz.example.com', 'HTTP_X_FORWARDED_HOST', 'dmz.example.com', 'www.example.com']], ]; }
/** * @dataProvider getCurrentHosts */ public function testGetCurrentHost($description, $test) { Url::setHost($test[0]); $_SERVER['HTTP_X_FORWARDED_HOST'] = $test[1]; Config::getInstance()->General['proxy_host_headers'] = [$test[2]]; Config::getInstance()->General['proxy_ips'] = [$test[3]]; Config::getInstance()->General['enable_trusted_host_check'] = 0; $this->assertEquals($test[4], Url::getCurrentHost(), $description); }
public function testGetHostWithTrustedHosts() { Config::getInstance()->General['enable_trusted_host_check'] = 1; Config::getInstance()->General['trusted_hosts'] = ['example.com','stats.example.com']; $_SERVER['HTTP_HOST'] = null;
$this->assertEquals('example.com', Url::getHost()); }
/** * @dataProvider getProtocol */ public function testGetCurrentSchemeProtoHeaderShouldPrecedenceHttpsHeader($proto) { $_SERVER['HTTPS'] = 'on'; $_SERVER['HTTP_X_FORWARDED_PROTO'] = $proto; Config::getInstance()->General['proxy_scheme_headers'] = ['HTTP_X_FORWARDED_PROTO']; $this->assertEquals($proto, Url::getCurrentScheme());
unset($_SERVER['HTTP_X_FORWARDED_PROTO']); unset($_SERVER['HTTPS']); Config::getInstance()->General['proxy_scheme_headers'] = null; }
public function testGetCurrentSchemeIgnoresProxyHeaderWhenNotConfigured() { $_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https'; Config::getInstance()->General['proxy_scheme_headers'] = null;
$this->assertEquals('http', Url::getCurrentScheme());
unset($_SERVER['HTTP_X_FORWARDED_PROTO']); }
public function testGetCurrentSchemeIgnoresProxyHeaderWhenNotConfigured2() { $_SERVER['HTTPS'] = 'on'; $_SERVER['HTTP_X_FORWARDED_PROTO'] = 'http'; Config::getInstance()->General['proxy_scheme_headers'] = null;
$this->assertEquals('https', Url::getCurrentScheme());
unset($_SERVER['HTTPS']); unset($_SERVER['HTTP_X_FORWARDED_PROTO']); }
/** * @dataProvider getProtocol */ public function testGetCurrentSchemeShouldDetectSecureFromHttpsHeader() { $_SERVER['HTTPS'] = 'on'; Config::getInstance()->General['proxy_scheme_headers'] = null; $this->assertEquals('https', Url::getCurrentScheme());
unset($_SERVER['HTTPS']); }
/** * @dataProvider getProtocol */ public function testGetCurrentSchemeShouldBeHttpByDefault() { Config::getInstance()->General['proxy_scheme_headers'] = null; $this->assertEquals('http', Url::getCurrentScheme()); }
public function getProtocol() { return [['http'], ['https']]; }
/** * Dataprovider for testIsLocalUrl */ public function getLocalUrls() { return [ // simple cases ['www.example.com', 'http://www.example.com/path/index.php', '/path/index.php', 'http://www.example.com/path/index.php', true], ['www.example.com', 'http://www.example.com/path/index.php?module=X', '/path/index.php', 'http://www.example.com/path/', true], ['www.example.com', 'http://www.example.com/path/', '/path/index.php', 'http://www.example.com/path/index.php?module=Y', true], ['www.example.com', 'http://www.example.com/path/#anchor', '/path/index.php', 'http://www.example.com/path/?query', true], ['localhost:8080', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true], ['www.example.com', 'http://www.example.com/path/', '/path/', 'http://www.example.com/path2/', true],
// ignore port ['www.example.com', 'http://www.example.com:80/path/index.php', '/path/index.php', 'http://www.example.com/path/index.php', true], ['www.example.com', 'http://www.example.com/path/index.php', '/path/index.php', 'http://www.example.com:80/path/index.php', true],
['localhost', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true], ['localhost', 'http://localhost/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true], ['localhost', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost/path/index.php', true],
['localhost:8080', 'http://localhost/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true], ['localhost:8080', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost/path/index.php', true], ['localhost:8080', 'http://localhost/path/index.php', '/path/index.php', 'http://localhost/path/index.php', true], ['localhost:8080', 'http://localhost:8080/path/index.php', '/path/index.php', 'http://localhost:8080/path/index.php', true],
// IPv6 ['[::1]', 'http://[::1]/path/index.php', '/path/index.php', 'http://[::1]/path/index.php', true], ['[::1]:8080', 'http://[::1]:8080/path/index.php', '/path/index.php', 'http://[::1]/path/index.php', true], ['[::1]:8080', 'http://[::1]/path/index.php', '/path/index.php', 'http://[::1]:8080/path/index.php', true],
// undefined SCRIPT URI ['www.example.com', null, '/path/index.php', 'http://www.example.com/path/index.php', true], ['localhost:8080', null, '/path/index.php', 'http://localhost:8080/path/index.php', true], ['127.0.0.1:8080', null, '/path/index.php', 'http://127.0.0.1:8080/path/index.php', true], ['[::1]', null, '/path/index.php', 'http://[::1]/path/index.php', true], ['[::1]:8080', null, '/path/index.php', 'http://[::1]:8080/path/index.php', true],
// Apache+Rails anomaly in SCRIPT_URI ['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 ['www.example.com', 'http://example.com/path/#anchor', '/path/index.php', 'http://example.com/path/referrer', true],
// suppressed Referrer ['www.example.com', 'http://www.example.com/path/#anchor', '/path/index.php', null, true], ['www.example.com', 'http://www.example.com/path/#anchor', '/path/index.php', '', true],
// mismatched scheme or host ['www.example.com', 'http://www.example.com/path/?module=X', '/path/index.php', 'ftp://www.example.com/path/index.php', false], ['www.example.com', 'http://www.example.com/path/?module=X', '/path/index.php', 'http://example.com/path/index.php', false], ['www.example.com', 'http://www.example.com/path/', '/path/', 'http://crsf.example.com/path/', false], ]; }
/** * @dataProvider getIsLocalHost */ public function testIsLocalHost($expectedIsLocal, $host) { $this->assertSame($expectedIsLocal, Url::isLocalHost($host)); }
public function getIsLocalHost() { return [ [$isLocal = false, '127.0.0.2'], [$isLocal = false, '192.168.1.1'], [$isLocal = false, '10.1.1.1'], [$isLocal = false, '172.30.1.1'],
[$isLocal = true, 'localhost'], [$isLocal = true, '127.0.0.1'], [$isLocal = true, '::1'], [$isLocal = true, '[::1]'],
// with port [$isLocal = false, '172.30.1.1:80'], [$isLocal = false, '3ffe:1900:4545:3:200:f8ff:fe21:67cf:1005'], [$isLocal = true, 'localhost:3000'], [$isLocal = true, '127.0.0.1:213424'], [$isLocal = true, '::1:345'], [$isLocal = true, '[::1]:443'], ]; }
/** * @dataProvider getLocalUrls */ public function testIsLocalUrl($httphost, $scripturi, $requesturi, $testurl, $result) { Url::setHost($httphost); $_SERVER['SCRIPT_URI'] = $scripturi; $_SERVER['REQUEST_URI'] = $requesturi; Config::getInstance()->General['enable_trusted_host_check'] = 1; Config::getInstance()->General['trusted_hosts'] = [$httphost]; $urlToTest = $testurl; $this->assertEquals($result, Url::isLocalUrl($urlToTest)); }
/** * Dataprovider for testGetCurrentUrlWithoutFilename */ public function getCurrentUrlWithoutFilename() { return [ ['http://example.com/', false, 'example.com', '/'], ['https://example.org/', true, 'example.org', '/'], ['https://example.net/piwik/', 'on', 'example.net', '/piwik/'], ]; }
/** * @dataProvider getCurrentUrlWithoutFilename */ public function testGetCurrentUrlWithoutFilename($expected, $https, $host, $path) { $this->resetGlobalVariables();
if ($https) { $_SERVER['HTTPS'] = $https; } else { unset($_SERVER['HTTPS']); }
$_SERVER['REQUEST_URI'] = $path; $_SERVER['HTTP_HOST'] = $host;
Config::getInstance()->General['trusted_hosts'] = [$host];
$url = Url::getCurrentUrlWithoutFilename(); $this->assertEquals($expected, $url); }
public function testGetCurrentScriptName() { $this->resetGlobalVariables();
$tests = [ ['/', 'http://example.com/', null], ['/', '/', null], ['/index.php', '/index.php', null], ['/index.php', '/index.php?module=Foo', null], ['/index.php', '/index.php/route/1', '/route/1'], ['/index.php', '/index.php#<img src=http://matomo.org', ''], ['/index.php', '/index.php/route/2?module=Bar', '/route/2'], ['/path/index.php', '/path/index.php/route/3/?module=Fu&action=Bar#Hash', '/route/3/'], // Current directory resolution ['/index.php', '/./index.php', null], ['/index.php', './index.php', null], ['/foo/index.php', '/foo/./index.php', null], ['/foo/index.php', '/foo/./index.php/route/4', '/route/4'],
// Parent directory resolution ['/index.php', '/test/../index.php', null], ['/index.php', '/test/../index.php/route/5', '/route/5'], ['/foo/path/index.php', '/foo/bar/../path/index.php/route/6', '/route/6'],
// Combined current and parent directory usage ['/index.php', '/test/.././index.php/route/7', '/route/7'], ['/a/c/deep/index.php', '/a/b/../c/./d/../deep/index.php/route/8', '/route/8'],
// With query strings and fragments ['/index.php', '/foo/../index.php?module=Relative', null], ['/index.php', '/bar/./../index.php/route/9?module=Test#section', '/route/9'],
['/index.php', '/index.php/route/../10', '/route/../10'], ['/index.php', '/index.php/route/./11', '/route/./11'],
['/index.php', '/../index.php', null], ['/index.php', '../index.php', null], ['/index.php', '/bar/../../index.php', null], ['/.../index.php', '/.../index.php', null], ['/index.php', '/.../../index.php', null], ['/index.php', '//index.php', null],
['/index.php', '~/index.php', null], ['/bar/index.php', '/bar/~/index.php', null], ['/bar/foo', '/bar/foo/~', null], ];
foreach ($tests as $test) { [$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 [ // $expected, $host, $trustedHosts, $description [true, 'example.com', ['example.com'], 'Naked domain'], [true, 'example.net', ['example.com', 'example.net'], 'Multiple domains'], [true, 'piwik.example.com', ['piwik.example.com'], 'Fully qualified domain name'], [true, 'piwik.example.com', ['example.com'], 'Valid subdomain'], [false, 'example.net', ['example.com'], 'Invalid domain'], [false, '.example.com', ['piwik.example.com'], 'Invalid subdomain'], [false, 'example-com', ['example.com'], 'Regex should match . literally'], [false, 'www.attacker.com?example.com', ['example.com'], 'Spoofed host'], [false, 'aexample.com', ['example.com', 'example2.com'], 'other host, matching first'], [false, 'aexample2.com', ['example.com', 'example2.com'], 'another host, matching second'], [false, 'example.com.attacker.com', ['example.com'], 'Spoofed subdomain'], [true, 'example.com.', ['example.com'], 'Trailing . on host is actually valid'], [true, 'www-dev.example.com', ['example.com'], 'host with dashes is valid'], [false, 'www.example.com:8080', ['example.com'], 'host:port is valid'], [true, 'www.example.com:8080', ['example.com:8080'], 'host:port is valid'], [false, 'www.whatever.com', ['*.whatever.com'], 'regex char is escaped'], [false, 'wwww.whatever.com', ['www.whatever.com'], 'correct start of string is detected'], [false, 'www.whatever.com', ['www.whatever.com/abc'], 'with path starting with /a does not throw error'], [false, 'www.whatever.com', ['www.whatever.com/path/here'], 'with path starting with /p does not throw error'], ]; }
/** * @dataProvider getValidHostData */ 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); }
public function testGetReferrer() { $_SERVER['HTTP_REFERER'] = 'http://www.piwik.org'; $this->assertEquals('http://www.piwik.org', Url::getReferrer()); }
/** * @dataProvider getQueryParameters */ public function testGetQueryStringFromParameters($params, $queryString) { $this->assertEquals($queryString, Url::getQueryStringFromParameters($params)); }
public function getQueryParameters() { return [ [[], ''], [['v1', 'v2'], '0=v1&1=v2'], [['key' => 'val'], 'key=val'], [['key' => 'val', 'k2' => 'v2'], 'key=val&k2=v2'], [['key' => 'val', 'k2' => false], 'key=val'], // remove false values [['key' => 'val', 'k2' => null], 'key=val'], // remove null values [['key' => 'val', 'k2' => ['v1', 'v2']], 'key=val&k2[]=v1&k2[]=v2'], [['key' => 'val', 'k2' => ['k1' => 'v1', 'k2' => 'v2']], 'key=val&k2[]=v1&k2[]=v2'], ]; }
/** * @dataProvider getHostsFromUrl */ public function testGetHostsFromUrl($url, $expectedHost) { $this->assertEquals($expectedHost, Url::getHostFromUrl($url)); }
public function getHostsFromUrl() { return [ [null, null], ['http://', null], ['http://www.example.com', 'www.example.com'], ['http://www.ExaMplE.cOm', 'www.example.com'], ['http://www.example.com/test/foo?bar=xy', 'www.example.com'], ['http://127.0.0.1', '127.0.0.1'], ['example.com', null], ]; }
public function testGetRFCValidHostname() { $_SERVER['HTTP_HOST'] = 'demo.matomo.cloud'; $this->assertEquals('demo.matomo.cloud', Url::getRFCValidHostname()); unset($_SERVER['HTTP_HOST']); $this->assertEquals('matomo.org', Url::getRFCValidHostname('matomo.org')); $this->assertEquals(false, Url::getRFCValidHostname('matomo org')); $this->assertEquals(false, Url::getRFCValidHostname('matomo.org;<script')); }
/** * @dataProvider getIsHostInUrls */ public function testIsHostInUrlsl($isHost, $host, $urls) { $this->assertEquals($isHost, Url::isHostInUrls($host, $urls)); }
public function getIsHostInUrls() { return [ [false, null, null], [false, 'http://', []], [false, 'example.com', []], [false, 'www.example.com', []], [false, 'example.com', ['www.example.com']], // not a domain so no "host" [true, 'example.com', ['example.com']], [true, 'eXamPle.com', ['exaMple.com']], [true, 'eXamPle.com', ['http://exaMple.com']], [true, 'eXamPle.com', ['http://piwik.org', 'http://www.exaMple.com', 'http://exaMple.com']], // multiple urls one or more are valid but not first one [true, 'example.com', ['http://example.com/test']], // url with path but correct host [true, 'example.com', ['http://www.example.com']], // subdomains are allowed [false, 'example.com', ['http://wwwexample.com']], // it should not be possible to create a similar host and make redirects work again. we allow only subdomains [true, 'example.com', ['http://ftp.exAmple.com/test']], [true, 'example.com', ['http://www.exAmple.com/test']], [false, 'ftp.example.com', ['http://www.example.com/test']], [true, '127.0.0.1', []], // always trusted host ]; }
public function urlProvider() { return [ ['http://example.com/'], ['https://example.com/'], ['http://example.com/piwik/'], ['http://example.com/index.php'], ['http://example.com/index.php?foo=bar'], ['http://example.com/index.php/.html?foo=bar', '/.html'], ]; }
/** * @dataProvider urlProvider */ public function testGetCurrentUrl($url, $pathInfo = null) { $this->resetGlobalVariables(); $this->setGlobalVariablesFromUrl($url, $pathInfo);
$this->assertEquals($url, Url::getCurrentUrl()); }
public function urlWithoutQueryStringProvider() { return [ ['http://example.com/', 'http://example.com/'], ['https://example.com/', 'https://example.com/'], ['http://example.com/piwik/', 'http://example.com/piwik/'], ['http://example.com/index.php', 'http://example.com/index.php'], ['http://example.com/index.php?foo=bar', 'http://example.com/index.php'], ['http://example.com/index.php/.html?foo=bar', 'http://example.com/index.php/.html', '/.html'], ]; }
/** * @dataProvider urlWithoutQueryStringProvider */ public function testGetCurrentUrlWithoutQueryString($url, $expected, $pathInfo = null) { $this->resetGlobalVariables(); $this->setGlobalVariablesFromUrl($url, $pathInfo);
$this->assertEquals($expected, Url::getCurrentUrlWithoutQueryString()); }
/** * Tests a use case that was reported by some users: Nginx is not properly configured and passes * incorrect PATH_INFO values in $_SERVER. * @link https://github.com/piwik/piwik/issues/6491 */ public function testMisconfiguredNginxPathInfo() { $this->resetGlobalVariables();
// these variables where taken from a bug report $_SERVER = [ 'QUERY_STRING' => 'foo=bar', 'PATH_INFO' => '/test.php', // Nginx passed a wrong value here (should be empty) 'SCRIPT_NAME' => '/test.php', 'REQUEST_URI' => '/test.php?foo=bar', 'DOCUMENT_URI' => '/test.php', 'SERVER_PROTOCOL' => 'HTTP/1.1', 'SERVER_NAME' => 'example.com', 'HTTP_HOST' => 'example.com', 'PHP_SELF' => '/test.php/test.php', // Nginx passed a wrong value here (should be /test.php) ];
$expectedUrl = 'http://example.com/test.php?foo=bar';
$this->assertEquals($expectedUrl, Url::getCurrentUrl()); }
/** * @group AddCampaignParametersToMatomoLink */ public function testAddCampaignParametersToMatomoLinkExceptIfDisabled() { $this->resetGlobalVariables(); $_GET['module'] = 'CoreHomeAdmin'; $_GET['action'] = 'trackingCodeGenerator';
Config::getInstance()->General['disable_tracking_matomo_app_links'] = 1; $this->assertEquals( 'https://matomo.org/faq/123', Url::addCampaignParametersToMatomoLink('https://matomo.org/faq/123') );
Config::getInstance()->General['disable_tracking_matomo_app_links'] = 0; $this->assertEquals( 'https://matomo.org/faq/123?mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', Url::addCampaignParametersToMatomoLink('https://matomo.org/faq/123') ); }
/** * @dataProvider getCampaignParametersToMatomoLink * @group AddCampaignParametersToMatomoLink */ public function testAddCampaignParametersToMatomoLink($url, $expected, $campaign, $source, $medium) { $this->resetGlobalVariables(); $_GET['module'] = 'CoreHomeAdmin'; $_GET['action'] = 'trackingCodeGenerator'; $this->assertSame($expected, Url::addCampaignParametersToMatomoLink($url, $campaign, $source, $medium));
$expectedLink = '<a target="_blank" rel="noreferrer noopener" href="' . $expected . '">'; $this->assertSame($expectedLink, Url::getExternalLinkTag($url, $campaign, $source, $medium)); }
public function getCampaignParametersToMatomoLink() { return [ // Matomo url ['https://matomo.org/faq/123', 'https://matomo.org/faq/123?mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', null, null, null, ],
// Matomo url, trailing ? ['https://matomo.org/faq/123?', 'https://matomo.org/faq/123?mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', null, null, null, ],
// Matomo url, trailing ? and / ['https://matomo.org/faq/123/?', 'https://matomo.org/faq/123/?mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', null, null, null, ],
// Matomo url, anchor ['https://matomo.org/faq/123#anchor', 'https://matomo.org/faq/123#anchor?mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', null, null, null, ],
// Matomo url, anchor and parameter ['https://matomo.org/faq/123/#anchor?abc=123', 'https://matomo.org/faq/123/#anchor?abc=123&mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', null, null, null, ],
// Matomo url, one parameter ['https://matomo.org/faq/123?abc=123', 'https://matomo.org/faq/123?abc=123&mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', null, null, null, ],
// Matomo url, two parameters ['https://matomo.org/faq/123?abc=123&def=456', 'https://matomo.org/faq/123?abc=123&def=456&mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', null, null, null, ],
// Matomo url with www subdomain, anchor and two parameters ['https://www.matomo.org/faq/123#anchor?abc=123&def=456', 'https://www.matomo.org/faq/123#anchor?abc=123&def=456&mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreHomeAdmin.trackingCodeGenerator', null, null, null, ],
// Non-matomo URL, two parameters and anchor - no change expected ['https://example.org/faq/123#anchor?abc=123&def=456', 'https://example.org/faq/123#anchor?abc=123&def=456', null, null, null, ],
// Matomo url, two parameters, campaign overrides ['https://matomo.org/faq/123?abc=123&def=456', 'https://matomo.org/faq/123?abc=123&def=456&mtm_campaign=SomeCampaign&mtm_source=SomeSource&mtm_medium=SomeMedium', 'SomeCampaign', 'SomeSource', 'SomeMedium', ],
// Empty url ['', '', null, null, null], ]; }
private function resetGlobalVariables() { $names = ['PATH_INFO', 'REQUEST_URI', 'SCRIPT_NAME', 'SCRIPT_FILENAME', 'argv', 'HTTPS', 'HTTP_HOST', 'QUERY_STRING', 'HTTP_REFERER'];
foreach ($names as $name) { unset($_SERVER[$name]); }
Config::getInstance()->General['enable_trusted_host_check'] = 0; }
/** * @param string $url * @param string $pathInfo The PATH_INFO has to be provided because parse_url() doesn't parse that */ private function setGlobalVariablesFromUrl($url, $pathInfo) { if (parse_url($url, PHP_URL_SCHEME) === 'https') { $_SERVER['HTTPS'] = true; }
$_SERVER['HTTP_HOST'] = parse_url($url, PHP_URL_HOST); $_SERVER['REQUEST_URI'] = parse_url($url, PHP_URL_PATH);
$queryString = parse_url($url, PHP_URL_QUERY); if ($queryString) { $_SERVER['REQUEST_URI'] .= '?' . $queryString; $_SERVER['QUERY_STRING'] = $queryString; }
if ($pathInfo) { $_SERVER['PATH_INFO'] = $pathInfo; } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Translation\Loader;
use Piwik\Validators\CharacterLength;
/** * @group Validator * @group CharacterLength * @group CharacterLengthTest */class CharacterLengthTest extends \PHPUnit\Framework\TestCase{ public function testValidateSuccessValueNotEmpty() { self::expectNotToPerformAssertions();
$this->validate('mytest', '2', '10'); $this->validate('mytest', 4, '6'); $this->validate('mytest', 6, 6); $this->validate('', 0, 6); $this->validate('testwewe', 0, 10); }
public function testValidateFailValueIsTooShort() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorCharacterTooShort'); $this->validate('myte', 5); }
public function testValidateFailValueIsTooLong() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorCharacterTooLong'); $this->validate('mytestfoo', null, 4); }
public function testValidateFailValueIsTooNotInRange() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorCharacterTooLong'); $this->validate('mytestfoobar', 5, 8); }
private function validate($value, $min = null, $max = null) { $validator = new CharacterLength($min, $max); $validator->validate($value); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Translation\Loader;
use Piwik\Validators\DateTime;
/** * @group Validator * @group DateTime * @group DateTimeTest */class DateTimeTest extends \PHPUnit\Framework\TestCase{ public function testValidateSuccessValueNotEmpty() { self::expectNotToPerformAssertions();
$this->validate('2014-05-06 10:13:14'); $this->validate('2014-05-06T10:13:14'); $this->validate('2014-05-06 10:13:14Z'); $this->validate('2014-05-06T10:13:14Z'); }
public function testValidateSuccessValueMayBeEmpty() { self::expectNotToPerformAssertions();
$this->validate(false); $this->validate(''); }
/** * @dataProvider getWrongFormat */ public function testValidateFailInvalidFormat($date) { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorInvalidDateTimeFormat'); $this->validate($date); }
public function getWrongFormat() { return array( array('2014-05-0610:13:14'), array('2014-05-06 10:13:14 '), array('2014/05/06 10:13:14'), array('10:13:14'), array('2014/05/06'), array('10:13:14 2014-05-06'), array('1577873410'), array('foo'), array('0'), ); }
public function testValidateInvalidDate() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ExceptionInvalidDateFormat'); $this->validate('2014-15-26 90:43:32'); }
private function validate($value) { $validator = new DateTime(); $validator->validate($value); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Translation\Loader;
use Piwik\Validators\Email;
/** * @group Validator * @group Email * @group EmailTest */class EmailTest extends \PHPUnit\Framework\TestCase{ /** * @dataProvider getValidEmails */ public function testValidateSuccessValueIsLikeUri($validEmail) { self::expectNotToPerformAssertions();
$this->validate($validEmail); }
public function getValidEmails() { return [ array('test@example.com'), array('1234567890@example.com'), array('test+test@example.com'), ]; }
/** * @dataProvider getFailedEmails */ public function testValidateFailValueIsNotValidEmail($email) { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('ValidatorErrorNotEmailLike');
$this->validate($email); }
public function getFailedEmails() { return [ array('-tld-cannot-start-from-hypen'), array('test@example.com,test2@example.com'), array('ąęśćżźł-there-is-no-such-idn'), array('xn--fd67as67fdsa'), array('!@#-inavlid-chars-in-tld'), array('no spaces in tld allowed'), array('no--double--hypens--allowed'), ]; }
private function validate($value) { $validator = new Email(); $validator->validate($value); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Validator;
use Piwik\Validators\IpRanges;
/** * @group Validator * @group IpRanges * @group IpRangesTest */class IpRangesTest extends \PHPUnit\Framework\TestCase{ public function testValidateSuccess() { self::expectNotToPerformAssertions();
$this->validate(array( '12.12.12.12/32', '14.14.14.14', '15.15.15.*', '2001:db8::/48', '2001:0db8:85a3:0000:0000:8a2e:0370:7334')); $this->validate(false); $this->validate(''); $this->validate(null); }
public function testValidateFailNotValidIpRange() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('SitesManager_ExceptionInvalidIPFormat'); $this->validate(array('127.0.0.1', 'foo')); }
private function validate($value) { $validator = new IpRanges(); $validator->validate($value); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Translation\Loader;
use Piwik\Validators\NotEmpty;
/** * @group Validator * @group NotEmpty * @group NotEmptyTest */class NotEmptyTest extends \PHPUnit\Framework\TestCase{ public function testValidateSuccessValueNotEmpty() { self::expectNotToPerformAssertions();
$this->validate('5'); $this->validate(true); $this->validate(99); }
/** * @dataProvider getFailValues */ public function testValidateFailValueIsEmpty($value) { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorEmptyValue');
$this->validate($value); }
public function getFailValues() { return array( array(false), array(''), array(0), ); }
private function validate($value) { $validator = new NotEmpty(); $validator->validate($value); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Translation\Loader;
use Piwik\Validators\NumberRange;
/** * @group Validator * @group NumberRange * @group NumberRangeTest */class NumberRangeTest extends \PHPUnit\Framework\TestCase{ public function testValidateSuccessValueNotEmpty() { self::expectNotToPerformAssertions();
$this->validate('5', '4', '5'); $this->validate('5', '5', '5'); $this->validate('5', '5', '7'); $this->validate('5', '4', '6'); $this->validate(5, 4, '6'); $this->validate(5.43, 5.30, 5.50); $this->validate('5'); $this->validate('5', 4); $this->validate('5', null, '6'); $this->validate('-5', -10, '-4'); }
public function testValidateFailValueIsTooLow() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorNumberTooLow'); $this->validate(3, 5); }
public function testValidateFailValueIsTooHigh() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorNumberTooHigh'); $this->validate(10, null, 8); }
public function testValidateFailValueIsTooNotInRange() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorNumberTooHigh'); $this->validate(10, 5, 8); }
public function testValidateFailValueIsTooNotInRangeFloat() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorNumberTooLow'); $this->validate(5.43, 5.44, 8); }
public function testValidateFailValueIsNotNumber() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorNotANumber'); $this->validate('foo'); }
private function validate($value, $min = null, $max = null) { $validator = new NumberRange($min, $max); $validator->validate($value); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Translation\Loader;
use Piwik\Validators\UrlLike;
/** * @group Validator * @group UrlLike * @group UrlLikeTest */class UrlLikeTest extends \PHPUnit\Framework\TestCase{ /** * @dataProvider getValidUrls */ public function testValidateSuccessValueIsLikeUri($validUrl) { self::expectNotToPerformAssertions();
$this->validate($validUrl); }
public function getValidUrls() { return [ array('http://piwik.org'), array('http://www.piwik.org'), array('https://piwik.org'), array('https://piwik.org/dir/dir2/?oeajkgea7aega=&ge=a'), array('ftp://www.pi-wik.org'), array('news://www.pi-wik.org'), array('https://www.tëteâ.org'), array('http://汉语/漢語.cn'), //chinese
array('rtp://whatever.com'), array('testhttp://test.com'), array('cylon://3.hmn'), array('://something.com'),
// valid network-path reference RFC3986 array('//piwik.org'), array('//piwik/hello?world=test&test'), array('//piwik.org/hello?world=test&test'), ]; }
/** * @dataProvider getFailedUrls */ public function testValidateFailValueIsNotUrlLike($url) { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('ValidatorErrorNotUrlLike');
$this->validate($url); }
public function getFailedUrls() { return [ array('it doesnt look like url'), array('/index?page=test'), array('http:/index?page=test'), array('http/index?page=test'), array('test.html'), array('/\/\/\/\/\/\\\http://test.com////'), array('jmleslangues.php'), array('http://'), array(' http://'), array('2fer://'), ]; }
private function validate($value) { $validator = new UrlLike(); $validator->validate($value); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Validator;
use Piwik\Validators\WhitelistedValue;
/** * @group Validator * @group WhiteListedValue * @group WhiteListedValueTest */class WhiteListedValueTest extends \PHPUnit\Framework\TestCase{ public function testValidateSuccessValueNotEmpty() { self::expectNotToPerformAssertions();
$this->validate('foo'); $this->validate('bar'); $this->validate('baz'); $this->validate('lorem'); }
/** * @dataProvider getInvalidValues */ public function testValidateFailInvalidFormat($date) { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('General_ValidatorErrorXNotWhitelisted'); $this->validate($date); }
public function getInvalidValues() { return array( array('BaR'), // value has to match exactly, not case insensitive array('invalidvalue'), array(''), array(false), array(null), ); }
public function testConstructThrowsExceptionIfParamIsNotAnArray() { $this->expectException(\Piwik\Validators\Exception::class); $this->expectExceptionMessage('The whitelisted values need to be an array'); new WhitelistedValue('foobar'); }
private function validate($value) { $validator = new WhitelistedValue(array('foo', 'bar', 'baz', 'lorem')); $validator->validate($value); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit;
use Composer\Semver\VersionParser;use Piwik\Version;
class VersionTest extends \PHPUnit\Framework\TestCase{ /** * @var Version */ private $version;
public function setUp(): void { $this->version = new Version(); }
public function testIsStableVersion() { $this->assertIsStableVersion('3.3.3'); $this->assertIsStableVersion('3.0.0'); $this->assertIsStableVersion('100.999.9191');
$this->assertNotStableVersion('3.3'); $this->assertNotStableVersion('3.3.'); $this->assertNotStableVersion('3-3-3'); $this->assertNotStableVersion('a3.3.3'); $this->assertNotStableVersion('3.0.0b'); $this->assertNotStableVersion('3.3.3-alpha'); $this->assertNotStableVersion('3.3.3-b1'); $this->assertNotStableVersion('3.3.3-rc1'); $this->assertNotStableVersion('3.3.3-rc1.20240509114000'); }
public function testIsVersionNumber() { $this->assertIsVersionNumber('3.3.3'); $this->assertIsVersionNumber('3.3.3-alpha'); $this->assertIsVersionNumber('3.3.3-b1'); $this->assertIsVersionNumber('3.3.3-rc1.20240509114000'); $this->assertIsVersionNumber('100.999.9991-rc90'); $this->assertIsVersionNumber('100.999.9991-b90'); $this->assertIsVersionNumber('100.999.9991-beta90');
$this->assertNotVersionNumber('3.3'); $this->assertNotVersionNumber('3.3.'); $this->assertNotVersionNumber('3-3-3'); $this->assertNotVersionNumber('a3.3.3'); $this->assertNotVersionNumber('3.0.0b'); $this->assertNotVersionNumber('3.0.0beta1'); // missing dash $this->assertNotVersionNumber('3.3.3-bbeta1'); // unknown stability $this->assertNotVersionNumber('3.3.3-rc1.2024'); // short preview }
public function testIsPreviewVersion() { $this->assertIsPreviewVersion('3.3.3-alpha.20240509114000'); $this->assertIsPreviewVersion('3.3.3-alpha.33331224183000'); $this->assertIsPreviewVersion('3.3.3-b1.20240509114000'); $this->assertIsPreviewVersion('100.999.9191-rc4.20240509114000');
$this->assertNotPreviewVersion('3.3'); $this->assertNotPreviewVersion('3.3.'); $this->assertNotPreviewVersion('3-3-3'); $this->assertNotPreviewVersion('a3.3.3'); $this->assertNotPreviewVersion('3.0.0b'); $this->assertNotPreviewVersion('3.3.3-alpha'); $this->assertNotPreviewVersion('3.3.3-b1'); $this->assertNotPreviewVersion('3.3.3-b1.p20240509114000'); $this->assertNotPreviewVersion('3.3.3-b1.20240509114000a'); $this->assertNotPreviewVersion('3.3.3-rc1'); $this->assertNotPreviewVersion('3.3.3-dev.20240509114000'); $this->assertNotPreviewVersion('3.3.3.20240509114000'); $this->assertNotPreviewVersion('p20240509114000'); $this->assertNotPreviewVersion('3.3.3-b1.202405091140'); $this->assertNotPreviewVersion('3.3.3-b1.20243309114000'); $this->assertNotPreviewVersion('3.3.3-b1.20240544114000'); $this->assertNotPreviewVersion('3.3.3-b1.20240509554000'); $this->assertNotPreviewVersion('3.3.3-b1.20240509117700'); $this->assertNotPreviewVersion('3.3.3-b1.20240509114088'); }
public function testNextPreviewVersion() { $this->assertNextVersionIsEmpty('3.3.3-alpha.29990101000000'); // preview is newer $this->assertNextVersionIsEmpty('3.3.3-dev'); // unsupported stability $this->assertNextVersionIsEmpty('p20240509114000');
$this->assertNextVersionExists('3.3.3'); $this->assertNextVersionExists('3.3.3-alpha'); $this->assertNextVersionExists('3.3.3-b1'); $this->assertNextVersionExists('3.3.3-rc1'); $this->assertNextVersionExists('3.3.3-alpha.20201224180000'); $this->assertNextVersionExists('3.3.3-b1.20201224180000'); $this->assertNextVersionExists('3.3.3-rc1.20201224180000'); }
public function testNextPreviewCorrectlyBumpsVersionIfNeeded() { // stable bumps patch and adds alpha $this->assertCorrectPreviewVersionWithoutSuffix('3.3.3', '3.3.4-alpha');
// non stable and preview does not bump x.y.z, only dt suffix $this->assertCorrectPreviewVersionWithoutSuffix('3.3.3-b1', '3.3.3-b1'); $this->assertCorrectPreviewVersionWithoutSuffix('3.3.3-rc1', '3.3.3-rc1'); $this->assertCorrectPreviewVersionWithoutSuffix('3.3.3-alpha.20201224180000', '3.3.3-alpha'); $this->assertCorrectPreviewVersionWithoutSuffix('3.3.3-b1.20201224180000', '3.3.3-b1'); $this->assertCorrectPreviewVersionWithoutSuffix('3.3.3-rc1.20201224180000', '3.3.3-rc1'); }
private function assertIsStableVersion($versionNumber) { $isStable = $this->version->isStableVersion($versionNumber); $this->assertTrue($isStable); }
private function assertNotStableVersion($versionNumber) { $isStable = $this->version->isStableVersion($versionNumber); $this->assertFalse($isStable); }
private function assertIsVersionNumber($versionNumber) { $isVersionNumber = $this->version->isVersionNumber($versionNumber); $this->assertTrue($isVersionNumber); }
private function assertNotVersionNumber($versionNumber) { $isVersionNumber = $this->version->isVersionNumber($versionNumber); $this->assertFalse($isVersionNumber); }
private function assertIsPreviewVersion($versionNumber) { $isPreviewVersion = $this->version->isPreviewVersion($versionNumber); $this->assertTrue($isPreviewVersion); }
private function assertNotPreviewVersion($versionNumber) { $isPreviewVersion = $this->version->isPreviewVersion($versionNumber); $this->assertFalse($isPreviewVersion); }
private function assertNextVersionIsEmpty($versionNumber) { $nextVersionNumber = $this->version->nextPreviewVersion($versionNumber); $this->assertEmpty($nextVersionNumber); }
private function assertNextVersionExists($versionNumber) { $nextVersionNumber = $this->version->nextPreviewVersion($versionNumber); $this->assertTrue($this->version->isPreviewVersion($nextVersionNumber)); }
private function assertCorrectPreviewVersionWithoutSuffix($versionNumber, $newVersionNumber) { $this->assertRegExp( "/^$newVersionNumber.\d{14}$/", $this->version->nextPreviewVersion($versionNumber) ); }
/** * @dataProvider getLowerVersionCompares */ public function testVersionConstraints($v1, $v2) { $v = new VersionParser(); $v1p = $v->parseConstraints($v1); $v2p = $v->parseConstraints('<' . $v2);
self::assertTrue($v2p->matches($v1p)); }
/** * @dataProvider getLowerVersionCompares */ public function testVersionCompares($v1, $v2) { self::assertTrue(version_compare($v1, $v2, '<')); }
public function getLowerVersionCompares() { return [ [ '5.1.0', '6.0.0-b1' ], [ '5.1.0-alpha.20240517231100', '5.1.0-b1' ], [ '5.1.0-alpha.20240517231100', '5.1.0-rc1' ], [ '5.1.0-alpha.20240517231100', '5.1.0-alpha.20240617231100' ], [ '5.1.0-b1.20240517231100', '5.1.0-b2' ], [ '5.1.0-b1.20240517231100', '5.1.0-rc1' ], [ '5.1.0-b1.20240517221100', '5.1.0-b1.20240517231100' ], [ '5.1.0-rc1.20240517231100', '5.1.0-rc2' ], [ '5.1.0-rc1.20240517221100', '5.1.0-rc1.20240517231100' ], ]; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Visualization;
use Piwik\Container\StaticContainer;use Piwik\Plugins\CoreVisualizations\FeatureFlags\SparklinesRedesign;use Piwik\Plugins\FeatureFlags\FeatureFlagManager;use Piwik\Visualization\Sparkline;
require_once PIWIK_INCLUDE_PATH . '/core/Visualization/Sparkline.php';require_once PIWIK_INCLUDE_PATH . '/plugins/CoreHome/tests/resources/sparkline/SparklineDouble.php';
/** * @group Sparkline */class SparklineTest extends \PHPUnit\Framework\TestCase{ private $oldGet; private $oldFeatureFlagManager;
protected function setUp(): void { parent::setUp();
$this->oldGet = $_GET; $container = StaticContainer::getContainer(); $this->oldFeatureFlagManager = $container->has(FeatureFlagManager::class) ? $container->get(FeatureFlagManager::class) : null; }
protected function tearDown(): void { $_GET = $this->oldGet;
StaticContainer::getContainer()->set( FeatureFlagManager::class, $this->oldFeatureFlagManager ?? $this->createFeatureFlagManager(false) );
parent::tearDown(); }
public function testSetSparklineColorsTreatsWhiteColorsCaseInsensitively(): void { $_GET['colors'] = json_encode([ 'backgroundColor' => '#FFFFFF', 'lineColor' => '#123456', 'fillColor' => '#FFFFFF', 'minPointColor' => '#FFFFFF', 'maxPointColor' => '#FFFFFF', 'lastPointColor' => '#FFFFFF', ]);
$sparkline = new Sparkline(); $double = new \Piwik\Plugins\CoreHome\tests\resources\sparkline\SparklineDouble();
$method = new \ReflectionMethod(Sparkline::class, 'setSparklineColors'); $method->setAccessible(true); $method->invoke($sparkline, $double, 0);
$this->assertTrue($double->backgroundDeactivated); $this->assertTrue($double->fillDeactivated); $this->assertSame([], $double->points); $this->assertSame([['#123456', null]], $double->lineColors); }
public function testGetLineThicknessUsesRedesignThicknessWhenFeatureFlagIsEnabled(): void { StaticContainer::getContainer()->set( FeatureFlagManager::class, $this->createFeatureFlagManager(true) );
$sparkline = new Sparkline();
$method = new \ReflectionMethod(Sparkline::class, 'getLineThickness'); $method->setAccessible(true);
$this->assertSame(Sparkline::REDESIGN_LINE_THICKNESS, $method->invoke($sparkline)); }
public function testGetLineThicknessUsesDefaultThicknessWhenFeatureFlagIsDisabled(): void { StaticContainer::getContainer()->set( FeatureFlagManager::class, $this->createFeatureFlagManager(false) );
$sparkline = new Sparkline();
$method = new \ReflectionMethod(Sparkline::class, 'getLineThickness'); $method->setAccessible(true);
$this->assertSame(Sparkline::DEFAULT_LINE_THICKNESS, $method->invoke($sparkline)); }
public function testGetPointSizeUsesRedesignSizeWhenFeatureFlagIsEnabled(): void { StaticContainer::getContainer()->set( FeatureFlagManager::class, $this->createFeatureFlagManager(true) );
$sparkline = new Sparkline();
$method = new \ReflectionMethod(Sparkline::class, 'getPointSize'); $method->setAccessible(true);
$this->assertSame(Sparkline::REDESIGN_POINT_SIZE, $method->invoke($sparkline)); }
public function testGetPointSizeUsesDefaultSizeWhenFeatureFlagIsDisabled(): void { StaticContainer::getContainer()->set( FeatureFlagManager::class, $this->createFeatureFlagManager(false) );
$sparkline = new Sparkline();
$method = new \ReflectionMethod(Sparkline::class, 'getPointSize'); $method->setAccessible(true);
$this->assertSame(Sparkline::DEFAULT_POINT_SIZE, $method->invoke($sparkline)); }
public function testSetWidthClampsToMaxWidth(): void { $sparkline = new Sparkline(); $sparkline->setWidth(Sparkline::MAX_WIDTH + 5000);
$this->assertSame(Sparkline::MAX_WIDTH, $sparkline->getWidth()); }
public function testSetHeightClampsToMaxHeight(): void { $sparkline = new Sparkline(); $sparkline->setHeight(Sparkline::MAX_HEIGHT + 5000);
$this->assertSame(Sparkline::MAX_HEIGHT, $sparkline->getHeight()); }
/** * @dataProvider getInvalidDimensions */ public function testSetWidthIgnoresInvalidValues($invalidValue): void { $sparkline = new Sparkline(); $sparkline->setWidth($invalidValue);
$this->assertSame(Sparkline::DEFAULT_WIDTH, $sparkline->getWidth()); }
/** * @dataProvider getInvalidDimensions */ public function testSetHeightIgnoresInvalidValues($invalidValue): void { $sparkline = new Sparkline(); $sparkline->setHeight($invalidValue);
$this->assertSame(Sparkline::DEFAULT_HEIGHT, $sparkline->getHeight()); }
public function getInvalidDimensions(): array { return [ 'zero' => [0], 'negative' => [-100], 'non-numeric' => ['abc'], ]; }
private function createFeatureFlagManager(bool $isEnabled): FeatureFlagManager { $featureFlagManager = $this->createMock(FeatureFlagManager::class); $featureFlagManager->method('isFeatureActive') ->with(SparklinesRedesign::class) ->willReturn($isEnabled);
return $featureFlagManager; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Widget;
use Piwik\Widget\WidgetConfig;
/** * @group Widget * @group WidgetConfig * @group WidgetConfigTest */class WidgetConfigTest extends \PHPUnit\Framework\TestCase{ /** * @var WidgetConfig */ private $config;
public function setUp(): void { parent::setUp(); $this->config = new WidgetConfig(); }
public function testNameSetGet() { $this->config->setName('testName');
$this->assertSame('testName', $this->config->getName()); }
public function testGetNameShouldBeEmptyStringByDefault() { $this->assertSame('', $this->config->getName()); }
public function testCategoryIdSetGet() { $this->config->setCategoryId('testCat');
$this->assertSame('testCat', $this->config->getCategoryId()); }
public function testGetCategoryIdShouldBeEmptyStringByDefault() { $this->assertSame('', $this->config->getCategoryId()); }
public function testIsWideShouldBeFalseByDefault() { $this->assertFalse($this->config->isWide()); }
public function testSetisWide() { $this->config->setIsWide(); $this->assertTrue($this->config->isWide()); }
public function testSubcategoryIdSetGet() { $this->config->setSubcategoryId('testsubcat');
$this->assertSame('testsubcat', $this->config->getSubcategoryId()); }
public function testGetSubcategoryIdShouldBeEmptyStringByDefault() { $this->assertSame('', $this->config->getSubcategoryId()); }
public function testModuleSetGet() { $this->config->setModule('CoreHome');
$this->assertSame('CoreHome', $this->config->getModule()); }
public function testGetModuleShouldBeEmptyStringByDefault() { $this->assertSame('', $this->config->getModule()); }
public function testActionSetGet() { $this->config->setAction('get');
$this->assertSame('get', $this->config->getAction()); }
public function testGetActionShouldBeEmptyStringByDefault() { $this->assertSame('', $this->config->getAction()); }
public function testOrderSetGet() { $this->config->setOrder(99); $this->assertSame(99, $this->config->getOrder());
$this->config->setOrder('98'); $this->assertSame(98, $this->config->getOrder()); }
public function testGetOrderShouldReturnADefaultValue() { $this->assertSame(99, $this->config->getOrder()); }
public function testSetMiddlewareParametersSetGet() { $this->config->setMiddlewareParameters(array( 'module' => 'Goals', 'action' => 'hasConversions', ));
$this->assertSame(array( 'module' => 'Goals', 'action' => 'hasConversions', ), $this->config->getMiddlewareParameters()); }
public function testGetMiddlewareParametersShouldReturnADefaultValue() { $this->assertSame(array(), $this->config->getMiddlewareParameters()); }
public function testGetParametersShouldAddModuleAndAction() { $this->setModuleAndAction(); $this->assertSame(array('module' => 'CoreHome', 'action' => 'renderMe'), $this->config->getParameters()); }
public function testGetParametersShouldNotBePossibleToOverwriteModuleAndAction() { $this->setModuleAndAction(); $this->config->setParameters(array('module' => 'Actions', 'action' => 'index'));
$this->assertSame(array('module' => 'CoreHome', 'action' => 'renderMe'), $this->config->getParameters()); }
public function testAddParametersShouldAddMoreParams() { $this->setModuleAndAction(); $this->config->addParameters(array('test' => '1')); // should be removed by setParameters $this->config->addParameters(array('forceView' => '1')); $this->config->addParameters(array('test' => '3'));
$this->assertSame(array('module' => 'CoreHome', 'action' => 'renderMe', 'test' => '3', 'forceView' => '1'), $this->config->getParameters()); }
public function testSetParametersShouldOverwriteAnyExistingParameters() { $this->setModuleAndAction(); $this->config->addParameters(array('test' => '1')); // should be removed by setParameters $this->config->setParameters(array('forceView' => '1'));
$this->assertSame(array('module' => 'CoreHome', 'action' => 'renderMe', 'forceView' => '1'), $this->config->getParameters()); }
public function testShouldBeEnabledByDefault() { $this->assertTrue($this->config->isEnabled()); }
public function testEnableDisable() { $this->config->disable(); $this->assertFalse($this->config->isEnabled()); $this->config->enable(); $this->assertTrue($this->config->isEnabled()); }
public function testSetIsEnabled() { $this->config->setIsEnabled(false); $this->assertFalse($this->config->isEnabled()); $this->config->setIsEnabled(true); $this->assertTrue($this->config->isEnabled()); }
public function testCheckIsEnabledShouldNotThrowExceptionIfEnabled() { self::expectNotToPerformAssertions();
$this->config->enable(); $this->config->checkIsEnabled(); }
public function testCheckIsEnabledShouldThrowExceptionIfDisabled() { $this->expectException(\Exception::class);
$this->config->disable(); $this->config->checkIsEnabled(); }
public function testShouldBeWidgetizableByDefault() { $this->assertTrue($this->config->isWidgetizeable()); }
public function testWidgetizeable() { $this->config->setIsNotWidgetizable(); $this->assertFalse($this->config->isWidgetizeable()); $this->config->setIsWidgetizable(); $this->assertTrue($this->config->isWidgetizeable()); }
public function testGetUniqueIdWithNoParameters() { $this->setModuleAndAction(); $this->assertSame('widgetCoreHomerenderMe', $this->config->getUniqueId()); }
public function testGetUniqueIdWithParameters() { $this->setModuleAndAction(); $this->config->addParameters(array('viewDataTable' => 'table', 'forceView' => '1', 'mtest' => array('test'))); $this->assertSame('widgetCoreHomerenderMeviewDataTabletableforceView1mtestArray', $this->config->getUniqueId()); }
private function setModuleAndAction() { $this->config->setModule('CoreHome'); $this->config->setAction('renderMe'); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Widget;
use Piwik\Widget\WidgetConfig;use Piwik\Widget\WidgetContainerConfig;
/** * @group Widget * @group WidgetContainerConfig * @group WidgetContainerConfigTest */class WidgetContainerConfigTest extends \PHPUnit\Framework\TestCase{ /** * @var WidgetContainerConfig */ private $config;
private $id = 'MyTestContainer';
public function setUp(): void { parent::setUp(); $this->config = new WidgetContainerConfig(); $this->config->setId($this->id); }
public function testIdSetGet() { $this->config->setId('testId');
$this->assertSame('testId', $this->config->getId()); }
public function testNameSetGet() { $this->config->setName('testName');
$this->assertSame('testName', $this->config->getName()); }
public function testGetNameShouldBeEmptyStringByDefault() { $this->assertSame('', $this->config->getName()); }
public function testLayoutSetGet() { $this->config->setLayout('ByDimension');
$this->assertSame('ByDimension', $this->config->getLayout()); }
public function testGetLayoutShouldBeEmptyStringByDefault() { $this->assertSame('', $this->config->getLayout()); }
public function testCategoryIdSetGet() { $this->config->setCategoryId('testCat');
$this->assertSame('testCat', $this->config->getCategoryId()); }
public function testGetCategoryIdShouldBeEmptyStringByDefault() { $this->assertSame('', $this->config->getCategoryId()); }
public function testSubcategoryIdSetGet() { $this->config->setSubcategoryId('testsubcat');
$this->assertSame('testsubcat', $this->config->getSubcategoryId()); }
public function testGetSubcategoryIdShouldBeEmptyStringByDefault() { $this->assertSame('', $this->config->getSubcategoryId()); }
public function testModuleSetGet() { $this->config->setModule('CoreHome');
$this->assertSame('CoreHome', $this->config->getModule()); }
public function testGetModuleShouldBeTheModuleToRenderItByDefault() { $this->assertSame('CoreHome', $this->config->getModule()); }
public function testActionSetGet() { $this->config->setAction('get');
$this->assertSame('get', $this->config->getAction()); }
public function testGetActionShouldBeTheActionToRenderItByDefault() { $this->assertSame('renderWidgetContainer', $this->config->getAction()); }
public function testOrderSetGet() { $this->config->setOrder(99); $this->assertSame(99, $this->config->getOrder());
$this->config->setOrder('98'); $this->assertSame(98, $this->config->getOrder()); }
public function testGetOrderShouldReturnADefaultValue() { $this->assertSame(99, $this->config->getOrder()); }
public function testSetMiddlewareParametersSetGet() { $this->config->setMiddlewareParameters(array( 'module' => 'Goals', 'action' => 'hasConversions', ));
$this->assertSame(array( 'module' => 'Goals', 'action' => 'hasConversions', ), $this->config->getMiddlewareParameters()); }
public function testGetMiddlewareParametersShouldReturnADefaultValue() { $this->assertSame(array(), $this->config->getMiddlewareParameters()); }
public function testGetParametersShouldAddModuleAndAction() { $this->assertSame(array( 'module' => 'CoreHome', 'action' => 'renderWidgetContainer', 'containerId' => $this->id, ), $this->config->getParameters()); }
public function testGetParametersShouldNotBePossibleToOverwriteModuleAndAction() { $this->config->setParameters(array('module' => 'Actions', 'action' => 'index', 'containerId' => 'test'));
$this->assertSame(array( 'module' => 'CoreHome', 'action' => 'renderWidgetContainer', 'containerId' => $this->id, ), $this->config->getParameters()); }
public function testAddParametersShouldAddMoreParams() { $this->config->addParameters(array('test' => '1')); // should be removed by setParameters $this->config->addParameters(array('forceView' => '1')); $this->config->addParameters(array('test' => '3'));
$this->assertSame(array( 'module' => 'CoreHome', 'action' => 'renderWidgetContainer', 'test' => '3', 'forceView' => '1', 'containerId' => $this->id, ), $this->config->getParameters()); }
public function testSetParametersShouldOverwriteAnyExistingParameters() { $this->config->addParameters(array('test' => '1')); // should be removed by setParameters $this->config->setParameters(array('forceView' => '1'));
$this->assertSame(array( 'module' => 'CoreHome', 'action' => 'renderWidgetContainer', 'forceView' => '1', 'containerId' => $this->id, ), $this->config->getParameters()); }
public function testShouldBeEnabledByDefault() { $this->assertTrue($this->config->isEnabled()); }
public function testEnableDisable() { $this->config->disable(); $this->assertFalse($this->config->isEnabled()); $this->config->enable(); $this->assertTrue($this->config->isEnabled()); }
public function testSetIsEnabled() { $this->config->setIsEnabled(false); $this->assertFalse($this->config->isEnabled()); $this->config->setIsEnabled(true); $this->assertTrue($this->config->isEnabled()); }
public function testCheckIsEnabledShouldNotThrowExceptionIfEnabled() { self::expectNotToPerformAssertions();
$this->config->enable(); $this->config->checkIsEnabled(); }
public function testCheckIsEnabledShouldThrowExceptionIfDisabled() { $this->expectException(\Exception::class);
$this->config->disable(); $this->config->checkIsEnabled(); }
public function testShouldNotBeWidgetizableByDefault() { $this->assertFalse($this->config->isWidgetizeable()); }
public function testWidgetizeable() { $this->config->setIsNotWidgetizable(); $this->assertFalse($this->config->isWidgetizeable()); $this->config->setIsWidgetizable(); $this->assertTrue($this->config->isWidgetizeable()); }
public function testGetUniqueIdShouldIncludeContainerId() { $this->assertSame('widgetMyTestContainer', $this->config->getUniqueId()); }
public function testGetUniqueIdWithParameters() { $this->config->addParameters(array('viewDataTable' => 'table', 'forceView' => '1', 'mtest' => array('test'))); $this->assertSame('widgetMyTestContainerviewDataTabletableforceView1mtestArray', $this->config->getUniqueId()); }
public function testGetWidgetConfigsShouldBeEmptyByDefault() { $this->assertSame(array(), $this->config->getWidgetConfigs()); }
public function testWidgetConfigsShouldBeEmptyByDefault() { $this->config->addWidgetConfig($widget1 = $this->createWidgetConfig('widget1')); $this->config->addWidgetConfig($widget2 = $this->createWidgetConfig('widget2')); $this->config->addWidgetConfig($widget3 = $this->createWidgetConfig('widget3')); $this->config->addWidgetConfig($widget4 = new WidgetContainerConfig()); // should be possible to add container to a container $this->assertSame(array( $widget1, $widget2, $widget3, $widget4, ), $this->config->getWidgetConfigs()); }
public function testSetWidgetConfigsCanOverwriteWidgets() { $this->assertSame(array(), $this->config->getWidgetConfigs());
$this->config->addWidgetConfig($widget1 = $this->createWidgetConfig('widget1')); $this->config->addWidgetConfig($widget2 = $this->createWidgetConfig('widget2')); $this->assertSame(array($widget1,$widget2), $this->config->getWidgetConfigs());
$widget3 = $this->createWidgetConfig('widget3'); $widget4 = new WidgetContainerConfig(); $this->config->setWidgetConfigs(array($widget2, $widget3, $widget4)); $this->assertSame(array( $widget2, $widget3, $widget4, ), $this->config->getWidgetConfigs()); }
private function createWidgetConfig($widgetName) { $config = new WidgetConfig(); $config->setName($widgetName);
return $config; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Tests\Unit\Widget;
use Piwik\Widget\WidgetConfig;use Piwik\Widget\WidgetContainerConfig;use Piwik\Widget\WidgetsList;
/** * @group Widget * @group WidgetsList * @group WidgetsListTest */class WidgetsListTest extends \PHPUnit\Framework\TestCase{ /** * @var WidgetsList */ private $list;
public function setUp(): void { parent::setUp(); $this->list = new WidgetsList(); }
public function testGetWidgetUniqueIdWithoutParameters() { $id = WidgetsList::getWidgetUniqueId('CoreHome', 'render'); $this->assertSame('widgetCoreHomerender', $id); }
public function testGetWidgetUniqueIdWithParameters() { $id = WidgetsList::getWidgetUniqueId('CoreHome', 'render', array('test1' => 'value', 'key' => array('test'), 'test2' => '4k3k')); $this->assertSame('widgetCoreHomerendertest1valuekeyArraytest24k3k', $id); }
public function testGetWidgetConfigsShouldBeEmptyByDefault() { $this->assertSame(array(), $this->list->getWidgetConfigs()); }
public function testAddWidgetShouldAddAnyWidgetConfigs() { $this->list->addWidgetConfig($widget1 = $this->createWidget('widget1')); $this->list->addWidgetConfig($widget2 = $this->createWidgetContainer('widget2')); $this->list->addWidgetConfig($widget3 = $this->createWidget('widget3'));
$this->assertSame(array($widget1, $widget2, $widget3), $this->list->getWidgetConfigs()); }
public function testAddWidgetsShouldAddAnyWidgetConfigs() { $this->list->addWidgetConfigs(array( $widget1 = $this->createWidget('widget1'), $widget2 = $this->createWidgetContainer('widget2'), $widget3 = $this->createWidget('widget3'), ));
$this->assertSame(array($widget1, $widget2, $widget3), $this->list->getWidgetConfigs()); }
public function testAddToContainerWidgetShouldAddWidgetToContainerImmediatelyIfContainerAlreadyExistsInList() { $this->list->addWidgetConfigs(array( $widget1 = $this->createWidget('widget1'), $widget2 = $this->createWidgetContainer('widget2')->setId('testId'), $widget3 = $this->createWidget('widget3'), ));
$this->list->addToContainerWidget('testId', $widget4 = $this->createWidget('widget4'));
$this->assertSame(array($widget4), $widget2->getWidgetConfigs());
// widget4 should not be added to this widgetConfigs $this->assertSame(array($widget1, $widget2, $widget3), $this->list->getWidgetConfigs()); }
public function testAddToContainerWidgetShouldAddWidgetToContainerAsSoonAsContainerAddedIfContainerNotAlreadyExistsInList() { $this->list->addToContainerWidget('testId', $widget4 = $this->createWidget('widget4'));
$this->list->addWidgetConfigs(array( $widget1 = $this->createWidget('widget1'), $widget2 = $this->createWidgetContainer('widget2')->setId('testId'), $widget3 = $this->createWidget('widget3'), ));
$this->assertSame(array($widget4), $widget2->getWidgetConfigs());
// widget4 should not be added to this widgetConfigs $this->assertSame(array($widget1, $widget2, $widget3), $this->list->getWidgetConfigs()); }
/** * @dataProvider getWidgetsToRemove */ public function testRemove($categoryId, $name, $expectedWidgetNamesInList) { $this->list->addWidgetConfigs(array( $widget1 = $this->createWidget('widget1')->setCategoryId('Visits'), $widget2 = $this->createWidgetContainer('widget2')->setCategoryId('Actions'), $widget3 = $this->createWidget('widget3')->setCategoryId('Visits'), ));
$this->list->remove($categoryId, $name);
$names = array(); foreach ($this->list->getWidgetConfigs() as $config) { $names[] = $config->getName(); }
$this->assertSame($expectedWidgetNamesInList, $names); }
public function getWidgetsToRemove() { return array( array('Visits', false, array('widget2')), array('Visits', 'widget3', array('widget1', 'widget2')), array('Actions', false, array('widget1', 'widget3')), array('Actions', 'widget2', array('widget1', 'widget3')), array('Actions', 'notExist', array('widget1', 'widget2', 'widget3')), array('NotExiSt', false, array('widget1', 'widget2', 'widget3')), ); }
/** * @dataProvider getWidgetsDefined */ public function testIsDefined($module, $action, $exists) { $this->list->addWidgetConfigs(array( $widget1 = $this->createWidget('widget1')->setModule('CoreHome')->setAction('renderMe'), $widget2 = $this->createWidgetContainer('widget2')->setModule('CoreHome')->setAction('renderContainer'), $widget3 = $this->createWidget('widget3')->setModule('Actions')->setAction('index'), ));
$this->assertSame($exists, $this->list->isDefined($module, $action)); }
public function getWidgetsDefined() { return array( array('CoreHome', 'renderMe', $isDefined = true), array('CoreHome', 'renderContainer', $isDefined = true), array('Actions', 'index', $isDefined = true), array('Actions', 'renderMe', $isDefined = false), array('AnyThiNg', 'renderMe', $isDefined = false), array('CoreHome', 'index', $isDefined = false), ); }
private function createWidget($name) { $config = new WidgetConfig(); $config->setName($name);
return $config; }
private function createWidgetContainer($name) { $config = new WidgetContainerConfig(); $config->setName($name);
return $config; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170<?php
use Piwik\Application\Environment;use Piwik\Intl\Locale;use Piwik\Config;use Piwik\SettingsPiwik;use Piwik\Tests\Framework\TestingEnvironmentManipulator;use Piwik\Tests\Framework\TestingEnvironmentVariables;
define('PIWIK_TEST_MODE', true);define('PIWIK_PRINT_ERROR_BACKTRACE', false);
if (!defined("PIWIK_PATH_TEST_TO_ROOT")) { define('PIWIK_PATH_TEST_TO_ROOT', realpath(dirname(__FILE__) . '/../..'));}if (!defined('PIWIK_DOCUMENT_ROOT')) { define('PIWIK_DOCUMENT_ROOT', PIWIK_PATH_TEST_TO_ROOT);}if (!defined('PIWIK_USER_PATH')) { define('PIWIK_USER_PATH', PIWIK_PATH_TEST_TO_ROOT);}if (!defined('PIWIK_INCLUDE_PATH')) { define('PIWIK_INCLUDE_PATH', PIWIK_PATH_TEST_TO_ROOT);}
if (file_exists(PIWIK_DOCUMENT_ROOT . '/bootstrap.php')) { require_once PIWIK_DOCUMENT_ROOT . '/bootstrap.php';}
if (!defined('PIWIK_INCLUDE_SEARCH_PATH')) { define('PIWIK_INCLUDE_SEARCH_PATH', get_include_path() . PATH_SEPARATOR . PIWIK_INCLUDE_PATH . '/vendor/bin' . PATH_SEPARATOR . PIWIK_INCLUDE_PATH . '/core' . PATH_SEPARATOR . PIWIK_INCLUDE_PATH . '/libs' . PATH_SEPARATOR . PIWIK_INCLUDE_PATH . '/plugins');}@ini_set('include_path', PIWIK_INCLUDE_SEARCH_PATH);@set_include_path(PIWIK_INCLUDE_SEARCH_PATH);@ini_set('memory_limit', -1);
$GLOBALS['MATOMO_PLUGIN_DIRS'] = array( array( 'pluginsPathAbsolute' => PIWIK_INCLUDE_PATH . '/tests/resources/custompluginsdir', 'webrootDirRelativeToMatomo' => 'tests/resources/custompluginsdir', ),);
require_once PIWIK_INCLUDE_PATH . '/core/bootstrap.php';
if (getenv('PIWIK_USE_XHPROF') == 1) { \Piwik\Profiler::setupProfilerXHProf();}
function setPiwikDomainFromEnvVar(){ $piwikDomain = getenv('PIWIK_DOMAIN'); if (!empty($piwikDomain)) { $_SERVER['HTTP_HOST'] = $piwikDomain; $_SERVER['SERVER_NAME'] = $piwikDomain; }}
setPiwikDomainFromEnvVar();
// setup container for testsfunction setupRootContainer($enable = false){ // before running tests, delete the TestingEnvironmentVariables file, since it can indirectly mess w/ // phpunit's class loading (if a test class is loaded in bootstrap.php, phpunit can't load it from a file, // so executing the tests in a file will fail) if ($enable) { $vars = new TestingEnvironmentVariables(); $vars->delete();
Environment::setGlobalEnvironmentManipulator(new TestingEnvironmentManipulator($vars)); }
$rootTestEnvironment = new \Piwik\Application\Environment(null); $rootTestEnvironment->init();}
setupRootContainer(); // do it in a function so it doesn't appear in $_GLOBALS and so PHPUnit won't try to serialize it.
Locale::setDefaultLocale();
function prepareServerVariables(Config $config){ $testConfig = $config->tests;
if ('@REQUEST_URI@' === $testConfig['request_uri']) { // config not done yet, if Piwik is installed we can automatically configure request_uri and http_host $url = \Piwik\SettingsPiwik::getPiwikUrl();
if (!empty($url)) { $parsedUrl = parse_url($url); $testConfig['request_uri'] = $parsedUrl['path']; $testConfig['http_host'] = $parsedUrl['host']; $config->tests = $testConfig; $config->forceSave(); } }
$_SERVER['HTTP_HOST'] = $testConfig['http_host']; $_SERVER['REQUEST_URI'] = $testConfig['request_uri']; $_SERVER['REMOTE_ADDR'] = $testConfig['remote_addr']; $_SERVER['SERVER_PORT'] = $testConfig['port'];}
function prepareTestDatabaseConfig(Config $config){ $testDb = $config->database_tests;
if ('@USERNAME@' !== $testDb['username']) { return; // testDb is already configured, we do not want to overwrite any existing settings. }
$db = $config->database; $testDb['username'] = $db['username'];
if (empty($testDb['password'])) { $testDb['password'] = $db['password']; }
if (empty($testDb['host'])) { $testDb['host'] = $db['host']; }
$testDb['tables_prefix'] = ''; // tables_prefix has to be empty for UI tests
$config->database_tests = $testDb; $config->forceSave();}
if (!SettingsPiwik::isMatomoInstalled()) { throw new Exception('Piwik needs to be installed in order to run the tests');}
$config = Config::getInstance();
prepareServerVariables($config);prepareTestDatabaseConfig($config);setupRootContainer(true);checkPiwikSetupForTests();printTestDoxHint();
function checkPiwikSetupForTests(){ if ( empty($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] == '@REQUEST_URI@' ) { echo "WARNING: for tests to pass, you must first:1) Install webserver on localhost, eg. apache2) Make these Piwik files available on the webserver, at eg. http://localhost/dev/piwik/3) Install Piwik by going through the installation process4) Configure tests section if needed in config/config.ini.php:[tests]http_host = \"localhost\"request_uri = \"@REQUEST_URI@\"remote_addr = \"127.0.0.1\"
Try again."; exit(1); }}
function printTestDoxHint(){ print "\nIf these tests time out consistently, it can be helpful to temporarily set testdox=true in the phpunit.xml.dist in order to see which test is causing the issue.\n";}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/8.5/phpunit.xsd" backupGlobals="true" backupStaticAttributes="false" bootstrap="bootstrap.php" colors="false" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" forceCoversAnnotation="false" processIsolation="false" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" testdox="false" verbose="true">
<testsuites> <testsuite name="SystemTests"> <directory>./System</directory> <directory>../../plugins/*/tests</directory><!-- There should be actually a tests/System but this way we make sure to execute all tests even if some are not moved to correct subdirectory. We will execute Unit and Integration tests twice :( ... --> <directory>../../plugins/*/Test</directory> <directory>../../tests/resources/custompluginsdir/*/tests/System</directory> <directory>../../tests/resources/custompluginsdir/*/Test/System</directory> <exclude>../../plugins/*/tests/Integration</exclude> <exclude>../../plugins/*/Test/Integration</exclude> <exclude>../../plugins/*/tests/Unit</exclude> <exclude>../../plugins/*/Test/Unit</exclude> </testsuite> <testsuite name="SystemTestsCore"> <directory>./System</directory> </testsuite> <testsuite name="SystemTestsPlugins"> <directory>../../plugins/*/tests</directory><!-- There should be actually a tests/System but this way we make sure to execute all tests even if some are not moved to correct subdirectory. We will execute Unit and Integration tests twice :( ... --> <directory>../../plugins/*/Test</directory> <directory>../../tests/resources/custompluginsdir/*/tests/System</directory> <directory>../../tests/resources/custompluginsdir/*/Test/System</directory> <exclude>../../plugins/*/tests/Integration</exclude> <exclude>../../plugins/*/Test/Integration</exclude> <exclude>../../plugins/*/tests/Unit</exclude> <exclude>../../plugins/*/Test/Unit</exclude> </testsuite> <testsuite name="IntegrationTests"> <directory>./Integration</directory> <directory>../../plugins/*/tests/Integration</directory> <directory>../../plugins/*/Test/Integration</directory> <directory>../../tests/resources/custompluginsdir/*/tests/Integration</directory> <directory>../../tests/resources/custompluginsdir/*/Test/Integration</directory> </testsuite> <testsuite name="IntegrationTestsCore"> <directory>./Integration</directory> <directory>../../tests/resources/custompluginsdir/*/tests/Integration</directory> <directory>../../tests/resources/custompluginsdir/*/Test/Integration</directory> </testsuite> <testsuite name="IntegrationTestsPlugins"> <directory>../../plugins/*/tests/Integration</directory> <directory>../../plugins/*/Test/Integration</directory> </testsuite> <testsuite name="UnitTests"> <directory>./Unit</directory> <directory>../../plugins/*/tests/Unit</directory> <directory>../../plugins/*/Test/Unit</directory> <directory>../../tests/resources/custompluginsdir/*/tests/Unit</directory> <directory>../../tests/resources/custompluginsdir/*/Test/Unit</directory> </testsuite> <testsuite name="PluginTests"> <directory>../../plugins/*/tests</directory> <directory>../../plugins/*/Test</directory> </testsuite> <testsuite name="CoreTests"> <directory>./Unit</directory> <directory>./Integration</directory> <directory>./System</directory> </testsuite></testsuites>
<filter> <whitelist addUncoveredFilesFromWhitelist="true"> <directory suffix=".php">../../core</directory> <directory suffix=".php">../../plugins</directory> <exclude> <directory suffix=".php">../../core/Updates</directory> <directory suffix=".php">../../plugins/Example*</directory> <directory suffix=".php">../../plugins/SecurityInfo*</directory> <directory suffix=".php">../../plugins/*/Updates</directory> <directory suffix=".php">../../plugins/*/libs</directory> <directory suffix=".php">../../plugins/*/tests</directory> <directory suffix=".php">../../plugins/*/Test</directory> </exclude> </whitelist></filter>
</phpunit>12345678910111213<?phpuse Piwik\Application\Environment;use Piwik\Tests\Framework\TestingEnvironmentManipulator;use Piwik\Tests\Framework\TestingEnvironmentVariables;
define('PIWIK_ARCHIVE_NO_TRUNCATE', true);
require realpath(dirname(__FILE__)) . "/includes.php";
Environment::setGlobalEnvironmentManipulator(new TestingEnvironmentManipulator(new TestingEnvironmentVariables()));
// include archive.php, and let 'er riprequire_once PIWIK_INCLUDE_PATH . "/misc/cron/archive.php";1234567891011#!/usr/bin/env php<?phpuse Piwik\Application\Environment;use Piwik\Tests\Framework\TestingEnvironmentManipulator;use Piwik\Tests\Framework\TestingEnvironmentVariables;
require realpath(dirname(__FILE__)) . "/includes.php";
Environment::setGlobalEnvironmentManipulator(new TestingEnvironmentManipulator(new TestingEnvironmentVariables()));
require_once PIWIK_INCLUDE_PATH . "/console";1234567891011121314151617181920212223<?php
if (!defined('PIWIK_INCLUDE_PATH')) { define('PIWIK_INCLUDE_PATH', realpath(dirname(__FILE__) . '/../../..'));}
if (!defined('PIWIK_USER_PATH')) { define('PIWIK_USER_PATH', PIWIK_INCLUDE_PATH);}if (!defined('PIWIK_TEST_MODE')) { define('PIWIK_TEST_MODE', true);}
$GLOBALS['MATOMO_PLUGIN_DIRS'] = array( array( 'pluginsPathAbsolute' => realpath(PIWIK_INCLUDE_PATH . '/tests/resources/custompluginsdir'), 'webrootDirRelativeToMatomo' => '../../resources/custompluginsdir' ),);
require_once PIWIK_INCLUDE_PATH . '/core/bootstrap.php';
Piwik\SettingsServer::setMaxExecutionTime(0);123456789101112131415<?php/** * Proxy to index.php, but will use the Test DB * Used by tests/PHPUnit/System/ImportLogsTest.php and tests/PHPUnit/System/UITest.php */
use Piwik\Application\Environment;use Piwik\Tests\Framework\TestingEnvironmentManipulator;use Piwik\Tests\Framework\TestingEnvironmentVariables;
require realpath(dirname(__FILE__)) . "/includes.php";
Environment::setGlobalEnvironmentManipulator(new TestingEnvironmentManipulator(new TestingEnvironmentVariables()));
include PIWIK_INCLUDE_PATH . '/index.php';123456789<?php/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
include __DIR__ . '/piwik.php';1234567891011121314151617181920<?php/** * Proxy to index.php, but will use the Test DB * Used by tests/PHPUnit/System/ImportLogsTest.php and tests/PHPUnit/System/UITest.php */
use Piwik\Application\Environment;use Piwik\Tests\Framework\TestingEnvironmentManipulator;use Piwik\Tests\Framework\TestingEnvironmentVariables;
define('PIWIK_ENABLE_DISPATCH', false);
require realpath(dirname(__FILE__)) . "/includes.php";$testEnvironment = new TestingEnvironmentVariables();$testEnvironment->configFileLocal = PIWIK_INCLUDE_PATH . "/tmp/test.config.ini.php";$testEnvironment->save();
Environment::setGlobalEnvironmentManipulator(new TestingEnvironmentManipulator($testEnvironment));
include PIWIK_INCLUDE_PATH . '/index.php';123456789101112131415161718192021222324252627282930313233343536373839404142434445464748<?php/** * Proxy to normal piwik.php, but in testing mode * * - Use the tests database to record Tracking data * - Allows to overwrite the Visitor IP, and Server datetime * */
use Piwik\Application\Environment;use Piwik\DataTable\Manager;use Piwik\Option;use Piwik\Site;use Piwik\Tests\Framework\TestingEnvironmentManipulator;use Piwik\Tests\Framework\TestingEnvironmentVariables;use Piwik\Tracker;
require realpath(dirname(__FILE__)) . "/includes.php";
// Wrapping the request inside ob_start() calls to ensure that the Test// calling us waits for the full request to process before unblockingob_start();
try { $globalObservers = array( array('Environment.bootstrapped', \Piwik\DI::value(function () { Tracker::setTestEnvironment(); Manager::getInstance()->deleteAll(); Option::clearCache(); Site::clearCache(); })) );
Environment::setGlobalEnvironmentManipulator(new TestingEnvironmentManipulator(new TestingEnvironmentVariables(), $globalObservers));
include PIWIK_INCLUDE_PATH . '/matomo.php';} catch (Exception $ex) { $stacktrace = ''; if (\Piwik\ExceptionHandler::shouldPrintBackTraceWithMessage()) { $stacktrace = "\n" . $ex->getTraceAsString(); } echo "Unexpected error during tracking: " . $ex->getMessage() . $stacktrace . "\n";}
if (ob_get_level() > 1) { ob_end_flush();}
123456Matomo comes with unit tests, integration tests, system tests, Javascript tests and UI tests.
To learn more about Matomo tests check out these sections on our developer website:
* [Matomo Tests](https://developer.matomo.org/guides/tests)* [Matomo Tests - In Depth](https://developer.matomo.org/guides/tests-system)123456# Screenshots UI tests
Matomo contains UI tests that compare captured screenshots of URLs and UI controls with expected screenshots.If a captured screenshot does not match its expected screenshot, the build will fail.
For a developer documentation, refer to the following guide: https://developer.matomo.org/guides/tests-ui1This guide was moved to our [reproducing issues](https://developer.matomo.org/guides/reproducing-issues) developer guide.123# Troubleshooting Piwik Tests
See our [Troubleshooting Tests](https://developer.matomo.org/guides/tests-troubleshooting) guide.12345678910processed-ui-screenshots/*.pngprocessed-ui-screenshots/**/*.pngprocessed-ui-screenshotsscreenshot-diffs/*.pngscreenshot-diffs/diff*.htmlscreenshot-diffs/jquery.jsscreenshot-diffs/resemble.js.idea/*php_errors.logconfig.js12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576/*! * Matomo - free/libre analytics platform * * UI tests config * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
/** * The root Matomo URL to test against. */exports.piwikUrl = "http://localhost/";
/** * Data for the $_SERVER variable in the setup/teardown PHP scripts. Should be the same as * the values in your phpunit.xml file. */exports.phpServer = { HTTP_HOST: 'localhost', REQUEST_URI: '/', REMOTE_ADDR: '127.0.0.1'};
/** * The path to the PHP executable to execute when setting up & tearing down the database. */exports.php = 'php';
/** * The folder in tests/lib that holds mocha. */exports.mocha = 'mocha-3.1.2';
/** * The folder in tests/lib that holds chai. */exports.chai = 'chai-1.9.0';
/** * Mocha reporters to use (can be multiple delimited by a comma). */if (process.env.TESTOMATIO && process.env.SHOULD_SEND_TO_TESTOMATIO === 'true') { exports.reporter = 'mocha-multi-reporters'; exports.reporterOptions = { reporterEnabled: 'spec, @testomatio/reporter/lib/adapter/mocha.js', testomatioReporterLibAdapterMochaJsReporterOptions: { apiKey: process.env.TESTOMATIO } };} else { exports.reporter = 'spec'; exports.reporterOptions = {};}
/** * The directory that stores expected screenshots. Relative to the UI repo's root directory. */exports.expectedScreenshotsDir = ["./expected-screenshots", "./expected-ui-screenshots"];
/** * The directory that stores processed screenshots. Relative to the UI repo's root directory. */exports.processedScreenshotsDir = "./processed-ui-screenshots";
/** * The directory that stores screenshot diffs. Relative to the UI repo's root directory. */exports.screenshotDiffDir = "./screenshot-diffs";
/** * The config object passed to the headless browser used by Puppeteer */exports.browserConfig = { args: ['--no-sandbox', '--ignore-certificate-errors']};tests/PHPUnit/Unit/Translation/Loader/LoaderCacheTest.phpDeleted-73
tests/PHPUnit/Unit/Translation/Loader/fixtures/dir1/en.jsonDeleted-6
tests/PHPUnit/Unit/Translation/Loader/fixtures/dir1/fr.jsonDeleted-5
tests/PHPUnit/Unit/Translation/Loader/fixtures/dir2/en.jsonDeleted-6
tests/PHPUnit/Unit/Translation/TranslatorTest.phpDeleted-157
tests/PHPUnit/Unit/TwigTest.phpDeleted-65
tests/PHPUnit/Unit/UpdateCheckTest.phpDeleted-240
tests/PHPUnit/Unit/UrlHelperTest.phpDeleted-371
tests/PHPUnit/Unit/UrlTest.phpDeleted-684
tests/PHPUnit/Unit/Validator/CharacterLengthTest.phpDeleted-58
tests/PHPUnit/Unit/Validator/DateTimeTest.phpDeleted-76
tests/PHPUnit/Unit/Validator/EmailTest.phpDeleted-69
tests/PHPUnit/Unit/Validator/IpRangesTest.phpDeleted-48
tests/PHPUnit/Unit/Validator/NotEmptyTest.phpDeleted-53
tests/PHPUnit/Unit/Validator/NumberRangeTest.phpDeleted-77
tests/PHPUnit/Unit/Validator/UrlLikeTest.phpDeleted-87
tests/PHPUnit/Unit/Validator/WhiteListedValueTest.phpDeleted-64
tests/PHPUnit/Unit/VersionTest.phpDeleted-210
tests/PHPUnit/Unit/Visualization/SparklineTest.phpDeleted-191
tests/PHPUnit/Unit/Widget/WidgetConfigTest.phpDeleted-236
tests/PHPUnit/Unit/Widget/WidgetContainerConfigTest.phpDeleted-300
tests/PHPUnit/Unit/Widget/WidgetsListTest.phpDeleted-177
tests/PHPUnit/bootstrap.phpDeleted-170
tests/PHPUnit/phpunit.xml.distDeleted-96
tests/PHPUnit/proxy/archive.phpDeleted-13
tests/PHPUnit/proxy/consoleDeleted-11
tests/PHPUnit/proxy/includes.phpDeleted-23
tests/PHPUnit/proxy/index.phpDeleted-15
tests/PHPUnit/proxy/matomo.phpDeleted-9
tests/PHPUnit/proxy/nodispatchnotinstalled.phpDeleted-20
tests/PHPUnit/proxy/piwik.phpDeleted-48
tests/README.mdDeleted-6
tests/README.screenshots.mdDeleted-6
tests/README.testing-data.mdDeleted-1
tests/README.troubleshooting.mdDeleted-3
tests/UI/.gitignoreDeleted-10
tests/UI/config.dist.jsDeleted-76
tests/UI/expected-screenshots/BarGraph_load.pngDeleted
tests/UI/expected-screenshots/BarGraph_load_fail_when_token_used.pngDeleted
tests/UI/expected-screenshots/BarGraph_metric_picker_shown.pngDeleted
tests/UI/expected-screenshots/BarGraph_other_metric.pngDeleted
tests/UI/expected-screenshots/Comparison_bar_graph.pngDeleted
tests/UI/expected-screenshots/Comparison_dashboard_last_period.pngDeleted
tests/UI/expected-screenshots/Comparison_dashboard_last_period_and_segment.pngDeleted
tests/UI/expected-screenshots/Comparison_goals_table.pngDeleted
tests/UI/expected-screenshots/Comparison_goals_table_specific.pngDeleted
tests/UI/expected-screenshots/Comparison_multi_row_evolution.pngDeleted
tests/UI/expected-screenshots/Comparison_normal_table.pngDeleted
tests/UI/expected-screenshots/Comparison_normal_table_no_periods.pngDeleted
tests/UI/expected-screenshots/Comparison_normal_table_no_segments.pngDeleted