File size: 17,616 Bytes
bf8c0ce | 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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | <?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\System;
use Piwik\API\Request;
use Piwik\Common;
use Piwik\Db;
use Piwik\Log\Logger;
use Piwik\Log\LoggerInterface;
use Piwik\Option;
use Piwik\Plugins\UserCountry\LocationProvider;
use Piwik\Scheduler\Schedule\Schedule;
use Piwik\Scheduler\Task;
use Piwik\Scheduler\Timetable;
use Piwik\SettingsPiwik;
use Piwik\Tests\Framework\Fixture;
use Piwik\Tests\Framework\TestCase\IntegrationTestCase;
/**
* @group Core
* @group Tracker
*/
class TrackerTest extends IntegrationTestCase
{
public const TASKS_FINISHED_OPTION_NAME = "Tests.scheduledTasksFinished";
public const TASKS_STARTED_OPTION_NAME = "Tests.scheduledTasksStarted";
public function setUp(): void
{
parent::setUp();
Fixture::createWebsite('2014-02-04');
$testingEnvironment = new \Piwik\Tests\Framework\TestingEnvironmentVariables();
$testingEnvironment->testCaseClass = null;
$testingEnvironment->addFailingScheduledTask = false;
$testingEnvironment->addScheduledTask = false;
$testingEnvironment->save();
Option::delete(self::TASKS_STARTED_OPTION_NAME);
Option::delete(self::TASKS_FINISHED_OPTION_NAME);
Option::delete(Timetable::TIMETABLE_OPTION_STRING);
Option::delete(Timetable::RETRY_OPTION_STRING);
SettingsPiwik::overwritePiwikUrl(self::$fixture->getRootUrl() . "tests/PHPUnit/proxy");
}
protected static function configureFixture($fixture)
{
$fixture->createSuperUser = true;
}
/**
* Test the Bulk tracking API as documented in: https://developer.matomo.org/api-reference/tracking-api#bulk-tracking
*
* With invalid token_auth the request would still work
*/
public function testTrackingApiWithBulkRequestsViaCurlWithWrongTokenAuth()
{
$token_auth = '33dc3f2536d3025974cccb4b4d2d98f4';
// one tracking request is supposed to be invalid, as the token doesn't allow tracking custom ip
$this->issueBulkTrackingRequest($token_auth, true, 1, 1);
}
public function testTrackingApiWithBulkRequestsViaCurlWithCorrectTokenAuth()
{
$token_auth = Fixture::getTokenAuth();
\Piwik\Filesystem::deleteAllCacheOnUpdate();
// both requests should be tracked, as the token doesn't allow tracking custom ip
$this->issueBulkTrackingRequest($token_auth, true, 2, 0);
}
public function testTrackingApiWithBulkRequestsViaCurlWithSecureTokenAuth()
{
\Piwik\Filesystem::deleteAllCacheOnUpdate();
$token = Request::processRequest('UsersManager.createAppSpecificTokenAuth', [
'userLogin' => Fixture::ADMIN_USER_LOGIN,
'passwordConfirmation' => Fixture::ADMIN_USER_PASSWORD,
'description' => 'secure one',
'secureOnly' => true,
]);
$this->issueBulkTrackingRequest($token, true, 2, 0);
}
public function testTrackingEcommerceOrderWithHtmlEscapedTextInsertsCorrectLogs()
{
// item sku, item name, item category, item price, item quantity
// NOTE: used to test with '𝌆' character, however, mysql on travis fails with this when
// inserting this character decoded.
$ecItems = array(array('"scarysku', 'superscarymovie"', 'scary & movies', 12.99, 1),
array('> scary', 'but < "super', 'scary"', 14, 15),
array("'Foo ©", " bar ", " baz ☃ qux", 16, 17));
$urlToTest = $this->getEcommerceItemsUrl($ecItems);
$response = $this->sendTrackingRequestByCurl($urlToTest);
Fixture::checkResponse($response);
$this->assertEquals(1, $this->getCountOfConversions());
$conversionItems = $this->getConversionItems();
$this->assertEquals(3, count($conversionItems));
$this->assertActionEquals('"scarysku', $conversionItems[0]['idaction_sku']);
$this->assertActionEquals('superscarymovie"', $conversionItems[0]['idaction_name']);
$this->assertActionEquals('scary & movies', $conversionItems[0]['idaction_category']);
$this->assertActionEquals('> scary', $conversionItems[1]['idaction_sku']);
$this->assertActionEquals('but < "super', $conversionItems[1]['idaction_name']);
$this->assertActionEquals('scary"', $conversionItems[1]['idaction_category']);
$this->assertActionEquals('\'Foo ©', $conversionItems[2]['idaction_sku']);
$this->assertActionEquals('bar', $conversionItems[2]['idaction_name']);
$this->assertActionEquals('baz ☃ qux', $conversionItems[2]['idaction_category']);
}
public function testTrackingEcommerceOrderWithAmpersandAndQuotesInsertsCorrectLogs()
{
// item sku, item name, item category, item price, item quantity
$ecItems = array(array("\"scarysku&", "superscarymovie'", 'scary <> movies', 12.99, 1));
$urlToTest = $this->getEcommerceItemsUrl($ecItems);
$response = $this->sendTrackingRequestByCurl($urlToTest);
Fixture::checkResponse($response);
$this->assertEquals(1, $this->getCountOfConversions());
$conversionItems = $this->getConversionItems();
$this->assertEquals(1, count($conversionItems));
$this->assertActionEquals('"scarysku&', $conversionItems[0]['idaction_sku']);
$this->assertActionEquals('superscarymovie\'', $conversionItems[0]['idaction_name']);
$this->assertActionEquals('scary <> movies', $conversionItems[0]['idaction_category']);
}
public function testTrackingEcommerceOrderWithNameAndSKUArrays()
{
// item sku, item name, item category, item price, item quantity
$ecItems = array(array(["sku1", "sku2"], ["name1", "name2"], 'category1', 12.99, 1));
$urlToTest = $this->getEcommerceItemsUrl($ecItems);
$response = $this->sendTrackingRequestByCurl($urlToTest);
Fixture::checkResponse($response);
$this->assertEquals(1, $this->getCountOfConversions());
$conversionItems = $this->getConversionItems();
$this->assertEquals(1, count($conversionItems));
$this->assertActionEquals('sku1,sku2', $conversionItems[0]['idaction_sku']);
$this->assertActionEquals('name1,name2', $conversionItems[0]['idaction_name']);
$this->assertActionEquals('category1', $conversionItems[0]['idaction_category']);
}
public function testTrackingEcommerceOrderDoesNotFailWhenEmptyEcommerceItemsParamUsed()
{
// item sku, item name, item category, item price, item quantity
$urlToTest = $this->getEcommerceItemsUrl("");
$response = $this->sendTrackingRequestByCurl($urlToTest);
Fixture::checkResponse($response);
$this->assertEquals(1, $this->getCountOfConversions());
$this->assertEquals(0, count($this->getConversionItems()));
}
public function testTrackingEcommerceOrderDoesNotFailWhenNonArrayUsedWithEcommerceItemsParam()
{
// item sku, item name, item category, item price, item quantity
$urlToTest = $this->getEcommerceItemsUrl("45");
$response = $this->sendTrackingRequestByCurl($urlToTest);
Fixture::checkResponse($response);
$this->assertEquals(0, $this->getCountOfConversions());
$this->assertEquals(0, count($this->getConversionItems()));
}
public function testTrackingEcommerceOrderFailsWhenNonUniqueOrderIsUsed()
{
$ecItems = array(array("\"scarysku&", "superscarymovie'", 'scary <> movies', 12.99, 1));
$urlToTest = $this->getEcommerceItemsUrl($ecItems);
$response = $this->sendTrackingRequestByCurl($urlToTest);
Fixture::checkResponse($response);
$this->assertEquals(1, $this->getCountOfConversions());
$this->assertEquals(1, count($this->getConversionItems()));
$response = $this->sendTrackingRequestByCurl($urlToTest);
self::assertStringContainsString('This resource is part of Matomo.', $response);
$this->assertEquals(1, $this->getCountOfConversions());
$this->assertEquals(1, count($this->getConversionItems()));
}
public function testTrackingWithLangParameterForwardsLangParameterToDefaultLocationProvider()
{
LocationProvider::$providers = null;
LocationProvider::getAllProviders();
LocationProvider::setCurrentProvider(LocationProvider\DefaultProvider::ID);
$urlToTest = "?idsite=1&rec=1&action_name=test&lang=fr-be";
$response = $this->sendTrackingRequestByCurl($urlToTest);
Fixture::checkResponse($response);
$logVisitTable = Common::prefixTable('log_visit');
$visitCount = Db::fetchOne("SELECT COUNT(*) FROM $logVisitTable");
$this->assertEquals(1, $visitCount);
$visitCountry = Db::fetchOne("SELECT location_country FROM $logVisitTable");
$this->assertEquals('be', $visitCountry);
}
public function testScheduledTasksCanBeRunThroughTrackerWithoutIncludingOutputInTrackerOutput()
{
$this->setScheduledTasksToRunInTracker();
$urlToTest = $this->getSimpleTrackingUrl();
$response = $this->sendTrackingRequestByCurl($urlToTest);
Fixture::checkResponse($response);
$this->assertScheduledTasksWereRun();
}
public function testScheduledTasksCanBeRunThroughTrackerWithOutputIncludedIfDebugQueryParamUsed()
{
$environment = $this->setScheduledTasksToRunInTracker();
$environment->overrideConfig('log', 'log_writers', array('screen'));
$environment->save();
$urlToTest = $this->getSimpleTrackingUrl() . '&debug=1';
$response = $this->sendTrackingRequestByCurl($urlToTest);
$this->assertScheduledTasksWereRun();
self::assertStringContainsString('Scheduled Tasks: Starting...', $response);
}
public function getTypesOfErrorsForScheduledTasksTrackerFailureTest()
{
return array(
array(true),
array(false),
);
}
/**
* @dataProvider getTypesOfErrorsForScheduledTasksTrackerFailureTest
*/
public function testScheduledTasksDoNotFailTrackingWhenScheduledTaskFails($doFatalError)
{
$this->setScheduledTasksToRunInTracker();
$this->addFailingScheduledTaskToTracker($doFatalError);
$urlToTest = $this->getSimpleTrackingUrl();
$response = $this->sendTrackingRequestByCurl($urlToTest);
Fixture::checkResponse($response);
if ($doFatalError) {
$this->assertScheduledTasksWereNotRun();
} else {
$this->assertScheduledTasksWereRun();
}
}
protected function issueBulkTrackingRequest($token_auth, $expectTrackingToSucceed, $tracked, $invalid)
{
$piwikHost = Fixture::getRootUrl() . 'tests/PHPUnit/proxy/matomo.php';
// Note: The first request requires a valid super user token, because of the custom ip
$command = 'curl -s -X POST -d \'{"requests":["?idsite=1&url=http://example.org&action_name=Test bulk log Pageview&cip=1.1.1.1&rec=1","?idsite=1&url=http://example.net/test.htm&action_name=Another bulk page view&rec=1"],"token_auth":"' . $token_auth . '"}\' ' . $piwikHost;
exec($command, $output, $result);
if ($result !== 0) {
throw new \Exception("tracking bulk failed: " . implode("\n", $output) . "\n\ncommand used: $command");
}
$output = implode("", $output);
$this->assertStringStartsWith('{"status":', $output);
$response = json_decode($output, true);
if ($expectTrackingToSucceed) {
self::assertEquals('success', $response['status']);
} else {
self::assertEquals('error', $response['status']);
}
self::assertEquals($tracked, $response['tracked']);
self::assertEquals($invalid, $response['invalid']);
}
private function sendTrackingRequestByCurl($url)
{
if (!function_exists('curl_init')) {
$this->markTestSkipped('Curl is not installed');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, Fixture::getRootUrl() . 'tests/PHPUnit/proxy/matomo.php' . $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$response = substr($response, $headerSize);
curl_close($ch);
return $response;
}
private function assertActionEquals($expected, $idaction)
{
$actionName = Db::fetchOne("SELECT name FROM " . Common::prefixTable('log_action') . " WHERE idaction = ?", array($idaction));
$this->assertEquals($expected, $actionName);
}
private function getCountOfConversions()
{
return Db::fetchOne("SELECT COUNT(*) FROM " . Common::prefixTable('log_conversion'));
}
private function getConversionItems()
{
return Db::fetchAll("SELECT * FROM " . Common::prefixTable('log_conversion_item'));
}
private function getEcommerceItemsUrl($ecItems, $doJsonEncode = true)
{
$ecItemsStr = $doJsonEncode ? json_encode($ecItems) : $ecItems;
return "?idsite=1&idgoal=0&rec=1&url=" . urlencode('http://quellehorreur.com/movies') . "&ec_items="
. urlencode($ecItemsStr) . '&ec_id=myspecial-id-1234&revenue=16.99&ec_st=12.99&ec_tx=0&ec_sh=3';
}
private function getSimpleTrackingUrl()
{
return "?idsite=1&rec=1&url=" . urlencode('http://quellehorreur.com/movies') . "&action_name=Movies";
}
private function setScheduledTasksToRunInTracker()
{
$testingEnvironment = new \Piwik\Tests\Framework\TestingEnvironmentVariables();
$testingEnvironment->testCaseClass = 'Piwik\Tests\System\TrackerTest';
$testingEnvironment->addScheduledTask = true;
$testingEnvironment->overrideConfig('Tracker', array('scheduled_tasks_min_interval' => 1, 'debug_on_demand' => 1));
$testingEnvironment->overrideConfig('log', array());
$testingEnvironment->save();
return $testingEnvironment;
}
private function addFailingScheduledTaskToTracker($doFatalError)
{
$testingEnvironment = new \Piwik\Tests\Framework\TestingEnvironmentVariables();
$testingEnvironment->addFailingScheduledTask = true;
$testingEnvironment->scheduledTaskFailureShouldBeFatal = $doFatalError;
$testingEnvironment->save();
}
public function provideContainerConfig()
{
if (!defined('DEBUG_FORCE_SCHEDULED_TASKS')) {
define('DEBUG_FORCE_SCHEDULED_TASKS', 1);
}
$testingEnvironment = new \Piwik\Tests\Framework\TestingEnvironmentVariables();
$tasksToAdd = array();
if ($testingEnvironment->addFailingScheduledTask) {
if ($testingEnvironment->scheduledTaskFailureShouldBeFatal) {
$tasksToAdd[] = new Task($this, 'triggerFatalError', null, Schedule::factory('hourly'));
} else {
$tasksToAdd[] = new Task($this, 'throwScheduledTaskException', null, Schedule::factory('hourly'));
}
}
if ($testingEnvironment->addScheduledTask) {
$tasksToAdd[] = new Task($this, 'markScheduledTaskExecutionFinished', null, Schedule::factory('hourly'));
}
$result = array();
if (!empty($tasksToAdd)) {
$initialTask = new Task($this, 'markCustomTaskExecuted', null, Schedule::factory('hourly'));
$tasksToAdd = array_merge(array($initialTask), $tasksToAdd);
$mockTaskLoader = $this->createPartialMock('Piwik\Scheduler\TaskLoader', array('loadTasks'));
$mockTaskLoader->expects($this->any())->method('loadTasks')->will($this->returnValue($tasksToAdd));
$result['Piwik\Scheduler\TaskLoader'] = $mockTaskLoader;
}
return $result;
}
public function triggerFatalError()
{
require 'thehowling';
}
public function throwScheduledTaskException()
{
throw new \Exception("triggered exception");
}
public function markScheduledTaskExecutionFinished()
{
Option::set(self::TASKS_FINISHED_OPTION_NAME, 1);
}
public function markCustomTaskExecuted()
{
Option::set(self::TASKS_STARTED_OPTION_NAME, 1);
}
private function assertScheduledTasksWereRun()
{
$this->assertCustomTasksWereStarted();
Option::clearCachedOption(self::TASKS_FINISHED_OPTION_NAME);
$this->assertEquals(1, Option::get(self::TASKS_FINISHED_OPTION_NAME));
}
private function assertScheduledTasksWereNotRun()
{
$this->assertCustomTasksWereStarted();
Option::clearCachedOption(self::TASKS_FINISHED_OPTION_NAME);
$this->assertFalse(Option::get(self::TASKS_FINISHED_OPTION_NAME));
}
private function assertCustomTasksWereStarted()
{
Option::clearCachedOption(self::TASKS_STARTED_OPTION_NAME);
$this->assertEquals(1, Option::get(self::TASKS_STARTED_OPTION_NAME));
}
public static function provideContainerConfigBeforeClass()
{
return array(
LoggerInterface::class => \Piwik\DI::get(Logger::class),
'Tests.log.allowAllHandlers' => true,
);
}
}
|