3 use Liuggio\StatsdClient\Entity\StatsdData
;
4 use Liuggio\StatsdClient\Sender\SenderInterface
;
7 * @covers SamplingStatsdClient
9 class SamplingStatsdClientTest
extends PHPUnit\Framework\TestCase
{
11 use MediaWikiCoversValidator
;
14 * @dataProvider samplingDataProvider
16 public function testSampling( $data, $sampleRate, $seed, $expectWrite ) {
17 $sender = $this->getMockBuilder( SenderInterface
::class )->getMock();
18 $sender->expects( $this->any() )->method( 'open' )->will( $this->returnValue( true ) );
20 $sender->expects( $this->once() )->method( 'write' )
21 ->with( $this->anything(), $this->equalTo( $data ) );
23 $sender->expects( $this->never() )->method( 'write' );
25 if ( defined( 'MT_RAND_PHP' ) ) {
26 mt_srand( $seed, MT_RAND_PHP
);
30 $client = new SamplingStatsdClient( $sender );
31 $client->send( $data, $sampleRate );
34 public function samplingDataProvider() {
35 $unsampled = new StatsdData();
36 $unsampled->setKey( 'foo' );
37 $unsampled->setValue( 1 );
39 $sampled = new StatsdData();
40 $sampled->setKey( 'foo' );
41 $sampled->setValue( 1 );
42 $sampled->setSampleRate( '0.1' );
45 // $data, $sampleRate, $seed, $expectWrite
46 [ $unsampled, 1, 0 /*0.44*/, true ],
47 [ $sampled, 1, 0 /*0.44*/, false ],
48 [ $sampled, 1, 4 /*0.03*/, true ],
49 [ $unsampled, 0.1, 0 /*0.44*/, false ],
50 [ $sampled, 0.5, 0 /*0.44*/, false ],
51 [ $sampled, 0.5, 4 /*0.03*/, false ],
55 public function testSetSamplingRates() {
56 $matching = new StatsdData();
57 $matching->setKey( 'foo.bar' );
58 $matching->setValue( 1 );
60 $nonMatching = new StatsdData();
61 $nonMatching->setKey( 'oof.bar' );
62 $nonMatching->setValue( 1 );
64 $sender = $this->getMockBuilder( SenderInterface
::class )->getMock();
65 $sender->expects( $this->any() )->method( 'open' )->will( $this->returnValue( true ) );
66 $sender->expects( $this->once() )->method( 'write' )->with( $this->anything(),
67 $this->equalTo( $nonMatching ) );
69 $client = new SamplingStatsdClient( $sender );
70 $client->setSamplingRates( [ 'foo.*' => 0.2 ] );
72 mt_srand( 0 ); // next random is 0.44
73 $client->send( $matching );
75 $client->send( $nonMatching );