| 1 |
<?php |
| 2 |
namespace Wikimedia\Tests\Telemetry; |
| 3 |
|
| 4 |
use MediaWikiUnitTestCase; |
| 5 |
use Wikimedia\Assert\ParameterAssertionException; |
| 6 |
use Wikimedia\Telemetry\ProbabilisticSampler; |
| 7 |
use Wikimedia\Telemetry\SamplerInterface; |
| 8 |
use Wikimedia\Telemetry\SpanContext; |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
class ProbabilisticSamplerTest extends MediaWikiUnitTestCase { |
| 14 |
private const DO_NOT_SAMPLE_SEED = 12; |
| 15 |
private const SAMPLE_SEED = 5; |
| 16 |
|
| 17 |
private SamplerInterface $sampler; |
| 18 |
|
| 19 |
public function setUp(): void { |
| 20 |
parent::setUp(); |
| 21 |
$this->sampler = new ProbabilisticSampler( 30 ); |
| 22 |
} |
| 23 |
|
| 24 |
public function testShouldNotSampleSpanWithNoParentBasedOnChance(): void { |
| 25 |
mt_srand( self::DO_NOT_SAMPLE_SEED ); |
| 26 |
|
| 27 |
$sampled = $this->sampler->shouldSample( null ); |
| 28 |
|
| 29 |
$this->assertFalse( $sampled ); |
| 30 |
} |
| 31 |
|
| 32 |
public function testShouldSampleSpanWithNoParentBasedOnChance(): void { |
| 33 |
mt_srand( self::SAMPLE_SEED ); |
| 34 |
|
| 35 |
$sampled = $this->sampler->shouldSample( null ); |
| 36 |
|
| 37 |
$this->assertTrue( $sampled ); |
| 38 |
} |
| 39 |
|
| 40 |
public function testShouldSampleSpanWithParentBasedOnParentDecision(): void { |
| 41 |
mt_srand( self::DO_NOT_SAMPLE_SEED ); |
| 42 |
|
| 43 |
$parentSpanContext = new SpanContext( '', '', null, '', true ); |
| 44 |
|
| 45 |
$sampled = $this->sampler->shouldSample( $parentSpanContext ); |
| 46 |
|
| 47 |
$this->assertTrue( $sampled ); |
| 48 |
} |
| 49 |
|
| 50 |
public function testShouldNotSampleSpanWithParentBasedOnParentDecision(): void { |
| 51 |
mt_srand( self::SAMPLE_SEED ); |
| 52 |
|
| 53 |
$parentSpanContext = new SpanContext( '', '', null, '', false ); |
| 54 |
|
| 55 |
$sampled = $this->sampler->shouldSample( $parentSpanContext ); |
| 56 |
|
| 57 |
$this->assertFalse( $sampled ); |
| 58 |
} |
| 59 |
|
| 60 |
public function testShouldThrowOnInvalidPercentChance(): void { |
| 61 |
$this->expectException( ParameterAssertionException::class ); |
| 62 |
$this->expectExceptionMessage( 'Bad value for parameter $percentChance: must be between 0 and 100 inclusive' ); |
| 63 |
|
| 64 |
new ProbabilisticSampler( 900 ); |
| 65 |
} |
| 66 |
} |