Debian Codegraph @

tests/phpunit/unit/includes/libs/Stats/MetricTest.php

raw symbols SCIP
1 <?php
2
3 namespace Wikimedia\Tests\Stats;
4
5 use PHPUnit\Framework\TestCase;
6 use Psr\Log\NullLogger;
7 use Wikimedia\Stats\IBufferingStatsdDataFactory;
8 use Wikimedia\Stats\Metrics\BaseMetric;
9 use Wikimedia\Stats\Metrics\CounterMetric;
10 use Wikimedia\Stats\Metrics\NullMetric;
11 use Wikimedia\Stats\OutputFormats;
12 use Wikimedia\Stats\StatsCache;
13 use Wikimedia\Stats\StatsFactory;
14 use Wikimedia\TestingAccessWrapper;
15
16 /**
17 * @covers \Wikimedia\Stats\Metrics\NullMetric
18 * @covers \Wikimedia\Stats\Metrics\CounterMetric
19 * @covers \Wikimedia\Stats\Metrics\GaugeMetric
20 * @covers \Wikimedia\Stats\Metrics\TimingMetric
21 * @covers \Wikimedia\Stats\StatsUtils
22 */
23 class MetricTest extends TestCase {
24
25 public const FORMATS = [ 'statsd', 'dogstatsd' ];
26
27 public const TYPES = [ 'counter', 'gauge', 'timing' ];
28
29 public const TESTS = [
30 'basic' => [
31 'config' => [
32 'name' => 'test.unit',
33 'component' => 'testComponent',
34 ],
35 'value' => 2,
36 'labels' => [],
37 ],
38 'invalidLabel' => [
39 'config' => [
40 'name' => 'test.unit',
41 'component' => 'testComponent',
42 ],
43 'value' => 2,
44 'labels' => [ ': x' => 'labelOne' ],
45 ],
46 'oneLabel' => [
47 'config' => [
48 'name' => 'test.unit',
49 'component' => 'testComponent',
50 ],
51 'value' => 2,
52 'labels' => [ 'x' => 'labelOne' ],
53 ],
54 'multiLabel' => [
55 'config' => [
56 'name' => 'test.unit',
57 'component' => 'testComponent',
58 ],
59 'value' => 2,
60 'labels' => [ 'x' => 'labelOne', 'y' => 'labelTwo' ],
61 ],
62 'noComponent' => [
63 'config' => [
64 'name' => 'test.unit',
65 'component' => null,
66 ],
67 'value' => 2,
68 'labels' => [],
69 ]
70 ];
71
72 public const RESULTS = [
73 'statsd.counter.basic' => [ 'mediawiki.testComponent.test_unit:2|c' ],
74 'statsd.counter.invalidLabel' => [ 'mediawiki.testComponent.test_unit.labelOne:2|c' ],
75 'statsd.counter.oneLabel' => [ 'mediawiki.testComponent.test_unit.labelOne:2|c' ],
76 'statsd.counter.multiLabel' => [ 'mediawiki.testComponent.test_unit.labelOne.labelTwo:2|c' ],
77 'statsd.counter.noComponent' => [ 'mediawiki.test_unit:2|c' ],
78 'statsd.gauge.basic' => [ 'mediawiki.testComponent.test_unit:2|g' ],
79 'statsd.gauge.invalidLabel' => [ 'mediawiki.testComponent.test_unit.labelOne:2|g' ],
80 'statsd.gauge.oneLabel' => [ 'mediawiki.testComponent.test_unit.labelOne:2|g' ],
81 'statsd.gauge.multiLabel' => [ 'mediawiki.testComponent.test_unit.labelOne.labelTwo:2|g' ],
82 'statsd.gauge.noComponent' => [ 'mediawiki.test_unit:2|g' ],
83 'statsd.timing.basic' => [ 'mediawiki.testComponent.test_unit:2|ms' ],
84 'statsd.timing.invalidLabel' => [ 'mediawiki.testComponent.test_unit.labelOne:2|ms' ],
85 'statsd.timing.oneLabel' => [ 'mediawiki.testComponent.test_unit.labelOne:2|ms' ],
86 'statsd.timing.multiLabel' => [ 'mediawiki.testComponent.test_unit.labelOne.labelTwo:2|ms' ],
87 'statsd.timing.noComponent' => [ 'mediawiki.test_unit:2|ms' ],
88
89 'dogstatsd.counter.basic' => [ 'mediawiki.testComponent.test_unit:2|c' ],
90 'dogstatsd.counter.invalidLabel' => [ 'mediawiki.testComponent.test_unit:2|c|#x:labelOne' ],
91 'dogstatsd.counter.oneLabel' => [ 'mediawiki.testComponent.test_unit:2|c|#x:labelOne' ],
92 'dogstatsd.counter.multiLabel' => [
93 'mediawiki.testComponent.test_unit:2|c|#x:labelOne,y:labelTwo' ],
94 'dogstatsd.counter.noComponent' => [ 'mediawiki.test_unit:2|c' ],
95 'dogstatsd.gauge.basic' => [ 'mediawiki.testComponent.test_unit:2|g' ],
96 'dogstatsd.gauge.invalidLabel' => [ 'mediawiki.testComponent.test_unit:2|g|#x:labelOne' ],
97 'dogstatsd.gauge.oneLabel' => [ 'mediawiki.testComponent.test_unit:2|g|#x:labelOne' ],
98 'dogstatsd.gauge.multiLabel' => [
99 'mediawiki.testComponent.test_unit:2|g|#x:labelOne,y:labelTwo' ],
100 'dogstatsd.gauge.noComponent' => [ 'mediawiki.test_unit:2|g' ],
101 'dogstatsd.timing.basic' => [ 'mediawiki.testComponent.test_unit:2|ms' ],
102 'dogstatsd.timing.invalidLabel' => [ 'mediawiki.testComponent.test_unit:2|ms|#x:labelOne' ],
103 'dogstatsd.timing.oneLabel' => [ 'mediawiki.testComponent.test_unit:2|ms|#x:labelOne' ],
104 'dogstatsd.timing.multiLabel' => [
105 'mediawiki.testComponent.test_unit:2|ms|#x:labelOne,y:labelTwo' ],
106 'dogstatsd.timing.noComponent' => [ 'mediawiki.test_unit:2|ms' ],
107 ];
108
109 /** @var StatsCache */
110 private $cache;
111
112 public function handleTest( $test, $type, $format ) {
113 $config = self::TESTS[$test];
114 $name = implode( '.', [ $format, $type, $test ] );
115 $this->setName( $name );
116 $this->cache->clear();
117 $formatter = OutputFormats::getNewFormatter( OutputFormats::getFormatFromString( $format ) );
118 $emitter = OutputFormats::getNewEmitter( 'mediawiki', $this->cache, $formatter );
119 $statsFactory = new StatsFactory( $this->cache, $emitter, new NullLogger );
120 if ( $config['config']['component'] !== null ) {
121 $statsFactory = $statsFactory->withComponent( $config['config']['component'] );
122 }
123 switch ( $type ) {
124 case 'counter':
125 $metric = $statsFactory->getCounter( $config['config']['name'] );
126 $metric->setLabels( $config['labels'] );
127 $metric->incrementBy( $config['value'] );
128 break;
129 case 'gauge':
130 $metric = $statsFactory->getGauge( $config['config']['name'] );
131 $metric->setLabels( $config['labels'] );
132 $metric->set( $config['value'] );
133 break;
134 case 'timing':
135 $metric = $statsFactory->getTiming( $config['config']['name'] );
136 $metric->setLabels( $config['labels'] );
137 $metric->observe( $config['value'] );
138 break;
139 case 'default':
140 break;
141 }
142 $this->assertEquals( self::RESULTS[$name], TestingAccessWrapper::newFromObject( $emitter )->render() );
143 }
144
145 public function handleType( $type, $format ) {
146 foreach ( self::TESTS as $test => $_ ) {
147 $this->handleTest( $test, $type, $format );
148 }
149 }
150
151 public function handleFormat( $format ) {
152 $this->cache = new StatsCache();
153 foreach ( self::TYPES as $type ) {
154 $this->handleType( $type, $format );
155 }
156 }
157
158 public function testMetrics() {
159 foreach ( self::FORMATS as $format ) {
160 $this->handleFormat( $format );
161 }
162 }
163
164 public function testSampledMetrics() {
165 $rounds = 10;
166 $m = StatsFactory::newNull();
167 $ten_percent_metrics = $m->getCounter( 'test.sampled.ten' )->setSampleRate( 0.1 );
168 $m = StatsFactory::newNull();
169 $all_metrics = $m->getCounter( 'test.sampled.hundred' )->setSampleRate( 1.0 );
170 $m = StatsFactory::newNull();
171 $zero_metrics = $m->getCounter( 'test.sampled.zero' )->setSampleRate( 0.0 );
172 for ( $i = 0; $i < $rounds; $i++ ) {
173 $ten_percent_metrics->increment();
174 $all_metrics->increment();
175 $zero_metrics->increment();
176 }
177 $this->assertLessThan( $rounds, count( $ten_percent_metrics->getSamples() ) ); // random
178 $this->assertCount( $rounds, $all_metrics->getSamples() );
179 $this->assertCount( 0, $zero_metrics->getSamples() );
180
181 # getSampleCount() should count all samples regardless of sample rate
182 $this->assertEquals( 10, $ten_percent_metrics->getSampleCount() );
183 $this->assertEquals( 10, $all_metrics->getSampleCount() );
184 $this->assertEquals( 10, $zero_metrics->getSampleCount() );
185 }
186
187 public function testTimerNotStarted() {
188 $m = StatsFactory::newNull();
189 $this->expectPHPWarning(
190 'Stats: stop() called before start() for metric \'test\'',
191 static function () use ( $m ) {
192 $m->getTiming( 'test' )->stop();
193 }
194 );
195 }
196
197 public function testChangingLabelsToUsedMetric() {
198 $m = StatsFactory::newNull();
199 $m->getCounter( 'testMetricCounter' )->setLabel( 'labelOne', 'a' )->increment();
200 $counter = @$m->getCounter( 'testMetricCounter' )->setLabel( 'labelTwo', 'b' );
201 $this->assertInstanceOf( NullMetric::class, $counter );
202 $m->getGauge( 'testMetricGauge' )->setLabel( 'labelOne', 'a' )->set( 1 );
203 $gauge = @$m->getGauge( 'testMetricGauge' )->setLabel( 'labelTwo', 'b' );
204 $this->assertInstanceOf( NullMetric::class, $gauge );
205 $m->getTiming( 'testMetricTiming' )->setLabel( 'labelOne', 'a' )->observe( 1 );
206 $timer = @$m->getTiming( 'testMetricTiming' )->setLabel( 'labelTwo', 'b' );
207 $this->assertInstanceOf( NullMetric::class, $timer );
208 }
209
210 public function testCounterHandleNotAllLabelsHaveValues() {
211 $m = StatsFactory::newNull();
212 $m->getCounter( 'testMetricCounter' )->setLabel( 'labelOne', 'a' )->increment();
213 $this->expectPHPWarning(
214 'Stats: Cannot associate label keys with label values: Not all initialized labels have an assigned value.',
215 static function () use ( $m ) {
216 $m->getCounter( 'testMetricCounter' )->increment();
217 }
218 );
219 }
220
221 public function testGaugeHandleNotAllLabelsHaveValues() {
222 $m = StatsFactory::newNull();
223 $m->getGauge( 'testMetricGauge' )->setLabel( 'labelOne', 'a' )->set( 1 );
224 $this->expectPHPWarning(
225 'Stats: Cannot associate label keys with label values: Not all initialized labels have an assigned value.',
226 static function () use ( $m ) {
227 $m->getGauge( 'testMetricGauge' )->set( 1 );
228 }
229 );
230 }
231
232 public function testTimingHandleNotAllLabelsHaveValues() {
233 $m = StatsFactory::newNull();
234 $m->getTiming( 'testMetricTiming' )->setLabel( 'labelOne', 'a' )->observe( 1 );
235 $this->expectPHPWarning(
236 'Stats: Cannot associate label keys with label values: Not all initialized labels have an assigned value.',
237 static function () use ( $m ) {
238 $m->getTiming( 'testMetricTiming' )->observe( 1 );
239 }
240 );
241 }
242
243 public function testSampleRateOOB() {
244 $m = StatsFactory::newNull();
245 $metric = @$m->getCounter( 'testMetricCounter' )->setSampleRate( 1.1 );
246 $this->assertInstanceOf( NullMetric::class, $metric );
247 $metric = @$m->getGauge( 'testMetricGauge' )->setSampleRate( -1 );
248 $this->assertInstanceOf( NullMetric::class, $metric );
249 $metric = @$m->getTiming( 'testMetricTimer' )->setSampleRate( 20 );
250 $this->assertInstanceOf( NullMetric::class, $metric );
251 }
252
253 public function testSampleRateDisallowed() {
254 $m = StatsFactory::newNull();
255 $m->getCounter( 'testMetric' )->increment();
256 $metric = @$m->getCounter( 'testMetric' )->setSampleRate( 0.5 );
257 $this->assertInstanceOf( NullMetric::class, $metric );
258 $m->getGauge( 'testMetricGauge' )->set( 1 );
259 $metric = @$m->getGauge( 'testMetricGauge' )->setSampleRate( 0.5 );
260 $this->assertInstanceOf( NullMetric::class, $metric );
261 $m->getTiming( 'testMetricTiming' )->observe( 1 );
262 $metric = @$m->getTiming( 'testMetricTiming' )->setSampleRate( 0.5 );
263 $this->assertInstanceOf( NullMetric::class, $metric );
264 }
265
266 public function testCopyToStatsdAtEmptyArrayResetsValue() {
267 $baseMetric = new BaseMetric( '', 'testMetric' );
268 $metric = new CounterMetric(
269 $baseMetric->withStatsdDataFactory( $this->createMock( IBufferingStatsdDataFactory::class ) ),
270 new NullLogger
271 );
272 $metric->copyToStatsdAt( 'test' );
273 $this->assertEquals( [ 'test' ], $baseMetric->getStatsdNamespaces() );
274 $metric->copyToStatsdAt( [] );
275 $this->assertEquals( [], $baseMetric->getStatsdNamespaces() );
276 }
277
278 public function testStatsdDataFactoryCopyToStatsdAtWithGauge() {
279 $statsFactory = StatsFactory::newNull();
280
281 $gaugeArgs = [ 'test.gauge.1', 'test.gauge.2' ];
282 $statsdMock = $this->createMock( IBufferingStatsdDataFactory::class );
283 $statsdMock->expects( $this->exactly( 2 ) )
284 ->method( 'gauge' )
285 ->with( $this->callback( static function ( $key ) use ( &$gaugeArgs ) {
286 $nextKey = array_shift( $gaugeArgs );
287 return $nextKey === $key;
288 } ) );
289
290 $statsFactory = $statsFactory->withStatsdDataFactory( $statsdMock );
291 $statsFactory->getGauge( 'testMetricGauge' )
292 ->copyToStatsdAt( [ 'test.gauge.1', 'test.gauge.2' ] )
293 ->set( 1 );
294 }
295
296 public function testHandleInvalidStatsdNamespace() {
297 $m = StatsFactory::newNull();
298 $m = $m->withStatsdDataFactory( $this->createMock( IBufferingStatsdDataFactory::class ) );
299 $this->expectPHPWarning(
300 'Stats: StatsD namespace must be a string.',
301 function () use ( $m ) {
302 $metric = $m->getCounter( 'testMetricCounter' )->copyToStatsdAt( null );
303 $this->assertInstanceOf( NullMetric::class, $metric );
304 }
305 );
306 }
307
308 public function testHandleEmptyStatsdNamespace() {
309 $m = StatsFactory::newNull();
310 $m = $m->withStatsdDataFactory( $this->createMock( IBufferingStatsdDataFactory::class ) );
311 $this->expectPHPWarning(
312 'Stats: StatsD namespace cannot be empty.',
313 function () use ( $m ) {
314 $metric = $m->getCounter( 'testMetricCounter' )->copyToStatsdAt( '' );
315 $this->assertInstanceOf( NullMetric::class, $metric );
316 }
317 );
318 }
319
320 public function testHandleNonStringStatsdNamespaceInArray() {
321 $m = StatsFactory::newNull();
322 $m = $m->withStatsdDataFactory( $this->createMock( IBufferingStatsdDataFactory::class ) );
323 $this->expectPHPWarning(
324 'Stats: StatsD namespace must be a string.',
325 function () use ( $m ) {
326 $metric = $m->getCounter( 'testMetricCounter' )->copyToStatsdAt( [ null ] );
327 $this->assertInstanceOf( NullMetric::class, $metric );
328 }
329 );
330 }
331
332 public function testCanChangeLabelsWhileTimerIsStarted() {
333 $cache = new StatsCache;
334 $formatter = OutputFormats::getNewFormatter( OutputFormats::getFormatFromString( 'dogstatsd' ) );
335 $emitter = OutputFormats::getNewEmitter( 'mediawiki', $cache, $formatter );
336 $statsFactory = new StatsFactory( $cache, $emitter, new NullLogger );
337 $timer = $statsFactory->getTiming( 'test', )->setLabel( 'foo', 'bar' );
338
339 // start() and stop() called so close together here should be fractions of a millisecond
340 $timer->start();
341 $timer->setLabel( 'foo', 'baz' )->stop();
342 $this->assertMatchesRegularExpression(
343 '/^mediawiki\.test:(0\.[0-9]+)\|ms\|#foo:baz$/',
344 TestingAccessWrapper::newFromObject( $emitter )->render()[0]
345 );
346 }
347
348 public function testStatsdDataFactoryPersistsWithComponent() {
349 $statsFactory = StatsFactory::newNull();
350
351 $timingArgs = [ 'test.timing.1', 'test.timing.2' ];
352 $statsdMock = $this->createMock( IBufferingStatsdDataFactory::class );
353 $statsdMock->expects( $this->exactly( 2 ) )
354 ->method( 'timing' )
355 ->with( $this->callback( static function ( $key ) use ( &$timingArgs ) {
356 $nextKey = array_shift( $timingArgs );
357 return $nextKey === $key;
358 }, 1.0 ) );
359
360 $statsFactory = $statsFactory->withStatsdDataFactory( $statsdMock );
361
362 // withComponent() returns a whole new StatsFactory instance
363 $componentStatsFactory = $statsFactory->withComponent( 'TestComponent' );
364
365 $componentStatsFactory->getTiming( 'testMetricTiming' )
366 ->copyToStatsdAt( [ 'test.timing.1', 'test.timing.2' ] )
367 ->observe( 1 );
368 }
369
370 public function testWithComponentStatsdFactoryChanges() {
371 $statsFactory = StatsFactory::newNull();
372
373 // statsdDataFactory should be null if withComponent called prior to calling withStatsdDataFactory()
374 $noStatsd = TestingAccessWrapper::newFromObject( $statsFactory->withComponent( 'foo' ) );
375 $this->assertNull( $noStatsd->statsdDataFactory );
376
377 // call withStatsdDataFactory
378 $statsFactory = $statsFactory->withStatsdDataFactory( $this->createMock( IBufferingStatsdDataFactory::class ) );
379
380 // statsdDataFactory should be an instance of IBufferingStatsdDataFactory
381 $yesStatsd = TestingAccessWrapper::newFromObject( $statsFactory->withComponent( 'foo' ) );
382 $this->assertInstanceOf( IBufferingStatsdDataFactory::class, $yesStatsd->statsdDataFactory );
383
384 // disable statsdDataFactory
385 $statsFactory = $statsFactory->withStatsdDataFactory( null );
386
387 // statsdDataFactory should be null again
388 $noStatsdAgain = TestingAccessWrapper::newFromObject( $statsFactory->withComponent( 'foo' ) );
389 $this->assertNull( $noStatsdAgain->statsdDataFactory );
390 }
391
392 /**
393 * PHPUnit 10 compatible replacement for expectWarning().
394 *
395 * @param string $msg
396 * @param callable $callback
397 * @return void
398 */
399 private function expectPHPWarning( string $msg, callable $callback ): void {
400 try {
401 $errorEmitted = false;
402 set_error_handler( function ( $_, $actualMsg ) use ( $msg, &$errorEmitted ) {
403 $this->assertStringContainsString( $msg, $actualMsg );
404 $errorEmitted = true;
405 }, E_USER_WARNING );
406 $callback();
407 $this->assertTrue( $errorEmitted, "No PHP warning was emitted." );
408 } finally {
409 restore_error_handler();
410 }
411 }
412
413 public function testMsConversion() {
414 $statsFactory = StatsFactory::newNull();
415 $statsFactory->getTiming( 'test_seconds' )->observeSeconds( 1 );
416 $statsFactory->getTiming( 'test_seconds' )->observeNanoseconds( 1000000 );
417 $samples = $statsFactory->getTiming( 'test_seconds' )->getSamples();
418 $this->assertEquals(
419 [ 1000, 1 ],
420 array_map(
421 static function ( $sample ) {
422 return $sample->getValue();
423 },
424 $samples
425 )
426 );
427 }
428 }