1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
|
<?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\Plugins\API\tests\System;
use Piwik\API\Request;
use Piwik\Application\Environment;
use Piwik\ArchiveProcessor\Rules;
use Piwik\Cache as PiwikCache;
use Piwik\Columns\Dimension;
use Piwik\Common;
use Piwik\Date;
use Piwik\Option;
use Piwik\Plugins\API\API;
use Piwik\Plugins\CustomVariables\Columns\CustomVariableName;
use Piwik\Plugins\CustomVariables\Columns\CustomVariableValue;
use Piwik\Tests\Fixtures\ManyVisitsWithGeoIPAndEcommerce;
use Piwik\Tests\Framework\TestCase\SystemTestCase;
use Piwik\Tracker\Cache;
// Class to cache results of getSuggestedValuesForSegment to prevent it beeing called multiple time for each segment
class CachedAPI extends API
{
public static $cache = [];
public function getSuggestedValuesForSegment($segmentName, $idSite)
{
if (empty(self::$cache[$segmentName . $idSite])) {
self::$cache[$segmentName . $idSite] = parent::getSuggestedValuesForSegment($segmentName, $idSite);
}
return self::$cache[$segmentName . $idSite];
}
}
/**
* testing a the auto suggest API for all known segments
*
* @group AutoSuggestAPITest
* @group Plugins
*/
class AutoSuggestAPITest extends SystemTestCase
{
public static $fixture = null; // initialized below class definition
private static $originalAutoSuggestLookBack = null;
protected static $processed = 0;
protected static $skipped = array();
private static $hasArchivedData = false;
public static function setUpBeforeClass(): void
{
$date = mktime(0, 0, 0, 1, 1, 2018);
$lookBack = ceil((time() - $date) / 86400);
self::$originalAutoSuggestLookBack = API::$_autoSuggestLookBack;
API::$_autoSuggestLookBack = $lookBack;
self::$fixture->dateTime = Date::factory($date)->getDatetime();
parent::setUpBeforeClass();
API::setSingletonInstance(CachedAPI::getInstance());
}
public static function tearDownAfterClass(): void
{
API::$_autoSuggestLookBack = self::$originalAutoSuggestLookBack;
parent::tearDownAfterClass();
CachedAPI::$cache = [];
API::unsetInstance();
}
/**
* @dataProvider getApiForTesting
*/
public function testApi($api, $params)
{
Cache::clearCacheGeneral();
$this->runApiTests($api, $params);
}
public function getApiForTesting()
{
$idSite = self::$fixture->idSite;
$segments = self::getSegmentsMetadata();
$apiForTesting = array();
foreach ($segments as $segment) {
$apiForTesting[] = $this->getApiForTestingForSegment($idSite, $segment);
}
if (self::isMysqli()) {
// Skip the test on Mysqli as it fails due to rounding Float errors on latitude/longitude
// then the test started failing after bc19503 and I cannot understand why
echo "Skipped test \n";
} else {
$apiForTesting[] = array('Live.getLastVisitsDetails',
array('idSite' => $idSite,
'date' => '1998-07-12,today',
'period' => 'range',
'otherRequestParameters' => array('filter_limit' => 1000)));
}
return $apiForTesting;
}
/**
* @dataProvider getApiForTestingBrowserArchivingDisabled
*/
public function testApiBrowserArchivingDisabled($api, $params)
{
if (!self::$hasArchivedData) {
self::$hasArchivedData = true;
// need to make sure data is archived before disabling the archiving
Request::processRequest('API.get', array(
'date' => '2018-01-10', 'period' => 'year', 'idSite' => $params['idSite'],
'trigger' => 'archivephp',
));
}
Cache::clearCacheGeneral();
// disable browser archiving so the APIs are used
Option::set(Rules::OPTION_BROWSER_TRIGGER_ARCHIVING, 0);
$this->runApiTests($api, $params);
Option::set(Rules::OPTION_BROWSER_TRIGGER_ARCHIVING, 1);
}
public function getApiForTestingBrowserArchivingDisabled()
{
$idSite = self::$fixture->idSite;
$segments = self::getSegmentsMetadata($onlyWithSuggestedValuesApi = true);
$apiForTesting = array();
foreach ($segments as $segment) {
$apiForTesting[] = $this->getApiForTestingForSegment($idSite, $segment);
}
return $apiForTesting;
}
/**
* @param $idSite
* @param $segment
* @return array
*/
protected function getApiForTestingForSegment($idSite, $segment)
{
return array('API.getSuggestedValuesForSegment',
array('idSite' => $idSite,
'testSuffix' => '_' . $segment,
'otherRequestParameters' => array('segmentName' => $segment)));
}
/**
* @depends testApi
* @dataProvider getAnotherApiForTesting
*/
public function testAnotherApi($api, $params)
{
// Get the top segment value
$request = new Request([
'method' => 'API.getSuggestedValuesForSegment',
'segmentName' => $params['segmentToComplete'],
'idSite' => $params['idSite'],
'format' => 'json',
]);
$response = json_decode($request->process(), true);
$this->assertApiResponseHasNoError($response);
$topSegmentValue = @$response[0];
if ($topSegmentValue !== false && !is_null($topSegmentValue)) {
if (is_numeric($topSegmentValue) || is_float($topSegmentValue) || preg_match('/^\d*?,\d*$/', $topSegmentValue)) {
$topSegmentValue = Common::forceDotAsSeparatorForDecimalPoint($topSegmentValue);
}
// use some specific test values for segments where auto suggest returns list of values that might not occur
switch ($params['segmentToComplete']) {
case 'countryName':
$topSegmentValue = 'France';
break;
case 'browserName':
$topSegmentValue = 'Chrome';
break;
case 'operatingSystemName':
$topSegmentValue = 'Android';
break;
case 'visitEndServerDate':
$topSegmentValue = '2018-01-03';
break;
case 'visitEndServerDayOfMonth':
$topSegmentValue = '03';
break;
case 'visitEndServerYear':
$topSegmentValue = '2018';
break;
case 'visitLocalMinute':
$topSegmentValue = '34';
break;
}
// Now build the segment request
$segmentValue = rawurlencode(html_entity_decode($topSegmentValue, ENT_COMPAT | ENT_HTML401, 'UTF-8'));
$params['segment'] = $params['segmentToComplete'] . '==' . $segmentValue;
unset($params['segmentToComplete']);
$this->runApiTests($api, $params);
self::$processed++;
} else {
self::$skipped[] = $params['segmentToComplete'];
}
}
public function getAnotherApiForTesting()
{
$segments = self::getSegmentsMetadata();
$apiForTesting = array();
foreach ($segments as $segment) {
$apiForTesting[] = array('VisitsSummary.get',
array('idSite' => self::$fixture->idSite,
'date' => date("Y-m-d", strtotime(self::$fixture->dateTime)) . ',today',
'period' => 'range',
'testSuffix' => '_' . $segment,
'segmentToComplete' => $segment));
}
return $apiForTesting;
}
/**
* @depends testAnotherApi
*/
public function testCheckOtherTestsWereComplete()
{
// Check that only a few haven't been tested specifically (these are all custom variables slots since we only test slot 1, 2, 5 (see the fixture) and example dimension slots and bandwidth)
$maximumSegmentsToSkip = 24;
$this->assertLessThan($maximumSegmentsToSkip, count(self::$skipped), 'SKIPPED ' . count(self::$skipped) . ' segments --> some segments had no "auto-suggested values"
but we should try and test the autosuggest for all new segments. Segments skipped were: ' . implode(', ', self::$skipped));
// and check that most others have been tested
$minimumSegmentsToTest = 46;
$message = 'PROCESSED ' . self::$processed . ' segments --> it seems some segments "auto-suggested values" haven\'t been tested as we were expecting. ';
$this->assertGreaterThan($minimumSegmentsToTest, self::$processed, $message);
}
public static function getSegmentsMetadata($onlyWithSuggestedValuesApi = false)
{
Cache::clearCacheGeneral();
PiwikCache::getTransientCache()->flushAll();
$segments = array();
$environment = new Environment(null);
$exception = null;
try {
$environment->init();
$environment->getContainer()->get('Piwik\Plugin\Manager')->loadActivatedPlugins();
foreach (Dimension::getAllDimensions() as $dimension) {
if (
$dimension instanceof CustomVariableName
|| $dimension instanceof CustomVariableValue
) {
continue; // ignore custom variables dimensions as they are tested in the plugin
}
foreach ($dimension->getSegments() as $segment) {
if ($segment->isInternal()) {
continue;
}
if ($onlyWithSuggestedValuesApi && !$segment->getSuggestedValuesApi()) {
continue;
}
$segments[] = $segment->getSegment();
}
}
} catch (\Exception $ex) {
$exception = $ex;
echo $ex->getMessage() . "\n" . $ex->getTraceAsString() . "\n";
}
$environment->destroy();
if (!empty($exception)) {
throw $exception;
}
return $segments;
}
public static function getPathToTestDirectory()
{
return dirname(__FILE__);
}
}
\Piwik\Plugins\API\tests\System\AutoSuggestAPITest::$fixture = new ManyVisitsWithGeoIPAndEcommerce();
|