diff --git a/plugin/error-handler/src/ErrorHandlerPlugin.php b/plugin/error-handler/src/ErrorHandlerPlugin.php index eb9d6e1b..2e629f74 100644 --- a/plugin/error-handler/src/ErrorHandlerPlugin.php +++ b/plugin/error-handler/src/ErrorHandlerPlugin.php @@ -5,6 +5,7 @@ namespace Testo\ErrorHandler; use Internal\Container\Container; +use Testo\Common\Messenger; use Testo\Common\PluginConfigurator; use Testo\ErrorHandler\Internal\ErrorHandlerInterceptor; use Testo\Pipeline\InterceptorCollector; @@ -32,6 +33,6 @@ public function __construct( public function configure(Container $container): void { $container->get(InterceptorCollector::class) - ->addInterceptor(new ErrorHandlerInterceptor($this->failOnError)); + ->addInterceptor(new ErrorHandlerInterceptor($container->get(Messenger::class), $this->failOnError)); } } diff --git a/plugin/error-handler/src/Internal/ErrorHandlerInterceptor.php b/plugin/error-handler/src/Internal/ErrorHandlerInterceptor.php index 12953e8b..bf03d0d1 100644 --- a/plugin/error-handler/src/Internal/ErrorHandlerInterceptor.php +++ b/plugin/error-handler/src/Internal/ErrorHandlerInterceptor.php @@ -9,8 +9,6 @@ use Testo\Core\Context\TestInfo; use Testo\Core\Context\TestResult; use Testo\Core\Log\Level; -use Testo\Core\Log\Message; -use Testo\Core\Log\MessageLog; use Testo\Core\Value\Status; use Testo\ErrorHandler\CapturedErrors; use Testo\ErrorHandler\Exception\ErrorHandlerUnchanged; @@ -26,8 +24,8 @@ * Installs a capturing error handler for the duration of the test and forwards every error to the * handler that was active before. Errors silenced with `@` or excluded by `error_reporting()` are * forwarded but not captured. Captured errors are stored in the returned {@see TestResult} as a - * {@see CapturedErrors} attribute; those the previous handler did not take are also written to the - * `stderr` message channel in place of PHP's own printing. `E_USER_ERROR` is thrown as an + * {@see CapturedErrors} attribute; those the previous handler did not take are also logged to the + * `stderr` channel of the {@see Messenger} in place of PHP's own printing. `E_USER_ERROR` is thrown as an * {@see \ErrorException}. * * A passing test that leaves the handler stack changed is reported {@see Status::Risky} unless it @@ -48,10 +46,13 @@ private const CHANNEL = 'error-handler'; /** + * @param Messenger $messenger Receives the unhandled errors and the plugin's verdicts on the + * handler stack, attributed to the running test. * @param bool $failOnError When true, any captured error upgrades a passing test to * {@see Status::Failed} with the first error wrapped in an {@see \ErrorException} as the failure. */ public function __construct( + private Messenger $messenger, private bool $failOnError = false, ) {} @@ -61,20 +62,16 @@ public function runTest(TestInfo $info, callable $next): TestResult if (self::declares($info, WithoutErrorHandler::class)) { $result = $next($info); - return self::declares($info, ExpectErrorHandlerChange::class) - ? $result->withMessages(new MessageLog([ - ...$result->messages->all(), - new Message( - \microtime(true), - Messenger::CHANNEL_STDERR, - Level::Warning, - '#[ExpectErrorHandlerChange] has no effect together with #[WithoutErrorHandler]: no handler is installed, so no stack change is checked.', - ), - ])) - : $result; + self::declares($info, ExpectErrorHandlerChange::class) and $this->messenger->log( + Messenger::CHANNEL_STDERR, + '#[ExpectErrorHandlerChange] has no effect together with #[WithoutErrorHandler]: no handler is installed, so no stack change is checked.', + Level::Warning, + ); + + return $result; } - $scope = new HandlerScope(); + $scope = new HandlerScope($this->messenger); $result = $this->run($info, $next, $scope); if ($result->status === Status::Passed) { @@ -82,14 +79,10 @@ public function runTest(TestInfo $info, callable $next): TestResult if ($declared && !$scope->changed()) { $result = $result->with(status: Status::Failed)->withFailure(new ErrorHandlerUnchanged()); } elseif (!$declared && $scope->changed()) { - $result = $result - ->with(status: Status::Risky) - ->withMessages(new MessageLog([ - ...$result->messages->all(), - new Message(\microtime(true), self::CHANNEL, Level::Warning, $scope->removed() - ? 'Test code or tested code removed error handlers other than its own.' - : 'Test code or tested code did not remove its own error handlers.'), - ])); + $result = $result->with(status: Status::Risky); + $this->messenger->log(self::CHANNEL, $scope->removed() + ? 'Test code or tested code removed error handlers other than its own.' + : 'Test code or tested code did not remove its own error handlers.', Level::Warning); } } @@ -98,7 +91,6 @@ public function runTest(TestInfo $info, callable $next): TestResult } $result = $result->withAttribute(CapturedErrors::class, new CapturedErrors($scope->errors)); - $scope->stderr === [] or $result = $result->withMessages(new MessageLog([...$result->messages->all(), ...$scope->stderr])); if ($this->failOnError && $result->status === Status::Passed) { $first = $scope->errors[0]; diff --git a/plugin/error-handler/src/Internal/HandlerScope.php b/plugin/error-handler/src/Internal/HandlerScope.php index ccecebc8..e6b41e36 100644 --- a/plugin/error-handler/src/Internal/HandlerScope.php +++ b/plugin/error-handler/src/Internal/HandlerScope.php @@ -6,7 +6,6 @@ use Testo\Common\Messenger; use Testo\Core\Log\Level; -use Testo\Core\Log\Message; use Testo\ErrorHandler\CapturedError; /** @@ -25,9 +24,6 @@ final class HandlerScope /** @var list */ public array $errors = []; - /** @var list What PHP would have printed for the errors nobody handled. */ - public array $stderr = []; - private readonly \Closure $handler; /** @var list Stack as it was before {@see install()}, bottom first. */ @@ -40,9 +36,12 @@ final class HandlerScope private bool $removed = false; private bool $left = false; - public function __construct() + /** + * @param Messenger $messenger Receives what PHP would have printed for the errors nobody handled. + */ + public function __construct(Messenger $messenger) { - $this->handler = function (int $severity, string $message, string $file, int $line): bool { + $this->handler = function (int $severity, string $message, string $file, int $line) use ($messenger): bool { // Forwarded first: a previous handler that throws turns the error into control flow of // the test, and then there is nothing to capture. $handled = $this->previous !== null && (bool) ($this->previous)($severity, $message, $file, $line); @@ -57,11 +56,10 @@ public function __construct() $error = new CapturedError($severity, $message, $file, $line, $handled); $this->errors[] = $error; - $handled or $this->stderr[] = new Message( - \microtime(true), + $handled or $messenger->log( Messenger::CHANNEL_STDERR, - self::level($severity), (string) $error, + self::level($severity), ['severity' => $severity, 'file' => $file, 'line' => $line], ); diff --git a/plugin/error-handler/tests/Feature/StderrFeatureTest.php b/plugin/error-handler/tests/Feature/StderrFeatureTest.php new file mode 100644 index 00000000..76015882 --- /dev/null +++ b/plugin/error-handler/tests/Feature/StderrFeatureTest.php @@ -0,0 +1,41 @@ +status, Status::Passed); + $stderr = $result->messages->channel(Messenger::CHANNEL_STDERR); + Assert::count($stderr, 1); + Assert::string($stderr[0]->content)->startsWith('Warning: Stub warning in '); + } +} diff --git a/plugin/error-handler/tests/Unit/ErrorHandlerInterceptorTest.php b/plugin/error-handler/tests/Unit/ErrorHandlerInterceptorTest.php index 9b2d3691..10259971 100644 --- a/plugin/error-handler/tests/Unit/ErrorHandlerInterceptorTest.php +++ b/plugin/error-handler/tests/Unit/ErrorHandlerInterceptorTest.php @@ -5,6 +5,8 @@ namespace Tests\ErrorHandler\Unit; use Internal\Path; +use Psr\EventDispatcher\EventDispatcherInterface; +use Testo\Application\Internal\MessengerHub; use Testo\Assert; use Testo\Codecov\Covers; use Testo\Common\Messenger; @@ -38,7 +40,7 @@ final class ErrorHandlerInterceptorTest { public function noErrorsPassesResultThrough(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static fn(TestInfo $info): TestResult => new TestResult(info: $info, status: Status::Passed); @@ -50,7 +52,7 @@ public function noErrorsPassesResultThrough(): void public function capturedErrorIsStoredAsAttribute(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('test warning', \E_USER_WARNING); @@ -70,7 +72,7 @@ public function capturedErrorIsStoredAsAttribute(): void public function multipleErrorsAreAllCaptured(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('first', \E_USER_NOTICE); @@ -91,7 +93,7 @@ public function multipleErrorsAreAllCaptured(): void public function collectModePreservesPassingStatus(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: false); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: false); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('deprecated usage', \E_USER_DEPRECATED); @@ -106,7 +108,7 @@ public function collectModePreservesPassingStatus(): void public function failModeUpgradesPassingTestToFailed(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: true); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('user warning', \E_USER_WARNING); @@ -123,7 +125,7 @@ public function failModeUpgradesPassingTestToFailed(): void public function failModeUsesFirstErrorAsFailure(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: true); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('first error', \E_USER_WARNING); @@ -140,7 +142,7 @@ public function failModeUsesFirstErrorAsFailure(): void public function failModeDoesNotOverrideAlreadyFailedTest(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: true); $info = self::createTestInfo(); $originalFailure = new \RuntimeException('assertion failure'); $next = static function (TestInfo $info) use ($originalFailure): TestResult { @@ -156,7 +158,7 @@ public function failModeDoesNotOverrideAlreadyFailedTest(): void public function failModeDoesNotOverrideErrorStatus(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: true); $info = self::createTestInfo(); $originalFailure = new \RuntimeException('unexpected throw'); $next = static function (TestInfo $info) use ($originalFailure): TestResult { @@ -172,7 +174,7 @@ public function failModeDoesNotOverrideErrorStatus(): void public function handlerIsRestoredAfterTestCompletes(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static fn(TestInfo $info): TestResult => new TestResult(info: $info, status: Status::Passed); @@ -194,7 +196,7 @@ public function handlerIsRestoredAfterTestCompletes(): void public function handlerIsRestoredEvenWhenTestThrows(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static fn(): TestResult => throw new \RuntimeException('unexpected throw'); @@ -219,7 +221,7 @@ public function handlerIsRestoredEvenWhenTestThrows(): void public function restoresTheOuterHandlerWhileSuspendedAndReinstallsItsOwnOnResume(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $outer = []; @@ -260,7 +262,7 @@ public function restoresTheOuterHandlerWhileSuspendedAndReinstallsItsOwnOnResume public function silencedErrorIsNotCaptured(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: true); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { @\trigger_error('silenced', \E_USER_WARNING); @@ -278,7 +280,7 @@ public function silencedErrorIsNotCaptured(): void */ public function silencedErrorStaysAvailableToErrorGetLast(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $last = null; $next = static function (TestInfo $info) use (&$last): TestResult { @@ -295,7 +297,7 @@ public function silencedErrorStaysAvailableToErrorGetLast(): void public function errorOutsideErrorReportingIsNotCaptured(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: true); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('deprecated', \E_USER_DEPRECATED); @@ -315,7 +317,7 @@ public function errorOutsideErrorReportingIsNotCaptured(): void public function handlerLeftByTestDoesNotShadowOuterHandler(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \set_error_handler(static fn(): bool => true); @@ -340,7 +342,7 @@ public function handlerLeftByTestDoesNotShadowOuterHandler(): void public function handlerLeftByTestDoesNotCaptureSiblingErrorsWhileSuspended(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \set_error_handler(static fn(): bool => true); @@ -370,7 +372,7 @@ public function handlerLeftByTestDoesNotCaptureSiblingErrorsWhileSuspended(): vo public function previousHandlerStillReceivesCapturedErrors(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('forwarded', \E_USER_WARNING); @@ -397,7 +399,7 @@ public function previousHandlerStillReceivesCapturedErrors(): void public function previousHandlerTurningErrorIntoExceptionLeavesNothingCaptured(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: true); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { try { @@ -423,7 +425,7 @@ public function previousHandlerTurningErrorIntoExceptionLeavesNothingCaptured(): public function previousHandlerObservesTheRealErrorReportingLevel(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('probe', \E_USER_WARNING); @@ -454,7 +456,8 @@ public function previousHandlerObservesTheRealErrorReportingLevel(): void #[WithoutErrorHandler] public function unhandledErrorIsWrittenToStderrChannel(): void { - $interceptor = new ErrorHandlerInterceptor(); + $messenger = self::createMessenger(); + $interceptor = new ErrorHandlerInterceptor($messenger); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('to stderr', \E_USER_WARNING); @@ -467,7 +470,7 @@ public function unhandledErrorIsWrittenToStderrChannel(): void Assert::instanceOf($errors, CapturedErrors::class); Assert::false($errors->errors[0]->handled); - $stderr = $result->messages->channel(Messenger::CHANNEL_STDERR); + $stderr = $messenger->getMessages()->channel(Messenger::CHANNEL_STDERR); Assert::same(\count($stderr), 1); Assert::same($stderr[0]->level, Level::Warning); Assert::same($stderr[0]->content, \sprintf('Warning: to stderr in %s on line %d', __FILE__, $errors->errors[0]->line)); @@ -476,7 +479,8 @@ public function unhandledErrorIsWrittenToStderrChannel(): void public function errorDeclinedByPreviousHandlerIsWrittenToStderr(): void { - $interceptor = new ErrorHandlerInterceptor(); + $messenger = self::createMessenger(); + $interceptor = new ErrorHandlerInterceptor($messenger); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('declined', \E_USER_NOTICE); @@ -491,12 +495,13 @@ public function errorDeclinedByPreviousHandlerIsWrittenToStderr(): void } Assert::false($result->getAttribute(CapturedErrors::class)->errors[0]->handled); - Assert::same(\count($result->messages->channel(Messenger::CHANNEL_STDERR)), 1); + Assert::same(\count($messenger->getMessages()->channel(Messenger::CHANNEL_STDERR)), 1); } public function errorHandledByPreviousHandlerIsCapturedButKeptOutOfStderr(): void { - $interceptor = new ErrorHandlerInterceptor(); + $messenger = self::createMessenger(); + $interceptor = new ErrorHandlerInterceptor($messenger); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('handled upstream', \E_USER_WARNING); @@ -513,12 +518,12 @@ public function errorHandledByPreviousHandlerIsCapturedButKeptOutOfStderr(): voi $errors = $result->getAttribute(CapturedErrors::class); Assert::instanceOf($errors, CapturedErrors::class); Assert::true($errors->errors[0]->handled); - Assert::same($result->messages->channel(Messenger::CHANNEL_STDERR), []); + Assert::same($messenger->getMessages()->channel(Messenger::CHANNEL_STDERR), []); } public function failModeFailsOnErrorHandledUpstreamToo(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: true); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('handled upstream', \E_USER_WARNING); @@ -537,7 +542,7 @@ public function failModeFailsOnErrorHandledUpstreamToo(): void public function unhandledErrorIsNotPrintedByPhp(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $printed = null; $next = static function (TestInfo $info) use (&$printed): TestResult { @@ -559,7 +564,7 @@ public function unhandledErrorIsNotPrintedByPhp(): void public function userErrorBecomesAnException(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \trigger_error('fatal by contract', \E_USER_ERROR); @@ -577,7 +582,8 @@ public function userErrorBecomesAnException(): void public function handlerLeftByTestMarksPassingTestRisky(): void { - $interceptor = new ErrorHandlerInterceptor(); + $messenger = self::createMessenger(); + $interceptor = new ErrorHandlerInterceptor($messenger); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \set_error_handler(static fn(): bool => true); @@ -587,12 +593,12 @@ public function handlerLeftByTestMarksPassingTestRisky(): void $result = $interceptor->runTest($info, $next); Assert::same($result->status, Status::Risky); - Assert::false($result->messages->isEmpty()); + Assert::false($messenger->getMessages()->isEmpty()); } public function handlerLeftByTestDoesNotOverrideFailedStatus(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $failure = new \RuntimeException('assertion failure'); $next = static function (TestInfo $info) use ($failure): TestResult { @@ -608,7 +614,7 @@ public function handlerLeftByTestDoesNotOverrideFailedStatus(): void public function handlerRemovedByTestMarksPassingTestRiskyAndKeepsOuterHandler(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(); $next = static function (TestInfo $info): TestResult { \restore_error_handler(); @@ -634,7 +640,7 @@ public function handlerRemovedByTestMarksPassingTestRiskyAndKeepsOuterHandler(): public function declaredHandlerChangeKeepsPassedStatus(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(new \ReflectionMethod(HandlerChange::class, 'declared')); $next = static function (TestInfo $info): TestResult { \set_error_handler(static fn(): bool => true); @@ -660,7 +666,7 @@ public function declaredHandlerChangeKeepsPassedStatus(): void public function declaredHandlerChangeOnClassAppliesToItsTests(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(new \ReflectionMethod(HandlerChangeCase::class, 'inherited')); $next = static function (TestInfo $info): TestResult { \set_error_handler(static fn(): bool => true); @@ -674,7 +680,7 @@ public function declaredHandlerChangeOnClassAppliesToItsTests(): void public function declaredHandlerChangeThatDoesNotHappenFails(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(new \ReflectionMethod(HandlerChange::class, 'declared')); $next = static fn(TestInfo $info): TestResult => new TestResult(info: $info, status: Status::Passed); @@ -686,7 +692,7 @@ public function declaredHandlerChangeThatDoesNotHappenFails(): void public function undeclaredStubMethodIsHeldToThePlainContract(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(new \ReflectionMethod(HandlerChange::class, 'undeclared')); $next = static function (TestInfo $info): TestResult { \set_error_handler(static fn(): bool => true); @@ -700,7 +706,7 @@ public function undeclaredStubMethodIsHeldToThePlainContract(): void public function handlerInstalledByTestIsBackAfterResume(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(new \ReflectionMethod(HandlerChange::class, 'declared')); $ownCount = 0; @@ -742,7 +748,7 @@ public function handlerInstalledByTestIsBackAfterResume(): void public function optedOutTestRunsWithTheStackItInherited(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(new \ReflectionMethod(NoHandler::class, 'optedOut')); $ambient = static fn(): bool => true; @@ -767,7 +773,8 @@ public function optedOutTestRunsWithTheStackItInherited(): void public function optedOutTestLeavesItsErrorsToTheAmbientHandler(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $messenger = self::createMessenger(); + $interceptor = new ErrorHandlerInterceptor($messenger, failOnError: true); $info = self::createTestInfo(new \ReflectionMethod(NoHandler::class, 'optedOut')); $next = static function (TestInfo $info): TestResult { \trigger_error('nobody captures this', \E_USER_WARNING); @@ -789,12 +796,13 @@ public function optedOutTestLeavesItsErrorsToTheAmbientHandler(): void Assert::same($count, 1); Assert::same($result->status, Status::Passed); Assert::null($result->getAttribute(CapturedErrors::class)); - Assert::same($result->messages->channel(Messenger::CHANNEL_STDERR), []); + Assert::same($messenger->getMessages()->channel(Messenger::CHANNEL_STDERR), []); } public function optedOutTestLeavingAHandlerIsNotRisky(): void { - $interceptor = new ErrorHandlerInterceptor(); + $messenger = self::createMessenger(); + $interceptor = new ErrorHandlerInterceptor($messenger); $info = self::createTestInfo(new \ReflectionMethod(NoHandler::class, 'optedOut')); $next = static function (TestInfo $info): TestResult { \set_error_handler(static fn(): bool => true); @@ -809,12 +817,12 @@ public function optedOutTestLeavingAHandlerIsNotRisky(): void } Assert::same($result->status, Status::Passed); - Assert::true($result->messages->isEmpty()); + Assert::true($messenger->getMessages()->isEmpty()); } public function optedOutOnClassAppliesToItsTests(): void { - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(new \ReflectionMethod(NoHandlerCase::class, 'inherited')); $ambient = static fn(): bool => true; @@ -837,7 +845,8 @@ public function optedOutOnClassAppliesToItsTests(): void public function optedOutWinsOverDeclaredHandlerChange(): void { - $interceptor = new ErrorHandlerInterceptor(); + $messenger = self::createMessenger(); + $interceptor = new ErrorHandlerInterceptor($messenger); $info = self::createTestInfo(new \ReflectionMethod(NoHandler::class, 'optedOutAndDeclaringChange')); $next = static fn(TestInfo $info): TestResult => new TestResult(info: $info, status: Status::Passed); @@ -845,7 +854,7 @@ public function optedOutWinsOverDeclaredHandlerChange(): void Assert::same($result->status, Status::Passed); Assert::null($result->failure); - $stderr = $result->messages->channel(Messenger::CHANNEL_STDERR); + $stderr = $messenger->getMessages()->channel(Messenger::CHANNEL_STDERR); Assert::same(\count($stderr), 1); Assert::same($stderr[0]->level, Level::Warning); Assert::string($stderr[0]->content)->contains('#[ExpectErrorHandlerChange]'); @@ -853,20 +862,21 @@ public function optedOutWinsOverDeclaredHandlerChange(): void public function optedOutAloneWritesNoWarning(): void { - $interceptor = new ErrorHandlerInterceptor(); + $messenger = self::createMessenger(); + $interceptor = new ErrorHandlerInterceptor($messenger); $info = self::createTestInfo(new \ReflectionMethod(NoHandler::class, 'optedOut')); $next = static fn(TestInfo $info): TestResult => new TestResult(info: $info, status: Status::Passed); $result = $interceptor->runTest($info, $next); - Assert::true($result->messages->isEmpty()); + Assert::true($messenger->getMessages()->isEmpty()); } public function optedOutFunctionRunsWithTheStackItInherited(): void { require_once __DIR__ . '/../Stub/no-handler-function.php'; - $interceptor = new ErrorHandlerInterceptor(); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger()); $info = self::createTestInfo(new \ReflectionFunction('Tests\ErrorHandler\Stub\optedOutFunction')); $ambient = static fn(): bool => true; @@ -889,7 +899,7 @@ public function optedOutFunctionRunsWithTheStackItInherited(): void public function optedOutFailingTestKeepsItsResult(): void { - $interceptor = new ErrorHandlerInterceptor(failOnError: true); + $interceptor = new ErrorHandlerInterceptor(self::createMessenger(), failOnError: true); $info = self::createTestInfo(new \ReflectionMethod(NoHandler::class, 'optedOut')); $failed = new TestResult(info: $info, status: Status::Failed, failure: new \RuntimeException('own failure')); $next = static fn(TestInfo $info): TestResult => $failed; @@ -899,6 +909,18 @@ public function optedOutFailingTestKeepsItsResult(): void Assert::same($result, $failed); } + private static function createMessenger(): Messenger + { + return new MessengerHub(new class() implements EventDispatcherInterface { + #[\Override] + public function dispatch(object $event): object + { + return $event; + } + }); + } + + private static function createTestInfo(?\ReflectionFunctionAbstract $reflection = null): TestInfo { $reflection ??= new \ReflectionMethod(self::class, 'createTestInfo'); diff --git a/skills/testo-php-errors/SKILL.md b/skills/testo-php-errors/SKILL.md index 5e2db85b..d05ac1ef 100644 --- a/skills/testo-php-errors/SKILL.md +++ b/skills/testo-php-errors/SKILL.md @@ -43,8 +43,8 @@ PHP's own printing is suppressed: the `stderr` channel replaces it, so nothing a Captured errors live in the result attribute `Testo\ErrorHandler\CapturedErrors::class`, a list of `CapturedError` (`severity`, `message`, `file`, `line`, `handled`; `(string) $error` gives the PHP -wording). The `stderr` channel shows in the terminal under a `[stderr]` header and reaches every -reporter that renders messages. +wording). The `stderr` channel goes to the process STDERR as soon as the error is raised, at any +verbosity, and stays in the test's messages for every reporter that renders them. `failOnError: true` upgrades only a **passing** test: the first captured error becomes an `\ErrorException` failure. A test that already failed or errored keeps its own failure.