Merge "maintenance: Document secondary purpose of --server"
[lhc/web/wiklou.git] / tests / phpunit / includes / libs / SamplingStatsdClientTest.php
1 <?php
2
3 use Liuggio\StatsdClient\Entity\StatsdData;
4 use Liuggio\StatsdClient\Sender\SenderInterface;
5
6 /**
7 * @covers SamplingStatsdClient
8 */
9 class SamplingStatsdClientTest extends PHPUnit\Framework\TestCase {
10
11 use MediaWikiCoversValidator;
12
13 /**
14 * @dataProvider samplingDataProvider
15 */
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 ) );
19 if ( $expectWrite ) {
20 $sender->expects( $this->once() )->method( 'write' )
21 ->with( $this->anything(), $this->equalTo( $data ) );
22 } else {
23 $sender->expects( $this->never() )->method( 'write' );
24 }
25 if ( defined( 'MT_RAND_PHP' ) ) {
26 mt_srand( $seed, MT_RAND_PHP );
27 } else {
28 mt_srand( $seed );
29 }
30 $client = new SamplingStatsdClient( $sender );
31 $client->send( $data, $sampleRate );
32 }
33
34 public function samplingDataProvider() {
35 $unsampled = new StatsdData();
36 $unsampled->setKey( 'foo' );
37 $unsampled->setValue( 1 );
38
39 $sampled = new StatsdData();
40 $sampled->setKey( 'foo' );
41 $sampled->setValue( 1 );
42 $sampled->setSampleRate( '0.1' );
43
44 return [
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 ],
52 ];
53 }
54
55 public function testSetSamplingRates() {
56 $matching = new StatsdData();
57 $matching->setKey( 'foo.bar' );
58 $matching->setValue( 1 );
59
60 $nonMatching = new StatsdData();
61 $nonMatching->setKey( 'oof.bar' );
62 $nonMatching->setValue( 1 );
63
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 ) );
68
69 $client = new SamplingStatsdClient( $sender );
70 $client->setSamplingRates( [ 'foo.*' => 0.2 ] );
71
72 mt_srand( 0 ); // next random is 0.44
73 $client->send( $matching );
74 mt_srand( 0 );
75 $client->send( $nonMatching );
76 }
77 }