Skip to content
Extraits de code Groupes Projets
ArchiveCronTest.php 7,2 ko
Newer Older
 * Piwik - free/libre analytics platform
 *
 * @link    http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */
use Interop\Container\ContainerInterface;
use Piwik\Tests\Framework\TestCase\SystemTestCase;
Thomas Steur's avatar
Thomas Steur a validé
use Piwik\Tests\Fixtures\ManySitesImportedLogs;
 * Tests to call the cron core:archive command script and check there is no error,
 * Then call the API testing for "Browser archiving is disabled" (see disableArchiving)
 * This tests that, when archiving is disabled,
 *  then Piwik API will return data that was pre-processed during archive.php run
 *
class ArchiveCronTest extends SystemTestCase
    public static $fixture = null; // initialized below class definition
mattab's avatar
mattab a validé

    public function getApiForTesting()
    {
        $results = array();
        foreach (self::$fixture->getDefaultSegments() as $segmentName => $info) {
            $results[] = array('VisitsSummary.get', array('idSite'     => 'all',
                                                          'date'       => '2012-08-09',
                                                          'periods'    => array('day', 'week', 'month', 'year'),
                                                          'segment'    => $info['definition'],
                                                          'testSuffix' => '_' . $segmentName));


        }
        // API Call Without segments
        $results[] = array('VisitsSummary.get', array('idSite'  => 'all',
                                                      'date'    => '2012-08-09',
                                                      'periods' => array('day', 'month', 'year',  'week')));
        $results[] = array('VisitsSummary.get', array('idSite'     => 'all',
                                                      'date'       => '2012-08-09',
                                                      'periods'    => array('day', 'week', 'month', 'year'),
                                                      'segment'    => 'browserCode==EP',
                                                      'testSuffix' => '_nonPreArchivedSegment'));
        $segments = array(ManySitesImportedLogs::SEGMENT_PRE_ARCHIVED,
                          ManySitesImportedLogs::SEGMENT_PRE_ARCHIVED_CONTAINS_ENCODED
        );
        foreach($segments as $segment) {
            // Test with a pre-processed segment
            $results[] = array(array('VisitsSummary.get', 'Live.getLastVisitsDetails', 'VisitFrequency.get'),
                               array('idSite'     => '1',
                                     'date'       => '2012-08-09',
                                     'periods'    => array('day', 'year'),
                                     'segment'    => $segment,
                                     'testSuffix' => '_preArchivedSegment',
                                     'otherRequestParameters' => array(
                                        'hideColumns' => 'latitude,longitude'
                                     ))
            );
mattab's avatar
mattab a validé

mattab's avatar
mattab a validé
    public function testArchivePhpCron()
    {
        $this->setLastRunArchiveOptions();
mattab's avatar
mattab a validé
        $output = $this->runArchivePhpCron();
mattab's avatar
mattab a validé

        $this->compareArchivePhpOutputAgainstExpected($output);

        foreach ($this->getApiForTesting() as $testInfo) {
mattab's avatar
mattab a validé

            list($api, $params) = $testInfo;
mattab's avatar
mattab a validé

            if (!isset($params['testSuffix'])) {
                $params['testSuffix'] = '';
            }
mattab's avatar
mattab a validé
            $params['testSuffix'] .= '_noOptions';
            $params['disableArchiving'] = true;
mattab's avatar
mattab a validé

mattab's avatar
mattab a validé
            $success = $this->runApiTests($api, $params);

mattab's avatar
mattab a validé
                var_dump($output);
            }
mattab's avatar
mattab a validé

    public function test_archivePhpScript_DoesNotFail_WhenCommandHelpRequested()
    {
        $output = $this->runArchivePhpCron(array('--help' => null), PIWIK_INCLUDE_PATH . '/misc/cron/archive.php');
        $output = implode("\n", $output);

        $this->assertRegExp('/Usage:\s*core:archive/', $output);
        $this->assertNotContains("Starting Piwik reports archiving...", $output);
    }

    private function setLastRunArchiveOptions()
    {
        $periodTypes = array('day', 'periods');
        $idSites = API::getInstance()->getAllSitesId();
mattab's avatar
mattab a validé

        $daysAgoArchiveRanSuccessfully = 1500;
mattab's avatar
mattab a validé
        $this->assertTrue($daysAgoArchiveRanSuccessfully > (\Piwik\CronArchive::ARCHIVE_SITES_WITH_TRAFFIC_SINCE / 86400));
mattab's avatar
mattab a validé
        $time = Date::factory(self::$fixture->dateTime)->subDay($daysAgoArchiveRanSuccessfully)->getTimestamp();
mattab's avatar
mattab a validé

        foreach ($periodTypes as $period) {
            foreach ($idSites as $idSite) {
                // lastRunKey() function inlined
                $lastRunArchiveOption = "lastRunArchive" . $period . "_" . $idSite;
                \Piwik\Option::set($lastRunArchiveOption, $time);
mattab's avatar
mattab a validé

    private function runArchivePhpCron($options = array(), $archivePhpScript = false)
        $archivePhpScript = $archivePhpScript ?: PIWIK_INCLUDE_PATH . '/tests/PHPUnit/proxy/archive.php';
        $urlToProxy = Fixture::getRootUrl() . 'tests/PHPUnit/proxy/index.php';
mattab's avatar
mattab a validé

        $cmd = "php \"$archivePhpScript\" --url=\"$urlToProxy\"";
        foreach ($options as $name => $value) {
            $cmd .= " $name";
            if ($value !== null) {
                $cmd .= "=" . escapeshellarg($value);
            }
        }
        $cmd .= " 2>&1";
mattab's avatar
mattab a validé

        // run the command
        exec($cmd, $output, $result);
        if ($result !== 0 || stripos($result, "error")) {
            $this->fail("archive cron failed: " . implode("\n", $output) . "\n\ncommand used: $cmd");

    private function compareArchivePhpOutputAgainstExpected($output)
    {
        $output = implode("\n", $output);

        $fileName = 'test_ArchiveCronTest_archive_php_cron_output.txt';
        list($pathProcessed, $pathExpected) = static::getProcessedAndExpectedDirs();

        $expectedOutputFile = $pathExpected . $fileName;
        $processedFile = $pathProcessed . $fileName;

        file_put_contents($processedFile, $output);

        try {
            $this->assertTrue(is_readable($expectedOutputFile));
            $this->assertEquals(file_get_contents($expectedOutputFile), $output);
        } catch (Exception $ex) {
            $this->comparisonFailures[] = $ex;
        }
    }

    public static function provideContainerConfigBeforeClass()
    {
        return array(
            'Psr\Log\LoggerInterface' => \DI\get('Monolog\Logger'),

            // for some reason, w/o real translations archiving segments in CronArchive fails. the data returned by CliMulti
            // is a translation token, and nothing else.
            'Piwik\Translation\Translator' => function (ContainerInterface $c) {
                return new \Piwik\Translation\Translator($c->get('Piwik\Translation\Loader\LoaderInterface'));
            }
ArchiveCronTest::$fixture = new ManySitesImportedLogs();
ArchiveCronTest::$fixture->addSegments = true;