| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\Tests; |
| 4 |
|
| 5 |
use Liuggio\StatsdClient\Entity\StatsdData; |
| 6 |
use Liuggio\StatsdClient\Sender\SenderInterface; |
| 7 |
use MediaWikiCoversValidator; |
| 8 |
use PHPUnit\Framework\TestCase; |
| 9 |
use Wikimedia\Stats\SamplingStatsdClient; |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
class SamplingStatsdClientTest extends TestCase { |
| 15 |
|
| 16 |
use MediaWikiCoversValidator; |
| 17 |
|
| 18 |
protected function setUp(): void { |
| 19 |
parent::setUp(); |
| 20 |
if ( version_compare( PHP_VERSION, '8.2', '>=' ) ) { |
| 21 |
|
| 22 |
$this->markTestSkipped( "PHP 8.2 isn't supported for this test" ); |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
public function testSampling( $data, $sampleRate, $seed, $expectWrite ) { |
| 30 |
$sender = $this->createMock( SenderInterface::class ); |
| 31 |
$sender->method( 'open' )->willReturn( true ); |
| 32 |
if ( $expectWrite ) { |
| 33 |
$sender->expects( $this->once() )->method( 'write' ) |
| 34 |
->with( $this->anything(), $data ); |
| 35 |
} else { |
| 36 |
$sender->expects( $this->never() )->method( 'write' ); |
| 37 |
} |
| 38 |
|
| 39 |
mt_srand( $seed ); |
| 40 |
|
| 41 |
$client = new SamplingStatsdClient( $sender ); |
| 42 |
$client->send( $data, $sampleRate ); |
| 43 |
} |
| 44 |
|
| 45 |
public function samplingDataProvider() { |
| 46 |
$unsampled = new StatsdData(); |
| 47 |
$unsampled->setKey( 'foo' ); |
| 48 |
$unsampled->setValue( 1 ); |
| 49 |
|
| 50 |
$sampled = new StatsdData(); |
| 51 |
$sampled->setKey( 'foo' ); |
| 52 |
$sampled->setValue( 1 ); |
| 53 |
$sampled->setSampleRate( '0.1' ); |
| 54 |
|
| 55 |
return [ |
| 56 |
|
| 57 |
[ $unsampled, 1, 0 , true ], |
| 58 |
[ $sampled, 1, 0 , false ], |
| 59 |
[ $sampled, 1, 7 , true ], |
| 60 |
[ $unsampled, 0.1, 0 , false ], |
| 61 |
[ $sampled, 0.5, 0 , false ], |
| 62 |
[ $sampled, 0.5, 7 , false ], |
| 63 |
]; |
| 64 |
} |
| 65 |
|
| 66 |
public function testSetSamplingRates() { |
| 67 |
$matching = new StatsdData(); |
| 68 |
$matching->setKey( 'foo.bar' ); |
| 69 |
$matching->setValue( 1 ); |
| 70 |
|
| 71 |
$nonMatching = new StatsdData(); |
| 72 |
$nonMatching->setKey( 'oof.bar' ); |
| 73 |
$nonMatching->setValue( 1 ); |
| 74 |
|
| 75 |
$sender = $this->createMock( SenderInterface::class ); |
| 76 |
$sender->method( 'open' )->willReturn( true ); |
| 77 |
$sender->expects( $this->once() )->method( 'write' ) |
| 78 |
->with( $this->anything(), $nonMatching ); |
| 79 |
|
| 80 |
$client = new SamplingStatsdClient( $sender ); |
| 81 |
$client->setSamplingRates( [ 'foo.*' => 0.2 ] ); |
| 82 |
|
| 83 |
mt_srand( 0 ); |
| 84 |
$client->send( $matching ); |
| 85 |
mt_srand( 0 ); |
| 86 |
$client->send( $nonMatching ); |
| 87 |
} |
| 88 |
} |