-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathComponentTestCaseBase.php
More file actions
577 lines (519 loc) · 21 KB
/
Copy pathComponentTestCaseBase.php
File metadata and controls
577 lines (519 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
<?php
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
declare(strict_types=1);
namespace ElasticApmTests\ComponentTests\Util;
use Elastic\Apm\Impl\AutoInstrument\AutoInstrumentationBase;
use Elastic\Apm\Impl\Config\OptionDefaultValues;
use Elastic\Apm\Impl\Config\OptionNames;
use Elastic\Apm\Impl\GlobalTracerHolder;
use Elastic\Apm\Impl\Log\Level as LogLevel;
use Elastic\Apm\Impl\Log\LoggableToString;
use Elastic\Apm\Impl\Tracer;
use Elastic\Apm\Impl\TransactionContext;
use Elastic\Apm\Impl\Util\BoolUtil;
use Elastic\Apm\Impl\Util\ClassNameUtil;
use Elastic\Apm\Impl\Util\RangeUtil;
use ElasticApmTests\Util\AssertMessageStack;
use ElasticApmTests\Util\DataFromAgent;
use ElasticApmTests\Util\IterableUtilForTests;
use ElasticApmTests\Util\MixedMap;
use ElasticApmTests\Util\TestCaseBase;
use ElasticApmTests\Util\TransactionContextDto;
use ElasticApmTests\Util\TransactionDto;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
use Throwable;
class ComponentTestCaseBase extends TestCaseBase
{
/** @var ?TestCaseHandle */
private $testCaseHandle = null;
public const LOG_LEVEL_FOR_PROD_CODE_KEY = 'log_level_for_prod_code';
public const LOG_LEVEL_FOR_TEST_CODE_KEY = 'log_level_for_test_code';
protected const LOG_LEVEL_FOR_CODE_KEYS = [self::LOG_LEVEL_FOR_PROD_CODE_KEY, self::LOG_LEVEL_FOR_TEST_CODE_KEY];
protected function initTestCaseHandle(?int $escalatedLogLevelForProdCode = null): TestCaseHandle
{
if ($this->testCaseHandle !== null) {
return $this->testCaseHandle;
}
ComponentTestsPhpUnitExtension::initSingletons();
$this->testCaseHandle = new TestCaseHandle($escalatedLogLevelForProdCode, $this->isSpanCompressionCompatible());
return $this->testCaseHandle;
}
protected function getTestCaseHandle(): TestCaseHandle
{
return $this->initTestCaseHandle();
}
/** @inheritDoc */
public function tearDown(): void
{
if ($this->testCaseHandle !== null) {
$this->testCaseHandle->tearDown();
$this->testCaseHandle = null;
}
parent::tearDown();
}
/**
* Sub-classes should override this method to return false
* in order to disable Span Compression feature and have all the expected spans individually.
*
* @return bool
*/
protected function isSpanCompressionCompatible(): bool
{
return true;
}
public static function appCodeEmpty(): void
{
}
public static function getTracerFromAppCode(): Tracer
{
$tracer = GlobalTracerHolder::getValue();
TestCase::assertInstanceOf(Tracer::class, $tracer);
/** @var Tracer $tracer */
return $tracer;
}
protected static function buildResourcesClientForAppCode(): ResourcesClient
{
$resCleanerId = AmbientContextForTests::testConfig()->dataPerProcess->resourcesCleanerSpawnedProcessInternalId;
TestCase::assertNotNull($resCleanerId);
$resCleanerPort = AmbientContextForTests::testConfig()->dataPerProcess->resourcesCleanerPort;
TestCase::assertNotNull($resCleanerPort);
return new ResourcesClient($resCleanerId, $resCleanerPort);
}
/**
* @param string $optName
* @param null|string|int|float|bool $optVal
*
* @return DataFromAgent
*/
protected function configTestImpl(string $optName, $optVal): DataFromAgent
{
$testCaseHandle = $this->getTestCaseHandle();
$appCodeHost = $testCaseHandle->ensureMainAppCodeHost(
function (AppCodeHostParams $appCodeParams) use ($optName, $optVal): void {
if ($optVal !== null) {
$appCodeParams->setAgentOption($optName, $optVal);
}
}
);
$appCodeHost->sendRequest(AppCodeTarget::asRouted([__CLASS__, 'appCodeEmpty']));
return $this->waitForOneEmptyTransaction($testCaseHandle);
}
public static function isSmoke(): bool
{
ComponentTestsPhpUnitExtension::initSingletons();
return AmbientContextForTests::testConfig()->isSmoke();
}
public static function isMainAppCodeHostHttp(): bool
{
ComponentTestsPhpUnitExtension::initSingletons();
return AmbientContextForTests::testConfig()->appCodeHostKind()->isHttp();
}
protected function skipIfMainAppCodeHostIsNotCliScript(): bool
{
if (self::isMainAppCodeHostHttp()) {
self::dummyAssert();
return true;
}
return false;
}
protected function skipIfMainAppCodeHostIsNotHttp(): bool
{
if (!self::isMainAppCodeHostHttp()) {
self::dummyAssert();
return true;
}
return false;
}
protected function waitForOneEmptyTransaction(TestCaseHandle $testCaseHandle): DataFromAgentPlusRaw
{
$dataFromAgent = $testCaseHandle->waitForDataFromAgent((new ExpectedEventCounts())->transactions(1));
$this->verifyOneTransactionNoSpans($dataFromAgent);
return $dataFromAgent;
}
protected function verifyOneTransactionNoSpans(DataFromAgent $dataFromAgent): TransactionDto
{
$this->assertEmpty($dataFromAgent->idToSpan);
$tx = $dataFromAgent->singleTransaction();
$this->assertSame(0, $tx->startedSpansCount);
$this->assertSame(0, $tx->droppedSpansCount);
$this->assertNull($tx->parentId);
return $tx;
}
/**
* @param class-string<AutoInstrumentationBase> $instrClassName
* @param string[] $expectedNames
*
* @return void
*/
protected static function implTestIsAutoInstrumentationEnabled(string $instrClassName, array $expectedNames): void
{
AssertMessageStack::newScope(/* out */ $dbgCtx);
$dbgCtx->add(['instrClassName' => $instrClassName, 'expectedNames' => $expectedNames]);
/** @var AutoInstrumentationBase $instr */
$instr = new $instrClassName(self::buildTracerForTests()->build());
$actualNames = $instr->keywords();
$actualNames[] = $instr->name();
self::assertEqualAsSets($expectedNames, $actualNames);
$isEnabledByDefault = OptionDefaultValues::AST_PROCESS_ENABLED || (!$instr->requiresUserlandCodeInstrumentation()); // @phpstan-ignore-line
self::assertSame($isEnabledByDefault, $instr->isEnabled());
/**
* @param string $name
*
* @return iterable<string>
*/
$genDisabledVariants = function (string $name): iterable {
yield $name;
yield '*' . $name;
yield $name . '*';
yield '*' . $name . '*';
yield '*someOtherDummyInstrumentationA*, ' . $name;
yield $name . ', *someOtherDummyInstrumentationB*';
yield '*someOtherDummyInstrumentationA*, ' . $name . ', *someOtherDummyInstrumentationB*';
};
foreach ($expectedNames as $name) {
$dbgCtx->pushSubScope();
foreach ($genDisabledVariants($name) as $disableInstrumentationsOptVal) {
$dbgCtx->clearCurrentSubScope(['name' => $name, 'disableInstrumentationsOptVal' => $disableInstrumentationsOptVal]);
$tracer = self::buildTracerForTests()->withConfig(OptionNames::DISABLE_INSTRUMENTATIONS, $disableInstrumentationsOptVal)->build();
$instr = new $instrClassName($tracer);
self::assertFalse($instr->isEnabled());
}
$dbgCtx->popSubScope();
}
/**
* @return iterable<string>
*/
$genEnabledVariants = function (): iterable {
yield '*someOtherDummyInstrumentation*';
yield '*someOtherDummyInstrumentationA*, *someOtherDummyInstrumentationB*';
};
$dbgCtx->pushSubScope();
foreach ($genEnabledVariants() as $disableInstrumentationsOptVal) {
$dbgCtx->clearCurrentSubScope(['disableInstrumentationsOptVal' => $disableInstrumentationsOptVal]);
$tracer = self::buildTracerForTests()->withConfig(OptionNames::DISABLE_INSTRUMENTATIONS, $disableInstrumentationsOptVal)->build();
$instr = new $instrClassName($tracer);
self::assertSame($isEnabledByDefault, $instr->isEnabled());
}
$dbgCtx->popSubScope();
$dbgCtx->pushSubScope();
foreach ([true, false] as $astProcessEnabled) {
$dbgCtx->clearCurrentSubScope(['astProcessEnabled' => $astProcessEnabled]);
$expectedIsEnabled = $astProcessEnabled || (!$instr->requiresUserlandCodeInstrumentation());
$tracer = self::buildTracerForTests()->withConfig(OptionNames::AST_PROCESS_ENABLED, BoolUtil::toString($astProcessEnabled))->build();
$instr = new $instrClassName($tracer);
self::assertSame($expectedIsEnabled, $instr->isEnabled());
}
$dbgCtx->popSubScope();
}
/**
* @template T
*
* @param iterable<T> $variants
*
* @return iterable<T>
*/
public static function adaptToSmoke(iterable $variants): iterable
{
if (!self::isSmoke()) {
return $variants;
}
foreach ($variants as $key => $value) {
return [$key => $value];
}
return [];
}
/**
* @return callable(iterable<mixed>): iterable<mixed>
*/
public static function adaptToSmokeAsCallable(): callable
{
/**
* @template T
*
* @param iterable<T> $dataSets
*
* @return iterable<T>
*/
return function (iterable $dataSets): iterable {
return self::adaptToSmoke($dataSets);
};
}
/**
* @template TKey of array-key
* @template TValue
*
* @param iterable<TKey, TValue> $variants
*
* @return iterable<TKey, TValue>
*/
public function adaptKeyValueToSmoke(iterable $variants): iterable
{
if (!self::isSmoke()) {
return $variants;
}
foreach ($variants as $key => $value) {
return [$key => $value];
}
return [];
}
/**
* @return iterable<array{bool}>
*/
public function boolDataProviderAdaptedToSmoke(): iterable
{
return self::adaptToSmoke(self::boolDataProvider());
}
/**
* @param string $dbgTestDesc
* @param callable(): void $testCall
*
* @return void
*/
protected function runAndEscalateLogLevelOnFailure(string $dbgTestDesc, callable $testCall): void
{
$logLevelForTestCodeToRestore = AmbientContextForTests::testConfig()->logLevel;
try {
$this->runAndEscalateLogLevelOnFailureImpl($dbgTestDesc, $testCall);
} finally {
AmbientContextForTests::resetLogLevel($logLevelForTestCodeToRestore);
}
}
/**
* @param string $dbgTestDesc
* @param callable(): void $testCall
*
* @return void
*/
private function runAndEscalateLogLevelOnFailureImpl(string $dbgTestDesc, callable $testCall): void
{
try {
$testCall();
return;
} catch (Throwable $ex) {
$initiallyFailedTestException = $ex;
}
$logger = $this->getLogger(__NAMESPACE__, __CLASS__, __FILE__)->addContext('dbgTestDesc', $dbgTestDesc);
$loggerProxyOutsideIt = $logger->ifCriticalLevelEnabledNoLine(__FUNCTION__);
if ($this->testCaseHandle === null) {
$loggerProxyOutsideIt && $loggerProxyOutsideIt->log(__LINE__, 'Test failed but $this->testCaseHandle is null - NOT re-running the test with escalated log levels');
throw $initiallyFailedTestException;
}
$initiallyFailedTestLogLevels = $this->getCurrentLogLevels($this->testCaseHandle);
$logger->addAllContext(['initiallyFailedTestLogLevels' => self::logLevelsWithNames($initiallyFailedTestLogLevels), 'initiallyFailedTestException' => $initiallyFailedTestException]);
$loggerProxyOutsideIt && $loggerProxyOutsideIt->log(__LINE__, 'Test failed');
$escalatedLogLevelsSeq = self::generateLevelsForRunAndEscalateLogLevelOnFailure($initiallyFailedTestLogLevels, AmbientContextForTests::testConfig()->escalatedRerunsMaxCount);
$rerunCount = 0;
foreach ($escalatedLogLevelsSeq as $escalatedLogLevels) {
$this->tearDown();
++$rerunCount;
$loggerPerIt = $logger->inherit()->addAllContext(['rerunCount' => $rerunCount, 'escalatedLogLevels' => self::logLevelsWithNames($escalatedLogLevels)]);
$loggerProxyPerIt = $loggerPerIt->ifCriticalLevelEnabledNoLine(__FUNCTION__);
$loggerProxyPerIt && $loggerProxyPerIt->log(__LINE__, 'Re-running failed test with escalated log levels...');
AmbientContextForTests::resetLogLevel($escalatedLogLevels[self::LOG_LEVEL_FOR_TEST_CODE_KEY]);
$this->initTestCaseHandle($escalatedLogLevels[self::LOG_LEVEL_FOR_PROD_CODE_KEY]);
try {
$testCall();
$loggerProxyPerIt && $loggerProxyPerIt->log(__LINE__, 'Re-run of failed test with escalated log levels did NOT fail (which is bad :(');
} catch (Throwable $ex) {
$loggerProxyPerIt && $loggerProxyPerIt->log(__LINE__, 'Re-run of failed test with escalated log levels failed (which is good :)', ['ex' => $ex]);
throw $ex;
}
}
if ($rerunCount === 0) {
$loggerProxyOutsideIt && $loggerProxyOutsideIt->log(__LINE__, 'There were no test re-runs with escalated log levels - re-throwing original test failure exception');
} else {
$loggerProxyOutsideIt && $loggerProxyOutsideIt->log(__LINE__, 'All test re-runs with escalated log levels did NOT fail (which is bad :( - re-throwing original test failure exception');
}
throw $initiallyFailedTestException;
}
/**
* @param class-string $testClass
* @param string $testFunc
*
* @return string
*/
protected static function buildDbgDescForTest(string $testClass, string $testFunc): string
{
return ClassNameUtil::fqToShort($testClass) . '::' . $testFunc;
}
/**
* @param class-string $testClass
* @param string $testFunc
* @param MixedMap $testArgs
*
* @return string
*/
protected static function buildDbgDescForTestWithArtgs(string $testClass, string $testFunc, MixedMap $testArgs): string
{
return ClassNameUtil::fqToShort($testClass) . '::' . $testFunc . '(' . LoggableToString::convert($testArgs) . ')';
}
/**
* @param TestCaseHandle $testCaseHandle
*
* @return array<string, int>
*/
private function getCurrentLogLevels(TestCaseHandle $testCaseHandle): array
{
$result = [];
$prodCodeLogLevels = $testCaseHandle->getProdCodeLogLevels();
Assert::assertNotEmpty($prodCodeLogLevels);
$result[self::LOG_LEVEL_FOR_PROD_CODE_KEY] = min($prodCodeLogLevels);
$result[self::LOG_LEVEL_FOR_TEST_CODE_KEY] = AmbientContextForTests::testConfig()->logLevel;
/** @var array<string, int> $result */
return $result;
}
/**
* @param array<string, int> $initialLevels
*
* @return iterable<array<string, int>>
*/
public static function generateEscalatedLogLevels(array $initialLevels): iterable
{
Assert::assertNotEmpty($initialLevels);
/**
* @param array<string, int> $currentLevels
*
* @return bool
*/
$haveCurrentLevelsReachedInitial = function (array $currentLevels) use ($initialLevels): bool {
foreach ($initialLevels as $levelTypeKey => $initialLevel) {
if ($initialLevel < $currentLevels[$levelTypeKey]) {
return false;
}
}
return true;
};
/** @var int $minInitialLevel */
$minInitialLevel = min($initialLevels);
$maxDelta = 0;
foreach ($initialLevels as $initialLevel) {
$maxDelta = max($maxDelta, LogLevel::getHighest() - $initialLevel);
}
foreach (RangeUtil::generateDown(LogLevel::getHighest(), $minInitialLevel) as $baseLevel) {
Assert::assertGreaterThan(LogLevel::OFF, $baseLevel);
$currentLevels = [];
foreach (self::LOG_LEVEL_FOR_CODE_KEYS as $levelTypeKey) {
$currentLevels[$levelTypeKey] = $baseLevel;
}
yield $currentLevels;
foreach (RangeUtil::generate(1, $maxDelta + 1) as $delta) {
foreach (self::LOG_LEVEL_FOR_CODE_KEYS as $levelTypeKey) {
if ($baseLevel < $initialLevels[$levelTypeKey] + $delta) {
continue;
}
$currentLevels[$levelTypeKey] = $baseLevel - $delta;
if (!$haveCurrentLevelsReachedInitial($currentLevels)) {
yield $currentLevels;
}
$currentLevels[$levelTypeKey] = $baseLevel;
}
}
}
}
/**
* @param array<string, int> $initialLevels
*
* @return iterable<array<string, int>>
*/
protected static function generateLevelsForRunAndEscalateLogLevelOnFailure(
array $initialLevels,
int $eachLevelsSetMaxCount
): iterable {
$result = self::generateEscalatedLogLevels($initialLevels);
$result = IterableUtilForTests::concat($result, [$initialLevels]);
/** @noinspection PhpUnnecessaryLocalVariableInspection */
$result = IterableUtilForTests::duplicateEachElement($result, $eachLevelsSetMaxCount);
return $result;
}
/**
* @param array<string, int> $logLevels
*
* @return array<string, string>
*/
protected static function logLevelsWithNames(array $logLevels): array
{
$result = [];
foreach ($logLevels as $levelTypeKey => $logLevel) {
$result[$levelTypeKey] = LogLevel::intToName($logLevel) . ' (' . $logLevel . ')';
}
return $result;
}
/**
* @template TKey of array-key
* @template TValue
*
* @param array<TKey, TValue> $array
* @param TKey $key
*
* @return TValue
*/
public static function &assertAndGetFromArrayByKey(array $array, $key)
{
self::assertArrayHasKey($key, $array);
return $array[$key];
}
/**
* @param TransactionContext $ctx
* @param string $key
* @param mixed $value
*
* @return void
*/
public static function setContextCustom(TransactionContext $ctx, string $key, $value): void
{
$valueSerialized = base64_encode(serialize($value));
$nonKeywordStringMaxLength = self::getTracerFromAppCode()->getConfig()->nonKeywordStringMaxLength();
self::assertLessThanOrEqual($nonKeywordStringMaxLength, strlen($valueSerialized));
$ctx->setCustom($key, $valueSerialized);
$ctx->setCustom($key . '_crc', crc32($valueSerialized));
}
/**
* @param TransactionContextDto $ctx
* @param string $key
*
* @return mixed
*/
public static function getContextCustom(TransactionContextDto $ctx, string $key)
{
self::assertNotNull($ctx->custom);
$valueSerialized = self::assertAndGetFromArrayByKey($ctx->custom, $key);
self::assertIsString($valueSerialized);
self::assertArrayHasKey($key . '_crc', $ctx->custom);
$receivedCrc = self::assertAndGetFromArrayByKey($ctx->custom, $key . '_crc');
$calculatedCrc = crc32($valueSerialized);
self::assertSame($receivedCrc, $calculatedCrc);
return unserialize(base64_decode($valueSerialized));
}
protected static function disableTimingDependentFeatures(AppCodeHostParams $appCodeParams): void
{
// Disable Span Compression feature to have all the expected spans individually
$appCodeParams->setAgentOption(OptionNames::SPAN_COMPRESSION_ENABLED, false);
// Enable span stack trace collection for span with any duration
$appCodeParams->setAgentOption(OptionNames::SPAN_STACK_TRACE_MIN_DURATION, 0);
}
protected static function setConfigIfNotNull(MixedMap $testArgs, string $optName, AppCodeHostParams $appCodeParams): void
{
$optVal = $testArgs->getNullableString($optName);
if ($optVal !== null) {
$appCodeParams->setAgentOption($optName, $optVal);
}
}
}