Upload folder using huggingface_hub (part 8)
Browse filesFiles changed (32)
- .gitattributes+1
- plugins/ArchivingMetrics/tests/Integration/TasksTest.phpAdded+92
- plugins/ArchivingMetrics/tests/Integration/TimerDbTest.phpAdded+57
- plugins/ArchivingMetrics/tests/Unit/TimerTest.phpAdded+616
- plugins/Bandwidth/.gitattributesAdded+6
- plugins/Bandwidth/.github/workflows/matomo-ai-checklist.ymlAdded+32
- plugins/Bandwidth/.github/workflows/matomo-tests.ymlAdded+74
- plugins/Bandwidth/.github/workflows/phpcs.ymlAdded+43
- plugins/Bandwidth/.gitignoreAdded+2
- plugins/Bandwidth/phpcs.xmlAdded+36
- plugins/Bandwidth/phpstan.neonAdded+21
- plugins/Bandwidth/screenshots/Downloads.pngAdded
- plugins/Bandwidth/screenshots/Pageviews.pngAdded
- plugins/Bandwidth/screenshots/Visitor_Overview.pngAdded
- plugins/Bandwidth/tests/Fixtures/OneVisitWithBandwidth.phpAdded+136
- plugins/Bandwidth/tests/Framework/TestCase/IntegrationTestCase.phpAdded+122
- plugins/Bandwidth/tests/Integration/APITest.phpAdded+133
- plugins/Bandwidth/tests/Integration/BandwidthTest.phpAdded+190
- plugins/Bandwidth/tests/System/CheckDirectDependencyUseCommandTest.phpAdded+48
- plugins/Bandwidth/tests/UI/Bandwidth_spec.jsAdded+87
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_downloads.pngAdded
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_downloads_flat.pngAdded
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_downloads_no_bandwidth.pngAdded
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_no_bandwidth_on_day_but_in_month.pngAdded
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_titles.pngAdded
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_titles_no_bandwidth.pngAdded
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_urls.pngAdded
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_urls_flat.pngAdded
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_urls_no_bandwidth.pngAdded
- plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_visitors_overview.pngAdded
- plugins/Bandwidth/tests/Unit/BandwidthTest.phpAdded+66
- plugins/Bandwidth/tests/Unit/MetricsTest.phpAdded+38
86 unmodified lines87888986 unmodified linestests/javascript/jash/** linguist-vendoredtests/javascript/jslint/** linguist-vendoredplugins/AnonymousPiwikUsageMeasurement/screenshots/AdminSettings.png filter=lfs diff=lfs merge=lfs -text86 unmodified lines8788899086 unmodified linestests/javascript/jash/** linguist-vendoredtests/javascript/jslint/** linguist-vendoredplugins/AnonymousPiwikUsageMeasurement/screenshots/AdminSettings.png filter=lfs diff=lfs merge=lfs -textplugins/Bandwidth/screenshots/Visitor_Overview.png filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
declare(strict_types=1);
namespace Piwik\Plugins\ArchivingMetrics\tests\Integration;
use Piwik\Common;use Piwik\Config;use Piwik\Date;use Piwik\Db;use Piwik\Plugins\ArchivingMetrics\Tasks;use Piwik\Tests\Framework\Fixture;use Piwik\Tests\Framework\TestCase\IntegrationTestCase;
/** * @group ArchivingMetrics * @group ArchivingMetrics_Tasks * @group Plugins */class TasksTest extends IntegrationTestCase{ public function testPurgeOldMetricsDeletesRowsOlderThanRetention(): void { $config = Config::getInstance(); $config->ArchivingMetrics = ['retention_days' => 30];
$this->insertRow(Date::now()->subDay(31)->getDatetime()); $this->insertRow(Date::now()->subDay(5)->getDatetime());
$task = new Tasks(); $task->purgeOldMetrics();
$count = (int) Db::fetchOne('SELECT COUNT(*) FROM ' . Common::prefixTable('archiving_metrics')); $this->assertSame(1, $count); }
public function testPurgeOldMetricsDisabledKeepsRows(): void { $config = Config::getInstance(); $config->ArchivingMetrics = ['retention_days' => 0];
$this->insertRow(Date::now()->subDay(400)->getDatetime());
$task = new Tasks(); $task->purgeOldMetrics();
$count = (int) Db::fetchOne('SELECT COUNT(*) FROM ' . Common::prefixTable('archiving_metrics')); $this->assertSame(1, $count); }
public function testPurgeMetricsForDeletedSitesRemovesOrphanedRows(): void { $idSite = Fixture::createWebsite('2024-01-01 00:00:00');
$this->insertRow(Date::now()->subDay(5)->getDatetime(), $idSite); $this->insertRow(Date::now()->subDay(5)->getDatetime(), 9999);
$task = new Tasks(); $task->purgeMetricsForDeletedSites();
$count = (int) Db::fetchOne('SELECT COUNT(*) FROM ' . Common::prefixTable('archiving_metrics')); $this->assertSame(1, $count); }
private function insertRow(string $tsStarted, int $idSite = 1): void { $table = Common::prefixTable('archiving_metrics'); Db::query( "INSERT INTO {$table} (idarchive, idsite, archive_name, date1, date2, period, ts_started, ts_finished, total_time, total_time_exclusive) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [ 1, $idSite, 'done', '2025-01-01', '2025-01-01', 1, $tsStarted, $tsStarted, 123, 100, ] ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
declare(strict_types=1);
namespace Piwik\Plugins\ArchivingMetrics\tests\Integration;
use Piwik\Common;use Piwik\Db;use Piwik\Period;use Piwik\Plugins\ArchivingMetrics\Clock\Clock;use Piwik\Plugins\ArchivingMetrics\Context;use Piwik\Plugins\ArchivingMetrics\Timer;use Piwik\Plugins\ArchivingMetrics\Writer\DbWriter;use Piwik\Segment;use Piwik\Tests\Framework\TestCase\IntegrationTestCase;
/** * @group ArchivingMetrics * @group ArchivingMetrics_TimerDb * @group Plugins */class TimerDbTest extends IntegrationTestCase{ public function testItWritesAndReadsFromDatabase(): void { $period = new Period\Day(\Piwik\Date::factory('2020-11-01')); $segment = new Segment('', [1]); $context = new Context(1, $period, $segment, '');
$timer = new Timer(true, new Clock(), new DbWriter()); $timer->start($context); $timer->complete($context, [999], false);
$rows = Db::fetchAll('SELECT * FROM ' . Common::prefixTable('archiving_metrics'));
self::assertCount(1, $rows, 'Expected archiving_metrics table to have exactly one record.'); self::assertSame(999, (int) $rows[0]['idarchive']); self::assertSame(1, (int) $rows[0]['idsite']); self::assertNotEmpty($rows[0]['archive_name']); self::assertSame('2020-11-01', $rows[0]['date1']); self::assertSame('2020-11-01', $rows[0]['date2']); self::assertIsNumeric($rows[0]['period']); self::assertNotEmpty($rows[0]['ts_started']); self::assertNotEmpty($rows[0]['ts_finished']); self::assertIsNumeric($rows[0]['total_time']); self::assertIsNumeric($rows[0]['total_time_exclusive']); self::assertArrayHasKey('is_temporary', $rows[0]); self::assertSame(0, (int) $rows[0]['is_temporary']); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
declare(strict_types=1);
namespace Piwik\Plugins\ArchivingMetrics\tests\Unit;
use PHPUnit\Framework\TestCase;use Piwik\ArchiveProcessor\Rules;use Piwik\Date;use Piwik\Period\Factory;use Piwik\Plugins\ArchivingMetrics\Clock\ClockInterface;use Piwik\Plugins\ArchivingMetrics\Context;use Piwik\Plugins\ArchivingMetrics\Timer;use Piwik\Plugins\ArchivingMetrics\Writer\WriterInterface;use Piwik\Segment;
/** * @group ArchivingMetrics * @group ArchivingMetrics_Timer * @group Plugins */class TimerTest extends TestCase{ /** * @dataProvider timerProvider */ public function testItRecordsArchivingRunsWithCorrectTiming(array $events, array $microtimes, array $expectedRecords): void { $writer = new InMemoryWriter(); $clock = $this->createMock(ClockInterface::class); $clock->method('microtime')->willReturnOnConsecutiveCalls(...$microtimes); $timer = new Timer(true, $clock, $writer);
foreach ($events as $event) { $context = $this->createContext($event['context']); if ($event['action'] === 'start') { $timer->start($context); continue; }
$timer->complete( $context, $event['idArchives'], $event['cached'] ); }
$this->assertSame($expectedRecords, $writer->records); }
public function testItSkipsWhenArchivePhpNotTriggered(): void { $writer = new InMemoryWriter(); $clock = $this->createMock(ClockInterface::class); $clock->method('microtime')->willReturnOnConsecutiveCalls(0.0); $timer = new Timer(false, $clock, $writer);
$context = $this->createContext([ 'idSite' => 1, 'segment' => '', 'plugin' => '', 'date1' => '2024-01-01', 'date2' => '2024-01-01', 'period' => 'day', ]);
$timer->start($context); $timer->complete($context, [123], false);
$this->assertSame([], $writer->records); }
/** * @dataProvider isTemporaryArchiveProvider */ public function testItSetsIsTemporaryFlagCorrectly( string $periodLabel, string $date, string $siteTimezone, int $startTimestamp, int $expectedIsTemporary ): void { $writer = new TimingCaptureWriter(); $clock = $this->createMock(ClockInterface::class); $clock->method('microtime')->willReturnOnConsecutiveCalls( $startTimestamp, $startTimestamp + 1 ); $timer = new Timer(true, $clock, $writer);
$period = Factory::build($periodLabel, $date); $segment = $this->createSegment(''); $context = new Context(1, $period, $segment, '', false, $siteTimezone);
$timer->start($context); $timer->complete($context, [123], false);
$this->assertCount(1, $writer->records); $this->assertSame($expectedIsTemporary, $writer->records[0]['timing']['is_temporary']); }
public function isTemporaryArchiveProvider(): \Generator { yield 'day in progress is temporary' => [ 'periodLabel' => 'day', 'date' => '2025-11-01', 'siteTimezone' => 'UTC', 'startTimestamp' => self::timestampInTimezone('2025-11-01 12:00:00', 'UTC'), 'expectedIsTemporary' => 1, ]; yield 'past day is not temporary' => [ 'periodLabel' => 'day', 'date' => '2025-10-31', 'siteTimezone' => 'UTC', 'startTimestamp' => self::timestampInTimezone('2025-11-01 00:00:00', 'UTC'), 'expectedIsTemporary' => 0, ]; yield 'week in progress is temporary' => [ 'periodLabel' => 'week', 'date' => '2025-11-01', 'siteTimezone' => 'UTC', 'startTimestamp' => self::timestampInTimezone('2025-11-01 12:00:00', 'UTC'), 'expectedIsTemporary' => 1, ]; yield 'past week is not temporary' => [ 'periodLabel' => 'week', 'date' => '2025-10-20', 'siteTimezone' => 'UTC', 'startTimestamp' => self::timestampInTimezone('2025-11-01 12:00:00', 'UTC'), 'expectedIsTemporary' => 0, ]; yield 'month in progress is temporary' => [ 'periodLabel' => 'month', 'date' => '2025-11-01', 'siteTimezone' => 'UTC', 'startTimestamp' => self::timestampInTimezone('2025-11-15 12:00:00', 'UTC'), 'expectedIsTemporary' => 1, ]; yield 'year in progress is temporary' => [ 'periodLabel' => 'year', 'date' => '2025-01-01', 'siteTimezone' => 'UTC', 'startTimestamp' => self::timestampInTimezone('2025-06-01 12:00:00', 'UTC'), 'expectedIsTemporary' => 1, ]; yield 'range in progress is temporary' => [ 'periodLabel' => 'range', 'date' => '2025-11-01,2025-11-10', 'siteTimezone' => 'UTC', 'startTimestamp' => self::timestampInTimezone('2025-11-05 12:00:00', 'UTC'), 'expectedIsTemporary' => 1, ]; yield 'exactly at period end is not temporary' => [ 'periodLabel' => 'day', 'date' => '2025-11-01', 'siteTimezone' => 'UTC', 'startTimestamp' => self::timestampInTimezone('2025-11-01 23:59:59', 'UTC'), 'expectedIsTemporary' => 0, ]; yield 'one second before period end is temporary' => [ 'periodLabel' => 'day', 'date' => '2025-11-01', 'siteTimezone' => 'UTC', 'startTimestamp' => self::timestampInTimezone('2025-11-01 23:59:58', 'UTC'), 'expectedIsTemporary' => 1, ]; yield 'site timezone affects temporary determination' => [ 'periodLabel' => 'day', 'date' => '2025-11-02', 'siteTimezone' => 'America/Los_Angeles', 'startTimestamp' => self::timestampInTimezone('2025-11-02 23:30:00', 'America/Los_Angeles'), 'expectedIsTemporary' => 1, ]; yield 'site timezone with positive UTC offset in progress' => [ 'periodLabel' => 'day', 'date' => '2025-11-02', 'siteTimezone' => 'Asia/Tokyo', 'startTimestamp' => self::timestampInTimezone('2025-11-01 00:00:00', 'Asia/Tokyo'), 'expectedIsTemporary' => 1, ]; yield 'site timezone with positive UTC offset after day end' => [ 'periodLabel' => 'day', 'date' => '2025-11-02', 'siteTimezone' => 'Asia/Tokyo', 'startTimestamp' => self::timestampInTimezone('2025-11-03 00:00:00', 'Asia/Tokyo'), 'expectedIsTemporary' => 0, ]; yield 'site timezone with negative UTC offset after day end' => [ 'periodLabel' => 'day', 'date' => '2025-11-02', 'siteTimezone' => 'America/Los_Angeles', 'startTimestamp' => self::timestampInTimezone('2025-11-10 12:00:00', 'America/Los_Angeles'), 'expectedIsTemporary' => 0, ]; yield 'dst start day before local day end stays temporary' => [ 'periodLabel' => 'day', 'date' => '2025-03-09', 'siteTimezone' => 'America/Los_Angeles', 'startTimestamp' => self::timestampInTimezone('2025-03-09 23:00:00', 'America/Los_Angeles'), 'expectedIsTemporary' => 1, ]; yield 'dst end day clearly before local day end is temporary' => [ 'periodLabel' => 'day', 'date' => '2025-11-02', 'siteTimezone' => 'America/Los_Angeles', 'startTimestamp' => self::timestampInTimezone('2025-11-02 18:00:00', 'America/Los_Angeles'), 'expectedIsTemporary' => 1, ]; }
public function timerProvider(): array { // Blank segment ensures Rules::getDoneStringFlagFor returns "done" so the timer is active. $base = [ 'idSite' => 1, 'segment' => '', 'plugin' => '', 'date1' => '2024-01-01', 'date2' => '2024-01-01', ];
return [ 'single period' => [ 'events' => [ ['action' => 'start', 'context' => array_merge($base, ['period' => 'day'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'day']), 'idArchives' => [101], 'cached' => false], ], 'microtimes' => [ strtotime('2024-01-01 00:00:00'), strtotime('2024-01-01 00:00:00') + 1.2, ], 'expectedRecords' => [ [ 'idarchive' => 101, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-01', 'date2' => '2024-01-01', 'period' => 1, 'ts_started' => '2024-01-01 00:00:00', 'ts_finished' => '2024-01-01 00:00:01', 'total_time' => 1200, 'total_time_exclusive' => 1200, ], ], ], 'mix of events with no nesting' => [ 'events' => [ ['action' => 'start', 'context' => array_merge($base, ['period' => 'year', 'date1' => '2024-01-01', 'date2' => '2024-12-31'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'year', 'date1' => '2024-01-01', 'date2' => '2024-12-31']), 'idArchives' => [303], 'cached' => false], ['action' => 'start', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-02-01', 'date2' => '2024-02-01'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-02-01', 'date2' => '2024-02-01']), 'idArchives' => [204], 'cached' => false], ['action' => 'start', 'context' => array_merge($base, ['period' => 'month', 'date1' => '2024-02-01', 'date2' => '2024-02-29'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'month', 'date1' => '2024-02-01', 'date2' => '2024-02-29']), 'idArchives' => [202], 'cached' => false], ], 'microtimes' => [ strtotime('2024-01-01 00:00:00'), strtotime('2024-01-01 00:00:00') + 6.3, strtotime('2024-02-01 00:00:01'), strtotime('2024-02-01 00:00:01') + 5.4, strtotime('2024-02-01 00:00:01'), strtotime('2024-02-01 00:00:01') + 12.3, ], 'expectedRecords' => [ [ 'idarchive' => 303, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-01', 'date2' => '2024-12-31', 'period' => 4, 'ts_started' => '2024-01-01 00:00:00', 'ts_finished' => '2024-01-01 00:00:06', 'total_time' => 6300, 'total_time_exclusive' => 6300, ], [ 'idarchive' => 204, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-02-01', 'date2' => '2024-02-01', 'period' => 1, 'ts_started' => '2024-02-01 00:00:01', 'ts_finished' => '2024-02-01 00:00:06', 'total_time' => 5400, 'total_time_exclusive' => 5400, ], [ 'idarchive' => 202, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-02-01', 'date2' => '2024-02-29', 'period' => 3, 'ts_started' => '2024-02-01 00:00:01', 'ts_finished' => '2024-02-01 00:00:13', 'total_time' => 12300, 'total_time_exclusive' => 12300, ], ], ], 'mix of events with no nesting and some fetched from cache' => [ 'events' => [ ['action' => 'start', 'context' => array_merge($base, ['period' => 'year', 'date1' => '2024-01-01', 'date2' => '2024-12-31'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'year', 'date1' => '2024-01-01', 'date2' => '2024-12-31']), 'idArchives' => [303], 'cached' => true], ['action' => 'start', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-02-01', 'date2' => '2024-02-01'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-02-01', 'date2' => '2024-02-01']), 'idArchives' => [204], 'cached' => false], ['action' => 'start', 'context' => array_merge($base, ['period' => 'month', 'date1' => '2024-02-01', 'date2' => '2024-02-29'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'month', 'date1' => '2024-02-01', 'date2' => '2024-02-29']), 'idArchives' => [202], 'cached' => true], ], 'microtimes' => [ strtotime('2024-01-01 00:00:00'), strtotime('2024-02-01 00:00:00'), strtotime('2024-02-01 00:00:00') + 3.0, strtotime('2024-02-01 00:00:01'), ], 'expectedRecords' => [ [ 'idarchive' => 204, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-02-01', 'date2' => '2024-02-01', 'period' => 1, 'ts_started' => '2024-02-01 00:00:00', 'ts_finished' => '2024-02-01 00:00:03', 'total_time' => 3000, 'total_time_exclusive' => 3000, ], ], ], 'nested day inside week' => [ 'events' => [ ['action' => 'start', 'context' => array_merge($base, ['period' => 'week', 'date1' => '2024-01-08', 'date2' => '2024-01-14'])], ['action' => 'start', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-01-10', 'date2' => '2024-01-10'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-01-10', 'date2' => '2024-01-10']), 'idArchives' => [202], 'cached' => false], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'week', 'date1' => '2024-01-08', 'date2' => '2024-01-14']), 'idArchives' => [303], 'cached' => false], ], 'microtimes' => [ strtotime('2024-01-01 00:00:00'), strtotime('2024-01-01 00:00:00') + 0.5, strtotime('2024-01-01 00:00:00') + 1.1, strtotime('2024-01-01 00:00:00') + 2.5, ], 'expectedRecords' => [ [ 'idarchive' => 202, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-10', 'date2' => '2024-01-10', 'period' => 1, 'ts_started' => '2024-01-01 00:00:00', 'ts_finished' => '2024-01-01 00:00:01', 'total_time' => 600, 'total_time_exclusive' => 600, ], [ 'idarchive' => 303, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-08', 'date2' => '2024-01-14', 'period' => 2, 'ts_started' => '2024-01-01 00:00:00', 'ts_finished' => '2024-01-01 00:00:02', 'total_time' => 2500, 'total_time_exclusive' => 1900, ], ], ], 'full cascade year <-> day' => [ 'events' => [ ['action' => 'start', 'context' => array_merge($base, ['period' => 'year', 'date1' => '2024-01-01', 'date2' => '2024-12-31'])], ['action' => 'start', 'context' => array_merge($base, ['period' => 'month', 'date1' => '2024-01-01', 'date2' => '2024-01-31'])], ['action' => 'start', 'context' => array_merge($base, ['period' => 'week', 'date1' => '2024-01-08', 'date2' => '2024-01-14'])], ['action' => 'start', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-01-10', 'date2' => '2024-01-10'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-01-10', 'date2' => '2024-01-10']), 'idArchives' => [202], 'cached' => false], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'week', 'date1' => '2024-01-08', 'date2' => '2024-01-14']), 'idArchives' => [303], 'cached' => false], ['action' => 'start', 'context' => array_merge($base, ['period' => 'week', 'date1' => '2024-01-15', 'date2' => '2024-01-22'])], ['action' => 'start', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-01-20', 'date2' => '2024-01-20'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-01-20', 'date2' => '2024-01-20']), 'idArchives' => [404], 'cached' => false], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'week', 'date1' => '2024-01-15', 'date2' => '2024-01-21']), 'idArchives' => [505], 'cached' => false], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'month', 'date1' => '2024-01-01', 'date2' => '2024-01-31']), 'idArchives' => [606], 'cached' => false], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'year', 'date1' => '2024-01-01', 'date2' => '2024-12-31']), 'idArchives' => [707], 'cached' => false], ], 'microtimes' => [ strtotime('2024-01-01 00:00:00'), strtotime('2024-01-01 00:00:00') + 1, strtotime('2024-01-01 00:00:00') + 2, strtotime('2024-01-01 00:00:00') + 4, strtotime('2024-01-01 00:00:00') + 8, strtotime('2024-01-01 00:00:00') + 16, strtotime('2024-01-01 00:00:00') + 32, strtotime('2024-01-01 00:00:00') + 64, strtotime('2024-01-01 00:00:00') + 128, strtotime('2024-01-01 00:00:00') + 256, strtotime('2024-01-01 00:00:00') + 512, strtotime('2024-01-01 00:00:00') + 1024, ], 'expectedRecords' => [ [ 'idarchive' => 202, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-10', 'date2' => '2024-01-10', 'period' => 1, 'ts_started' => '2024-01-01 00:00:04', 'ts_finished' => '2024-01-01 00:00:08', 'total_time' => 4000, 'total_time_exclusive' => 4000, ], [ 'idarchive' => 303, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-08', 'date2' => '2024-01-14', 'period' => 2, 'ts_started' => '2024-01-01 00:00:02', 'ts_finished' => '2024-01-01 00:00:16', 'total_time' => 14000, 'total_time_exclusive' => 10000, ], [ 'idarchive' => 404, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-20', 'date2' => '2024-01-20', 'period' => 1, 'ts_started' => '2024-01-01 00:01:04', 'ts_finished' => '2024-01-01 00:02:08', 'total_time' => 64000, 'total_time_exclusive' => 64000, ], [ 'idarchive' => 505, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-15', 'date2' => '2024-01-21', 'period' => 2, 'ts_started' => '2024-01-01 00:00:32', 'ts_finished' => '2024-01-01 00:04:16', 'total_time' => 224000, 'total_time_exclusive' => 160000, ], [ 'idarchive' => 606, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-01', 'date2' => '2024-01-31', 'period' => 3, 'ts_started' => '2024-01-01 00:00:01', 'ts_finished' => '2024-01-01 00:08:32', 'total_time' => 511000, 'total_time_exclusive' => 273000, ], [ 'idarchive' => 707, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-01-01', 'date2' => '2024-12-31', 'period' => 4, 'ts_started' => '2024-01-01 00:00:00', 'ts_finished' => '2024-01-01 00:17:04', 'total_time' => 1024000, 'total_time_exclusive' => 513000, ], ], ], 'segments have timings recorded' => [ 'events' => [ ['action' => 'start', 'context' => array_merge($base, ['period' => 'year', 'date1' => '2024-01-01', 'date2' => '2024-12-31', 'segment' => 'browserCode==FF'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'year', 'date1' => '2024-01-01', 'date2' => '2024-12-31', 'segment' => 'browserCode==FF']), 'idArchives' => [303], 'cached' => false], ['action' => 'start', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-02-01', 'date2' => '2024-02-01'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'day', 'date1' => '2024-02-01', 'date2' => '2024-02-01']), 'idArchives' => [204], 'cached' => false], ['action' => 'start', 'context' => array_merge($base, ['period' => 'month', 'date1' => '2024-02-01', 'date2' => '2024-02-29'])], ['action' => 'complete', 'context' => array_merge($base, ['period' => 'month', 'date1' => '2024-02-01', 'date2' => '2024-02-29']), 'idArchives' => [202], 'cached' => false], ], 'microtimes' => [ strtotime('2024-01-01 00:00:00'), strtotime('2024-01-01 00:00:00') + 6.3, strtotime('2024-02-01 00:00:01'), strtotime('2024-02-01 00:00:01') + 5.4, strtotime('2024-02-01 00:00:01'), strtotime('2024-02-01 00:00:01') + 12.3, ], 'expectedRecords' => [ [ 'idarchive' => 303, 'idsite' => 1, 'archive_name' => 'done' . md5('browserCode==FF'), 'date1' => '2024-01-01', 'date2' => '2024-12-31', 'period' => 4, 'ts_started' => '2024-01-01 00:00:00', 'ts_finished' => '2024-01-01 00:00:06', 'total_time' => 6300, 'total_time_exclusive' => 6300, ], [ 'idarchive' => 204, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-02-01', 'date2' => '2024-02-01', 'period' => 1, 'ts_started' => '2024-02-01 00:00:01', 'ts_finished' => '2024-02-01 00:00:06', 'total_time' => 5400, 'total_time_exclusive' => 5400, ], [ 'idarchive' => 202, 'idsite' => 1, 'archive_name' => 'done', 'date1' => '2024-02-01', 'date2' => '2024-02-29', 'period' => 3, 'ts_started' => '2024-02-01 00:00:01', 'ts_finished' => '2024-02-01 00:00:13', 'total_time' => 12300, 'total_time_exclusive' => 12300, ], ], ], ]; }
private function createContext(array $data): Context { $period = Factory::build($data['period'], $data['date1']);
$segment = $this->createSegment($data['segment']);
return new Context( $data['idSite'], $period, $segment, $data['plugin'], $data['report'] ?? false ); } private function createSegment(string $segmentString): Segment { $segment = $this->createMock(Segment::class); $segment->method('getString')->willReturn($segmentString); $segment->method('getHash')->willReturn($segmentString === '' ? '' : md5(urldecode($segmentString))); $segment->method('isEmpty')->willReturn($segmentString === ''); return $segment; }
private static function timestampInTimezone(string $datetime, string $timezone): int { return Date::factory($datetime, $timezone)->getTimestampUTC(); }}
class InMemoryWriter implements WriterInterface{ public $records = [];
public function write(Context $context, array $timing): void { $baseTiming = [ 'idarchive' => $timing['idarchive'], 'ts_started' => $timing['ts_started'], 'ts_finished' => $timing['ts_finished'], 'total_time' => $timing['total_time'], 'total_time_exclusive' => $timing['total_time_exclusive'], ];
$this->records[] = array_merge( [ 'idarchive' => $baseTiming['idarchive'], 'idsite' => $context->idSite, 'archive_name' => Rules::getDoneStringFlagFor( [$context->idSite], $context->segment, $context->period->getLabel(), $context->plugin ), 'date1' => $context->period->getDateTimeStart()->toString('Y-m-d'), 'date2' => $context->period->getDateTimeEnd()->toString('Y-m-d'), 'period' => $context->period->getId(), ], $baseTiming ); }}
class TimingCaptureWriter implements WriterInterface{ public $records = [];
public function write(Context $context, array $timing): void { $this->records[] = [ 'context' => $context, 'timing' => $timing, ]; }}123456# Files excluded from git packagestests/ export-ignore.github/ export-ignore.gitignore export-ignore.gitattributes export-ignore.travis.yml export-ignore1234567891011121314151617181920212223242526272829303132# Action for running tests
name: AI Checklist
on: pull_request: types: [opened, synchronize, reopened, edited]
permissions: actions: read checks: none contents: none deployments: none issues: none packages: none pull-requests: read repository-projects: none security-events: none statuses: none
concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true
jobs: AiChecklist: runs-on: ubuntu-24.04 strategy: fail-fast: false steps: - name: Run tests uses: matomo-org/github-action-checklist-gate@main1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# Action for running tests# This file has been automatically created.# To recreate it you can run this command# ./console generate:test-action --plugin="Bandwidth" --php-versions="matomo5_min_php,matomo5_max_php" --schedule-cron="10 2 * * 6"
name: Plugin Bandwidth Tests
on: pull_request: types: [opened, synchronize] push: branches: - '**.x-dev' workflow_dispatch: schedule: - cron: "10 2 * * 6"
permissions: actions: read checks: none contents: read deployments: none issues: read packages: none pull-requests: read repository-projects: none security-events: none statuses: none
concurrency: group: php-${{ github.ref }} cancel-in-progress: true
jobs: PluginTests: runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: php: [ 'matomo5_min_php', 'matomo5_max_php' ] target: ['minimum_required_matomo', 'maximum_supported_matomo'] steps: - uses: actions/checkout@v3 with: lfs: true persist-credentials: false - name: Install package ripgrep run: sudo apt-get install ripgrep - name: Run tests uses: matomo-org/github-action-tests@main with: plugin-name: 'Bandwidth' php-version: ${{ matrix.php }} test-type: 'PluginTests' matomo-test-branch: ${{ matrix.target }} artifacts-pass: ${{ secrets.ARTIFACTS_PASS }} upload-artifacts: ${{ matrix.php == 'matomo5_min_php' && matrix.target == 'maximum_supported_matomo' }} UI: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v3 with: lfs: true persist-credentials: false - name: running tests uses: matomo-org/github-action-tests@main with: plugin-name: 'Bandwidth' matomo-test-branch: 'maximum_supported_matomo' test-type: 'UI' php-version: 'matomo5_min_php' node-version: '16' artifacts-pass: ${{ secrets.ARTIFACTS_PASS }} upload-artifacts: true12345678910111213141516171819202122232425262728293031323334353637383940414243name: PHPCS check
on: pull_request
permissions: actions: read checks: read contents: read deployments: none issues: read packages: none pull-requests: read repository-projects: none security-events: none statuses: read
jobs: phpcs: name: PHPCS runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 with: lfs: false persist-credentials: false - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: '7.4' tools: cs2pr - name: Install dependencies run: composer init --name=matomo/bandwidth --quiet; composer --no-plugins config allow-plugins.dealerdirect/phpcodesniffer-composer-installer true -n; composer config repositories.matomo-coding-standards vcs https://github.com/matomo-org/matomo-coding-standards -n; composer require matomo-org/matomo-coding-standards:dev-master; composer install --dev --prefer-dist --no-progress --no-suggest - name: Check PHP code styles id: phpcs run: ./vendor/bin/phpcs --report-full --standard=phpcs.xml --report-checkstyle=./phpcs-report.xml - name: Show PHPCS results in PR if: ${{ always() && steps.phpcs.outcome == 'failure' }} run: cs2pr ./phpcs-report.xml --prepend-filename12tests/UI/processed-ui-screenshotstests/UI/screenshot-diffs123456789101112131415161718192021222324252627282930313233343536<?xml version="1.0"?><ruleset name="bandwidth" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
<description>Matomo Coding Standard for Bandwidth plugin</description>
<arg name="extensions" value="php" />
<file>.</file>
<exclude-pattern>tests/javascript/*</exclude-pattern> <exclude-pattern>*/vendor/*</exclude-pattern>
<rule ref="Matomo"></rule>
<rule ref="Generic.Files.LineLength"> <properties> <property name="lineLimit" value="250" /> </properties> <exclude-pattern>tests/*</exclude-pattern> </rule>
<rule ref="Squiz.Classes.ValidClassName.NotCamelCaps"> <!-- Classnames for our update files don't match PascalCase, this can't be changed easily --> <exclude-pattern>Updates/*</exclude-pattern> </rule>
<rule ref="PSR1.Methods.CamelCapsMethodName.NotCamelCaps"> <!-- Allow using method name without camel caps in tests as long as some methods are named test_* --> <exclude-pattern>tests/*</exclude-pattern> </rule>
<rule ref="PSR1.Classes.ClassDeclaration.MultipleClasses"> <!-- Allow using multiple classes in one file for tests --> <exclude-pattern>tests/*</exclude-pattern> </rule></ruleset>123456789101112131415161718192021parameters: level: 1 phpVersion: 70200 tmpDir: /tmp/phpstan/Bandwidth/main paths: - . excludePaths: - tests/* - vendor/ - github-action-tests/ bootstrapFiles: - ../../bootstrap-phpstan.php universalObjectCratesClasses: - Piwik\Config - Piwik\View - Piwik\ViewDataTable\Config scanDirectories: # ../../ does not actually seem to give us anything # that ../plugins/ does not, but including it for # completeness. It does not seem to slow down performance. - ../../123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Plugins\Bandwidth\tests\Fixtures;
use Piwik\Date;use Piwik\Filesystem;use Piwik\Plugin;use Piwik\Tests\Framework\Fixture;
/** * Track actions with bandwidth */class OneVisitWithBandwidth extends Fixture{ public $dateTime = '2010-01-03 11:22:33'; public $idSite = 1;
/** * @var \MatomoTracker */ private $tracker;
public function setUp(): void { Plugin\Manager::getInstance()->loadPlugin('Bandwidth'); Plugin\Manager::getInstance()->installLoadedPlugins(); Filesystem::deleteAllCacheOnUpdate();
$this->setUpWebsiteAndUser(); $this->trackVisits(); }
private function setUpWebsiteAndUser() { // tests run in UTC, the Tracker in UTC if (!self::siteCreated($idSite = 1)) { self::createWebsite($this->dateTime); }
if (!self::siteCreated($idSite = 2)) { self::createWebsite($this->dateTime); }
self::createSuperUser(); }
public function trackVisits() { $this->tracker = self::getTracker($this->idSite, $this->dateTime, $useDefault = true, $uselocal = false); $this->tracker->setUrl('http://www.example.org/page');
$this->trackPageview('Test Title', 550); $this->trackPageview('Test 2', 200928); $this->trackPageview('Test Title');
$this->moveTimeForward(2); $this->trackDownload('/test/xyz.png', 23929); $this->trackDownload('/app.apk', 194948483939); $this->trackPageview('Test Title 4', 10); $this->trackPageview('Test Title'); $this->moveTimeForward(3); $this->trackPageview('Test 3', 52); $this->trackPageview('Test Title', 20); $this->trackPageview('Test 3', 13); $this->moveTimeForward(4); $this->trackPageview('Test Title 4', 6889); $this->trackDownload('/app.apk', 194948483939);
$this->trackPageview('No bandwidth');
$this->moveTimeForward(4.5); $this->trackPageview('Test Title', 95); $this->trackPageview('Index', 19493); $this->trackPageview('Index', 204948283939); $this->trackPageview('No bandwidth'); $this->trackPageview('Index', 455);
// we want to track pageviews for a different day in the same month year to verify it will still show // bandwidth columns on that day even there were no bytes tracked but there were some tracked in the same month $this->tracker = self::getTracker($this->idSite, '2010-01-05 23:23:23', $useDefault = true, $uselocal = false); $this->trackPageview('Test Title'); $this->trackPageview('Test Title'); $this->trackPageview('Test Title 2'); $this->trackPageview('Index');
// we want to track some more pageviews with no bytes to make sure columns are not shown here as there are no // tracked bytes for this month $this->tracker = self::getTracker($this->idSite, '2010-02-05 23:23:23', $useDefault = true, $uselocal = false); $this->trackPageview('Test Title'); $this->trackPageview('Test Title'); $this->trackPageview('Index'); $this->trackDownload('/test/xyz.png'); $this->trackDownload('/app.apk'); }
private function trackPageview($title, $bytes = null) { $this->setBandwidthTrackerParam($bytes); $url = str_replace(' ', '/', strtolower($title)); $this->tracker->setUrl('http://www.example.org/' . $url); self::checkResponse($this->tracker->doTrackPageView($title)); }
private function trackDownload($path, $bytes = null) { $this->setBandwidthTrackerParam($bytes); self::checkResponse($this->tracker->doTrackAction('http://www.example.org' . $path, 'download')); }
private function setBandwidthTrackerParam($bytes) { if ($bytes !== null) { $this->tracker->setDebugStringAppend('bw_bytes=' . $bytes); } else { $this->tracker->setDebugStringAppend(''); } }
private function moveTimeForward($minutes) { $hour = $minutes / 60; $this->tracker->setForceVisitDateTime(Date::factory($this->dateTime)->addHour($hour)->getDatetime()); }
public function tearDown(): void { }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Plugins\Bandwidth\tests\Framework\TestCase;
use Piwik\DataAccess\ArchiveTableCreator;use Piwik\Db;use Piwik\Plugin;use Piwik\Tests\Framework\Fixture;use Piwik\Tests\Framework\Mock\FakeAccess;
/** * @group Bandwidth */class IntegrationTestCase extends \Piwik\Tests\Framework\TestCase\IntegrationTestCase{ protected $date;
public function setUp(): void { parent::setUp(); $this->setSuperUser();
Fixture::createSuperUser(); Fixture::createWebsite('2014-01-01 00:00:00');
Plugin\Manager::getInstance()->loadPlugin('Bandwidth'); try { Plugin\Manager::getInstance()->activatePlugin('Bandwidth'); } catch (\Exception $e) { } }
public function tearDown(): void { // clean up your test here if needed $tables = ArchiveTableCreator::getTablesArchivesInstalled(); if (!empty($tables)) { Db::dropTables($tables); } parent::tearDown(); }
protected function setUser() { FakeAccess::$superUser = false; FakeAccess::$idSitesView = [1]; FakeAccess::$identity = 'aUser'; }
protected function setSuperUser() { FakeAccess::$superUser = true; }
protected function setAnonymousUser() { FakeAccess::clearAccess(); FakeAccess::$identity = 'anonymous'; }
protected function getTracker() { $tracker = Fixture::getTracker(1, $this->date . ' 00:01:01', true, true); $tracker->setTokenAuth(Fixture::getTokenAuth()); return $tracker; }
protected function trackPageviews($bytes) { $tracker = $this->getTracker();
foreach ($bytes as $byte) { $this->trackPageview($tracker, $byte); } }
protected function trackPageview($tracker, $byte, $url = null) { if (null !== $url) { $tracker->setUrl('http://www.example.org' . $url); }
if (null === $byte) { $tracker->setDebugStringAppend(''); } else { $tracker->setDebugStringAppend('bw_bytes=' . $byte); }
$title = $url ?: 'test';
$tracker->doTrackPageView($title); }
protected function trackDownloads($bytes) { $tracker = $this->getTracker();
foreach ($bytes as $byte) { if (null === $byte) { $tracker->setDebugStringAppend(''); } else { $tracker->setDebugStringAppend('bw_bytes=' . $byte); }
$tracker->doTrackAction('http://www.example.com/test', 'download'); } }
public function provideContainerConfig() { return [ 'Piwik\Access' => new FakeAccess(), ]; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Plugins\Bandwidth\tests\Integration;
use Piwik\DataTable;use Piwik\Plugins\Bandwidth\API;use Piwik\Plugins\Bandwidth\Metrics;use Piwik\Plugins\Bandwidth\tests\Framework\TestCase\IntegrationTestCase;
/** * @group Bandwidth * @group APITest * @group Plugins */class APITest extends IntegrationTestCase{ /** * @var API */ private $api;
protected $date = '2014-04-04'; private $idSite = 1;
public function setUp(): void { parent::setUp(); $this->api = API::getInstance(); $this->setSuperUser(); }
public function test_get_shouldReturnADataTable() { $this->trackPageviews([1]);
$result = $this->api->get($this->idSite, 'month', $this->date); $result->applyQueuedFilters();
$this->assertTrue($result instanceof DataTable); }
public function test_get_shouldReturnZero_IfNoTrackedBandwidth() { $result = $this->api->get($this->idSite, 'day', $this->date);
$this->assertTotalBandwidthValue(0, 0, 0, $result); }
public function test_get_shouldReturnTheSumOfAllOnlyPageviews() { $this->trackPageviews([1, 10, 20, 348]); $result = $this->api->get($this->idSite, 'day', $this->date);
$this->assertTotalBandwidthValue(379, 379, 0, $result); }
public function test_get_shouldReturnTheSumOfAllOnlyDownloads() { $this->trackDownloads([1, 10, 20, 348]); $result = $this->api->get($this->idSite, 'day', $this->date);
$this->assertTotalBandwidthValue(379, 0, 379, $result); }
public function test_get_shouldReturnTheSumOfAll_MixedPageviewsAndDownloads() { $this->trackPageviews([1, 10, 20, 49]); $this->trackDownloads([59, 4, 1, 34, 592]);
$result = $this->api->get($this->idSite, 'day', $this->date); $result->applyQueuedFilters();
$this->assertTotalBandwidthValue(770, 80, 690, $result); }
public function test_get_shouldReturnTheSumOfAll_DifferentPeriod() { $this->trackPageviews([1, 10, 20, 49]); $this->trackDownloads([59, 4, 1, 34, 592]);
$result = $this->api->get($this->idSite, 'month', $this->date); $result->applyQueuedFilters();
$this->assertTotalBandwidthValue(770, 80, 690, $result); }
public function test_get_shouldReturnFalse_IfColumnShallNotBeDisplayed() { $this->trackPageviews([1, 10, 20, 49]); $this->trackDownloads([59, 4, 1, 34]);
$result = $this->api->get($this->idSite, 'day', $this->date, false, 'nb_visits'); $result->applyQueuedFilters();
$this->assertTotalBandwidthValue(false, false, false, $result); }
public function test_get_shouldReturnSomeColumns_IfValidOnesRequested() { $this->trackPageviews([1, 10, 20, 49]); $this->trackDownloads([59, 4, 1, 34]);
$displayColumns = Metrics::COLUMN_TOTAL_DOWNLOAD_BANDWIDTH . ',' . Metrics::COLUMN_TOTAL_PAGEVIEW_BANDWIDTH; $result = $this->api->get($this->idSite, 'day', $this->date, false, $displayColumns); $result->applyQueuedFilters();
$this->assertTotalBandwidthValue(false, 80, 98, $result); }
public function test_get_shouldFailIfUserHasNoPermission() { $this->expectException(\Exception::class); $this->expectExceptionMessage('checkUserHasViewAccess');
$this->setAnonymousUser(); $this->api->get($this->idSite, 'day', $this->date); }
private function assertTotalBandwidthValue($expectedOverall, $expectedPageview, $expectedDownload, DataTable $dataTable) { $row = $dataTable->getFirstRow(); $this->assertSame($expectedOverall, $row->getColumn(Metrics::COLUMN_TOTAL_OVERALL_BANDWIDTH)); $this->assertSame($expectedPageview, $row->getColumn(Metrics::COLUMN_TOTAL_PAGEVIEW_BANDWIDTH)); $this->assertSame($expectedDownload, $row->getColumn(Metrics::COLUMN_TOTAL_DOWNLOAD_BANDWIDTH)); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Plugins\Bandwidth\tests\Integration;
use Piwik\API\Request;use Piwik\DataTable;use Piwik\Plugins\Bandwidth\API;use Piwik\Plugins\Bandwidth\tests\Framework\TestCase\IntegrationTestCase;use Piwik\Version;
/** * Bandidth Class and Bandwidth Tracker test * * @group Bandwidth * @group BandwidthTest * @group Plugins */class BandwidthTest extends IntegrationTestCase{ /** * @var API */ private $api;
protected $date = '2014-04-04';
public function setUp(): void { parent::setUp(); $this->api = API::getInstance();
$this->setSuperUser(); }
public function test_shouldEnrichPageUrls() { $this->trackPageviews([1, 10, null, 5, null, 3949, 399]);
$result = $this->requestAction('getPageUrls');
$row = $result->getFirstRow(); $this->assertBandwidthStats($row, $maxB = 3949, $minB = 1, $sumB = 4364, $avgB = 872); }
public function test_shouldEnrichPageUrls_ZeroShouldCountToAverageCount() { $this->trackPageviews([1, 10, 5, 0, null, 3949, 0, null, 399]); $result = $this->requestAction('getPageUrls');
$row = $result->getFirstRow(); $this->assertSame($row->getColumn('avg_bandwidth'), 623); }
public function test_shouldEnrichPageUrls_ShouldNotFailIfNoPageHasBandwidth() { $this->trackPageviews([null, null, null, null]); $result = $this->requestAction('getPageUrls');
$row = $result->getFirstRow(); $this->assertBandwidthStats($row, $maxB = false, $minB = false, $sumB = 0, $avgB = 0); }
public function test_shouldEnrichPageUrls_ShouldDefineASegment() { $this->trackPageviews([1, 10, 5, 0, null, 3949, 0, null, 399]); $result = $this->requestAction('getPageUrls', ['segment' => 'bandwidth>=34']);
$row = $result->getFirstRow();
$this->assertBandwidthStats($row, $maxB = 3949, $minB = 0, $sumB = 4364, $avgB = 623); }
public function test_shouldEnrichPageTitlesAndFormat_IfRequested() { $this->trackPageviews([1, 10, null, 5, null, 3949, 399]);
$result = $this->requestAction('getPageTitles', ['format_metrics' => '1']);
$row = $result->getFirstRow(); $this->assertBandwidthStats($row, $maxB = '3.86 K', $minB = '1 B', $sumB = '4.26 K', $avgB = '872 B'); }
public function test_shouldEnrichPageTitles() { $this->trackPageviews([1, 10, null, 5, null, 3949, 399]);
$result = $this->requestAction('getPageTitles');
$row = $result->getFirstRow(); $this->assertBandwidthStats($row, $maxB = 3949, $minB = 1, $sumB = 4364, $avgB = 872); }
public function test_shouldEnrichDownloads() { $this->trackDownloads([1, 10, null, 5, null, 3949, 397]);
$result = $this->requestAction('getDownloads');
$row = $result->getFirstRow(); $this->assertBandwidthStats($row, $maxB = 3949, $minB = 1, $sumB = 4362, $avgB = 872); }
public function test_shouldEnrichLiveActions() { $this->trackPageviews([1, 10, null, 5, null, 3949, 399]);
$params = [ 'idSite' => 1, 'period' => 'day', 'date' => $this->date, ];
$result = Request::processRequest('Live.getLastVisitsDetails', $params); $row = $result->getFirstRow();
$actions = $row->getColumn('actionDetails'); foreach ($actions as $action) { $this->assertArrayHasKey('bandwidth', $action); } }
public function test_manyDifferentUrlsWithFolders_ShouldAggregateStats() { $tracker = $this->getTracker(); $this->trackPageview($tracker, 10, '/index'); $this->trackPageview($tracker, 20, '/blog/2014/test'); $this->trackPageview($tracker, 15, '/blog/2014/test2'); $this->trackPageview($tracker, 3, '/team/contact'); $this->trackPageview($tracker, null, '/index'); $this->trackPageview($tracker, 10, '/index');
$result = $this->requestAction('getPageUrls'); $this->assertSame(3, $result->getRowsCount());
$row = $result->getRowFromLabel('/index'); $this->assertBandwidthStats($row, $maxB = 10, $minB = 10, $sumB = 20, $avgB = 10); $row = $result->getRowFromLabel('team'); $this->assertBandwidthStats($row, $maxB = 3, $minB = 3, $sumB = 3, $avgB = 3); $row = $result->getRowFromLabel('blog'); $this->assertBandwidthStats($row, $maxB = 20, $minB = 15, $sumB = 35, $avgB = 17);
// request subtable /blog $result = $this->requestAction('getPageUrls', ['idSubtable' => $row->getIdSubDataTable()]); $row = $result->getRowFromLabel('2014'); $this->assertBandwidthStats($row, $maxB = 20, $minB = 15, $sumB = 35, $avgB = 17);
// request subtable /blog/2014 $result = $this->requestAction('getPageUrls', ['idSubtable' => $row->getIdSubDataTable()]); $row = $result->getRowFromLabel('/test'); $this->assertBandwidthStats($row, $maxB = 20, $minB = 20, $sumB = 20, $avgB = 20); }
private function assertBandwidthStats(DataTable\Row $row, $maxB, $minB, $sumB, $avgB) { if (version_compare(Version::VERSION, '5.2.0-alpha', '>=')) { // calculation of min/max metrics was broken before Matomo 5.2, so results would be incorrect $this->assertSame($row->getColumn('max_bandwidth'), $maxB); $this->assertSame($row->getColumn('min_bandwidth'), $minB); } $this->assertSame($row->getColumn('sum_bandwidth'), $sumB); $this->assertSame($row->getColumn('avg_bandwidth'), $avgB); }
/** * @param string $action * @param array $additionalParams * @return DataTable */ private function requestAction($action, $additionalParams = []) { $params = [ 'idSite' => 1, 'period' => 'day', 'date' => $this->date, ];
if (!empty($additionalParams)) { $params = array_merge($params, $additionalParams); }
return Request::processRequest('Actions.' . $action, $params); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748<?php
/** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Plugins\Bandwidth\tests\System;
use Piwik\Plugins\TestRunner\Commands\CheckDirectDependencyUse;use Piwik\Tests\Framework\TestCase\SystemTestCase;use Piwik\Version;use Symfony\Component\Console\Input\ArrayInput;use Symfony\Component\Console\Output\NullOutput;
class CheckDirectDependencyUseCommandTest extends SystemTestCase{ public function testCommand() { if (version_compare(Version::VERSION, '5.0.3', '<=') && !file_exists(PIWIK_INCLUDE_PATH . '/plugins/TestRunner/Commands/CheckDirectDependencyUse.php')) { $this->markTestSkipped('tests:check-direct-dependency-use is not available in this version'); }
$pluginName = 'Bandwidth';
$checkDirectDependencyUse = new CheckDirectDependencyUse();
$console = new \Piwik\Console(self::$fixture->piwikEnvironment); $console->addCommands([$checkDirectDependencyUse]); $command = $console->find('tests:check-direct-dependency-use'); $arguments = [ 'command' => 'tests:check-direct-dependency-use', '--plugin' => $pluginName, '--grep-vendor', ];
$inputObject = new ArrayInput($arguments); $command->run($inputObject, new NullOutput());
$this->assertEquals([ 'Symfony\Component\Console' => [ 'Bandwidth/tests/System/CheckDirectDependencyUseCommandTest.php' ], ], $checkDirectDependencyUse->usesFoundList[$pluginName]); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687/*! * Matomo - free/libre analytics platform * * Screenshot integration tests. * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
describe("Bandwidth", function () { this.timeout(0);
this.fixture = "Piwik\\Plugins\\Bandwidth\\tests\\Fixtures\\OneVisitWithBandwidth";
var generalParams = 'idSite=1&period=day&date=2010-01-03', secondDateParams = 'idSite=1&period=day&date=2010-01-05', thirdDateParams = 'idSite=1&period=day&date=2010-02-05', urlBase = 'module=CoreHome&action=index&' + generalParams;
before(function () { testEnvironment.pluginsToLoad = ['Bandwidth']; testEnvironment.save();
});
it('should load the actions > pages page correctly', async function () { await page.goto("?" + urlBase + "#?" + generalParams + "&category=General_Actions&subcategory=General_Pages&flat=0"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('actions_page_urls'); });
it('should load the actions > pages page flat correctly', async function () { await page.goto('about:blank'); await page.goto("?" + urlBase + "#?" + generalParams + "&category=General_Actions&subcategory=General_Pages&flat=1"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('actions_page_urls_flat'); });
it('should load the actions > pages titles correctly', async function () { await page.goto("?" + urlBase + "#?" + generalParams + "&category=General_Actions&subcategory=Actions_SubmenuPageTitles"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('actions_page_titles'); });
it('should load the actions > downloads correctly', async function () { await page.goto("?" + urlBase + "#?" + generalParams + "&category=General_Actions&subcategory=General_Downloads"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('actions_downloads'); });
it('should load the actions > downloads flat correctly', async function () { await page.goto('about:blank'); await page.goto("?" + urlBase + "#?" + generalParams + "&category=General_Actions&subcategory=General_Downloads&flat=1"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('actions_downloads_flat'); });
it('should load the visitors > overview correctly', async function () { await page.goto("?" + urlBase + "#?" + generalParams + "&category=General_Visitors&subcategory=General_Overview&columns=nb_total_overall_bandwidth,nb_total_pageview_bandwidth,nb_total_download_bandwidth"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('visitors_overview'); });
it('should show bandwidth columns if no byte was tracked on that day but during the month', async function () { await page.goto("?" + urlBase + "#?" + secondDateParams + "&category=General_Actions&subcategory=General_Pages&flat=1"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('actions_no_bandwidth_on_day_but_in_month'); });
it('should not show bandwidth columns if no byte was tracked in actions > pages page', async function () { await page.goto("?" + urlBase + "#?" + thirdDateParams + "&category=General_Actions&subcategory=General_Pages&flat=1"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('actions_page_urls_no_bandwidth'); });
it('should not show bandwidth columns if no byte was tracked in actions > pages titles', async function () { await page.goto("?" + urlBase + "#?" + thirdDateParams + "&category=General_Actions&subcategory=Actions_SubmenuPageTitles"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('actions_page_titles_no_bandwidth'); });
it('should not show bandwidth columns if no byte was tracked in actions > downloads', async function () { await page.goto("?" + urlBase + "#?" + thirdDateParams + "&category=General_Actions&subcategory=General_Downloads"); var elem = await page.jQuery('.pageWrap'); expect(await elem.screenshot()).to.matchImage('actions_downloads_no_bandwidth'); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Plugins\Bandwidth\tests\Unit;
use Piwik\Plugins\Bandwidth\Bandwidth;use Piwik\Tests\Framework\TestCase\UnitTestCase;
/** * @group Bandwidth * @group BandwidthTest * @group Plugins */class BandwidthTest extends UnitTestCase{ /** * @var Bandwidth */ private $bandwidth;
public function setUp(): void { parent::setUp(); $this->bandwidth = new Bandwidth(); }
public function test_addMetricTranslations_shouldAddToExistTranslations() { $translations = [ 'my' => 'test', ];
$this->bandwidth->addMetricTranslations($translations);
$this->assertGreaterThanOrEqual(9, count($translations)); $this->assertSame('test', $translations['my']); // make sure this one is not overwritten }
public function test_addActionMetrics_shouldAddToExistingMetrics() { $metric = ['aggregation' => 'sum', 'query' => 'count(*)']; $metrics = [ 3 => $metric, ];
$this->bandwidth->addActionMetrics($metrics);
// should have added metrics $this->assertGreaterThanOrEqual(5, count($metrics));
// should still have original metric $this->assertSame($metric, $metrics[3]);
// make sure each is properly configured foreach ($metrics as $metric) { $this->assertNotEmpty($metric['aggregation']); $this->assertNotEmpty($metric['query']); } }}1234567891011121314151617181920212223242526272829303132333435363738<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
namespace Piwik\Plugins\Bandwidth\tests\Unit;
use Piwik\Plugins\Bandwidth\Metrics;use Piwik\Tests\Framework\TestCase\UnitTestCase;
/** * @group Bandwidth * @group MetricsTest * @group Plugins */class MetricsTest extends UnitTestCase{ public function test_getMetricTranslations() { $translations = Metrics::getMetricTranslations(); $expected = [ 'nb_hits_with_bandwidth' => 'Bandwidth_ColumnHitsWithBandwidth', 'max_bandwidth' => 'Bandwidth_ColumnMaxBandwidth', 'min_bandwidth' => 'Bandwidth_ColumnMinBandwidth', 'sum_bandwidth' => 'Bandwidth_ColumnSumBandwidth', 'avg_bandwidth' => 'Bandwidth_ColumnAvgBandwidth', 'nb_total_overall_bandwidth' => 'Bandwidth_ColumnTotalOverallBandwidth', 'nb_total_pageview_bandwidth' => 'Bandwidth_ColumnTotalPageviewBandwidth', 'nb_total_download_bandwidth' => 'Bandwidth_ColumnTotalDownloadBandwidth', ];
$this->assertEquals($expected, $translations); }}.gitattributes+1
plugins/ArchivingMetrics/tests/Integration/TasksTest.phpAdded+92
plugins/ArchivingMetrics/tests/Integration/TimerDbTest.phpAdded+57
plugins/ArchivingMetrics/tests/Unit/TimerTest.phpAdded+616
plugins/Bandwidth/.gitattributesAdded+6
plugins/Bandwidth/.github/workflows/matomo-ai-checklist.ymlAdded+32
plugins/Bandwidth/.github/workflows/matomo-tests.ymlAdded+74
plugins/Bandwidth/.github/workflows/phpcs.ymlAdded+43
plugins/Bandwidth/.gitignoreAdded+2
plugins/Bandwidth/phpcs.xmlAdded+36
plugins/Bandwidth/phpstan.neonAdded+21
plugins/Bandwidth/screenshots/Downloads.pngAdded

plugins/Bandwidth/screenshots/Pageviews.pngAdded

plugins/Bandwidth/screenshots/Visitor_Overview.pngAdded

plugins/Bandwidth/tests/Fixtures/OneVisitWithBandwidth.phpAdded+136
plugins/Bandwidth/tests/Framework/TestCase/IntegrationTestCase.phpAdded+122
plugins/Bandwidth/tests/Integration/APITest.phpAdded+133
plugins/Bandwidth/tests/Integration/BandwidthTest.phpAdded+190
plugins/Bandwidth/tests/System/CheckDirectDependencyUseCommandTest.phpAdded+48
plugins/Bandwidth/tests/UI/Bandwidth_spec.jsAdded+87
plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_downloads.pngAdded

plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_downloads_flat.pngAdded

plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_downloads_no_bandwidth.pngAdded

plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_no_bandwidth_on_day_but_in_month.pngAdded

plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_titles.pngAdded

plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_titles_no_bandwidth.pngAdded

plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_urls.pngAdded

plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_urls_flat.pngAdded

plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_actions_page_urls_no_bandwidth.pngAdded

plugins/Bandwidth/tests/UI/expected-ui-screenshots/Bandwidth_visitors_overview.pngAdded

plugins/Bandwidth/tests/Unit/BandwidthTest.phpAdded+66
plugins/Bandwidth/tests/Unit/MetricsTest.phpAdded+38