allow vendord
All checks were successful
Build, Push and Deploy / build-and-push (push) Successful in 3m3s
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 16s
Build, Push and Deploy / deploy-staging (push) Successful in 32s
Build, Push and Deploy / deploy-production (push) Has been skipped
Build, Push and Deploy / cleanup (push) Successful in 1s

This commit is contained in:
2026-03-30 14:54:57 +07:00
parent 66aed7c4e8
commit b5e3a778ce
21316 changed files with 2777892 additions and 13 deletions

View File

@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace NunoMaduro\Collision\Adapters\Phpunit;
use NunoMaduro\Collision\Adapters\Phpunit\Subscribers\EnsurePrinterIsRegisteredSubscriber;
use PHPUnit\Runner\Version;
if (class_exists(Version::class) && (int) Version::series() >= 10) {
EnsurePrinterIsRegisteredSubscriber::register();
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* This file is part of Collision.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NunoMaduro\Collision\Adapters\Phpunit;
use ReflectionObject;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\Output;
/**
* @internal
*/
final class ConfigureIO
{
/**
* Configures both given input and output with
* options from the environment.
*
* @throws \ReflectionException
*/
public static function of(InputInterface $input, Output $output): void
{
$application = new Application;
$reflector = new ReflectionObject($application);
$method = $reflector->getMethod('configureIO');
$method->setAccessible(true);
$method->invoke($application, $input, $output);
}
}

View File

@@ -0,0 +1,432 @@
<?php
declare(strict_types=1);
namespace NunoMaduro\Collision\Adapters\Phpunit\Printers;
use NunoMaduro\Collision\Adapters\Phpunit\ConfigureIO;
use NunoMaduro\Collision\Adapters\Phpunit\State;
use NunoMaduro\Collision\Adapters\Phpunit\Style;
use NunoMaduro\Collision\Adapters\Phpunit\Support\ResultReflection;
use NunoMaduro\Collision\Adapters\Phpunit\TestResult;
use NunoMaduro\Collision\Exceptions\ShouldNotHappen;
use NunoMaduro\Collision\Exceptions\TestOutcome;
use Pest\Result;
use PHPUnit\Event\Code\TestMethod;
use PHPUnit\Event\Code\ThrowableBuilder;
use PHPUnit\Event\Test\BeforeFirstTestMethodErrored;
use PHPUnit\Event\Test\ConsideredRisky;
use PHPUnit\Event\Test\DeprecationTriggered;
use PHPUnit\Event\Test\Errored;
use PHPUnit\Event\Test\Failed;
use PHPUnit\Event\Test\Finished;
use PHPUnit\Event\Test\MarkedIncomplete;
use PHPUnit\Event\Test\NoticeTriggered;
use PHPUnit\Event\Test\Passed;
use PHPUnit\Event\Test\PhpDeprecationTriggered;
use PHPUnit\Event\Test\PhpNoticeTriggered;
use PHPUnit\Event\Test\PhpunitDeprecationTriggered;
use PHPUnit\Event\Test\PhpunitErrorTriggered;
use PHPUnit\Event\Test\PhpunitWarningTriggered;
use PHPUnit\Event\Test\PhpWarningTriggered;
use PHPUnit\Event\Test\PreparationStarted;
use PHPUnit\Event\Test\PrintedUnexpectedOutput;
use PHPUnit\Event\Test\Skipped;
use PHPUnit\Event\Test\WarningTriggered;
use PHPUnit\Event\TestRunner\DeprecationTriggered as TestRunnerDeprecationTriggered;
use PHPUnit\Event\TestRunner\ExecutionFinished;
use PHPUnit\Event\TestRunner\ExecutionStarted;
use PHPUnit\Event\TestRunner\WarningTriggered as TestRunnerWarningTriggered;
use PHPUnit\Framework\IncompleteTestError;
use PHPUnit\Framework\SkippedWithMessageException;
use PHPUnit\TestRunner\TestResult\Facade;
use PHPUnit\TextUI\Configuration\Registry;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
/**
* @internal
*/
final class DefaultPrinter
{
/**
* The output instance.
*/
private ConsoleOutput $output;
/**
* The state instance.
*/
private State $state;
/**
* The style instance.
*/
private Style $style;
/**
* If the printer should be compact.
*/
private static bool $compact = false;
/**
* If the printer should profile.
*/
private static bool $profile = false;
/**
* When profiling, holds a list of slow tests.
*/
private array $profileSlowTests = [];
/**
* The test started at in microseconds.
*/
private float $testStartedAt = 0.0;
/**
* If the printer should be verbose.
*/
private static bool $verbose = false;
/**
* Creates a new Printer instance.
*/
public function __construct(bool $colors)
{
$this->output = new ConsoleOutput(OutputInterface::VERBOSITY_NORMAL, $colors);
ConfigureIO::of(new ArgvInput, $this->output);
self::$verbose = $this->output->isVerbose();
$this->style = new Style($this->output);
$this->state = new State;
}
/**
* If the printer instances should be compact.
*/
public static function compact(?bool $value = null): bool
{
if (! is_null($value)) {
self::$compact = $value;
}
return ! self::$verbose && self::$compact;
}
/**
* If the printer instances should profile.
*/
public static function profile(?bool $value = null): bool
{
if (! is_null($value)) {
self::$profile = $value;
}
return self::$profile;
}
/**
* Defines if the output should be decorated or not.
*/
public function setDecorated(bool $decorated): void
{
$this->output->setDecorated($decorated);
}
/**
* Listen to the runner execution started event.
*/
public function testPrintedUnexpectedOutput(PrintedUnexpectedOutput $printedUnexpectedOutput): void
{
$this->output->write($printedUnexpectedOutput->output());
}
/**
* Listen to the runner execution started event.
*/
public function testRunnerExecutionStarted(ExecutionStarted $executionStarted): void
{
// ..
}
/**
* Listen to the test finished event.
*/
public function testFinished(Finished $event): void
{
$duration = (hrtime(true) - $this->testStartedAt) / 1_000_000;
$test = $event->test();
if (! $test instanceof TestMethod) {
throw new ShouldNotHappen;
}
if (! $this->state->existsInTestCase($event->test())) {
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::PASS));
}
$result = $this->state->setDuration($test, $duration);
if (self::$profile) {
$this->profileSlowTests[$event->test()->id()] = $result;
// Sort the slow tests by time, and keep only 10 of them.
uasort($this->profileSlowTests, static function (TestResult $a, TestResult $b) {
return $b->duration <=> $a->duration;
});
$this->profileSlowTests = array_slice($this->profileSlowTests, 0, 10);
}
}
/**
* Listen to the test prepared event.
*/
public function testPreparationStarted(PreparationStarted $event): void
{
$this->testStartedAt = hrtime(true);
$test = $event->test();
if (! $test instanceof TestMethod) {
throw new ShouldNotHappen;
}
if ($this->state->testCaseHasChanged($test)) {
$this->style->writeCurrentTestCaseSummary($this->state);
$this->state->moveTo($test);
}
}
/**
* Listen to the test errored event.
*/
public function testBeforeFirstTestMethodErrored(BeforeFirstTestMethodErrored $event): void
{
$this->state->add(TestResult::fromBeforeFirstTestMethodErrored($event));
}
/**
* Listen to the test errored event.
*/
public function testErrored(Errored $event): void
{
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::FAIL, $event->throwable()));
}
/**
* Listen to the test failed event.
*/
public function testFailed(Failed $event): void
{
$throwable = $event->throwable();
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::FAIL, $throwable));
}
/**
* Listen to the test marked incomplete event.
*/
public function testMarkedIncomplete(MarkedIncomplete $event): void
{
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::INCOMPLETE, $event->throwable()));
}
/**
* Listen to the test considered risky event.
*/
public function testConsideredRisky(ConsideredRisky $event): void
{
$throwable = ThrowableBuilder::from(new IncompleteTestError($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::RISKY, $throwable));
}
/**
* Listen to the test runner deprecation triggered.
*/
public function testRunnerDeprecationTriggered(TestRunnerDeprecationTriggered $event): void
{
$this->style->writeWarning($event->message());
}
/**
* Listen to the test runner warning triggered.
*/
public function testRunnerWarningTriggered(TestRunnerWarningTriggered $event): void
{
if (! str_starts_with($event->message(), 'No tests found in class')) {
$this->style->writeWarning($event->message());
}
}
/**
* Listen to the test runner warning triggered.
*/
public function testPhpDeprecationTriggered(PhpDeprecationTriggered $event): void
{
$throwable = ThrowableBuilder::from(new TestOutcome($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::DEPRECATED, $throwable));
}
/**
* Listen to the test runner notice triggered.
*/
public function testPhpNoticeTriggered(PhpNoticeTriggered $event): void
{
$throwable = ThrowableBuilder::from(new TestOutcome($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::NOTICE, $throwable));
}
/**
* Listen to the test php warning triggered event.
*/
public function testPhpWarningTriggered(PhpWarningTriggered $event): void
{
$throwable = ThrowableBuilder::from(new TestOutcome($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::WARN, $throwable));
}
/**
* Listen to the test runner warning triggered.
*/
public function testPhpunitWarningTriggered(PhpunitWarningTriggered $event): void
{
$throwable = ThrowableBuilder::from(new TestOutcome($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::WARN, $throwable));
}
/**
* Listen to the test deprecation triggered event.
*/
public function testDeprecationTriggered(DeprecationTriggered $event): void
{
$throwable = ThrowableBuilder::from(new TestOutcome($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::DEPRECATED, $throwable));
}
/**
* Listen to the test phpunit deprecation triggered event.
*/
public function testPhpunitDeprecationTriggered(PhpunitDeprecationTriggered $event): void
{
$throwable = ThrowableBuilder::from(new TestOutcome($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::DEPRECATED, $throwable));
}
/**
* Listen to the test phpunit error triggered event.
*/
public function testPhpunitErrorTriggered(PhpunitErrorTriggered $event): void
{
$throwable = ThrowableBuilder::from(new TestOutcome($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::FAIL, $throwable));
}
/**
* Listen to the test warning triggered event.
*/
public function testNoticeTriggered(NoticeTriggered $event): void
{
$throwable = ThrowableBuilder::from(new TestOutcome($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::NOTICE, $throwable));
}
/**
* Listen to the test warning triggered event.
*/
public function testWarningTriggered(WarningTriggered $event): void
{
$throwable = ThrowableBuilder::from(new TestOutcome($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::WARN, $throwable));
}
/**
* Listen to the test skipped event.
*/
public function testSkipped(Skipped $event): void
{
if ($event->message() === '__TODO__') {
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::TODO));
return;
}
$throwable = ThrowableBuilder::from(new SkippedWithMessageException($event->message()));
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::SKIPPED, $throwable));
}
/**
* Listen to the test finished event.
*/
public function testPassed(Passed $event): void
{
if (! $this->state->existsInTestCase($event->test())) {
$this->state->add(TestResult::fromTestCase($event->test(), TestResult::PASS));
}
}
/**
* Listen to the runner execution finished event.
*/
public function testRunnerExecutionFinished(ExecutionFinished $event): void
{
$result = Facade::result();
if (ResultReflection::numberOfTests(Facade::result()) === 0) {
$this->output->writeln([
'',
' <fg=white;options=bold;bg=blue> INFO </> No tests found.',
'',
]);
return;
}
$this->style->writeCurrentTestCaseSummary($this->state);
if (self::$compact) {
$this->output->writeln(['']);
}
if (class_exists(Result::class)) {
$failed = Result::failed(Registry::get(), Facade::result());
} else {
$failed = ! Facade::result()->wasSuccessful();
}
$this->style->writeErrorsSummary($this->state);
$this->style->writeRecap($this->state, $event->telemetryInfo(), $result);
if (! $failed && count($this->profileSlowTests) > 0) {
$this->style->writeSlowTests($this->profileSlowTests, $event->telemetryInfo());
}
}
/**
* Reports the given throwable.
*/
public function report(Throwable $throwable): void
{
$this->style->writeError(ThrowableBuilder::from($throwable));
}
}

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace NunoMaduro\Collision\Adapters\Phpunit\Printers;
use Throwable;
/**
* @internal
*
* @mixin DefaultPrinter
*/
final class ReportablePrinter
{
/**
* Creates a new Printer instance.
*/
public function __construct(private readonly DefaultPrinter $printer)
{
// ..
}
/**
* Calls the original method, but reports any errors to the reporter.
*/
public function __call(string $name, array $arguments): mixed
{
try {
return $this->printer->$name(...$arguments);
} catch (Throwable $throwable) {
$this->printer->report($throwable);
}
exit(1);
}
}

View File

@@ -0,0 +1,267 @@
<?php
declare(strict_types=1);
namespace NunoMaduro\Collision\Adapters\Phpunit;
use NunoMaduro\Collision\Contracts\Adapters\Phpunit\HasPrintableTestCaseName;
use PHPUnit\Event\Code\Test;
use PHPUnit\Event\Code\TestMethod;
/**
* @internal
*/
final class State
{
/**
* The complete test suite tests.
*
* @var array<string, TestResult>
*/
public array $suiteTests = [];
/**
* The current test case class.
*/
public ?string $testCaseName;
/**
* The current test case tests.
*
* @var array<string, TestResult>
*/
public array $testCaseTests = [];
/**
* The current test case tests.
*
* @var array<string, TestResult>
*/
public array $toBePrintedCaseTests = [];
/**
* Header printed.
*/
public bool $headerPrinted = false;
/**
* The state constructor.
*/
public function __construct()
{
$this->testCaseName = '';
}
/**
* Checks if the given test already contains a result.
*/
public function existsInTestCase(Test $test): bool
{
return isset($this->testCaseTests[$test->id()]);
}
/**
* Adds the given test to the State.
*/
public function add(TestResult $test): void
{
$this->testCaseName = $test->testCaseName;
$levels = array_flip([
TestResult::PASS,
TestResult::RUNS,
TestResult::TODO,
TestResult::SKIPPED,
TestResult::WARN,
TestResult::NOTICE,
TestResult::DEPRECATED,
TestResult::RISKY,
TestResult::INCOMPLETE,
TestResult::FAIL,
]);
if (isset($this->testCaseTests[$test->id])) {
$existing = $this->testCaseTests[$test->id];
if ($levels[$existing->type] >= $levels[$test->type]) {
return;
}
}
$this->testCaseTests[$test->id] = $test;
$this->toBePrintedCaseTests[$test->id] = $test;
$this->suiteTests[$test->id] = $test;
}
/**
* Sets the duration of the given test, and returns the test result.
*/
public function setDuration(Test $test, float $duration): TestResult
{
$result = $this->testCaseTests[$test->id()];
$result->setDuration($duration);
return $result;
}
/**
* Gets the test case title.
*/
public function getTestCaseTitle(): string
{
foreach ($this->testCaseTests as $test) {
if ($test->type === TestResult::FAIL) {
return 'FAIL';
}
}
foreach ($this->testCaseTests as $test) {
if ($test->type !== TestResult::PASS && $test->type !== TestResult::TODO && $test->type !== TestResult::DEPRECATED && $test->type !== TestResult::NOTICE) {
return 'WARN';
}
}
foreach ($this->testCaseTests as $test) {
if ($test->type === TestResult::NOTICE) {
return 'NOTI';
}
}
foreach ($this->testCaseTests as $test) {
if ($test->type === TestResult::DEPRECATED) {
return 'DEPR';
}
}
if ($this->todosCount() > 0 && (count($this->testCaseTests) === $this->todosCount())) {
return 'TODO';
}
return 'PASS';
}
/**
* Gets the number of tests that are todos.
*/
public function todosCount(): int
{
return count(array_values(array_filter($this->testCaseTests, function (TestResult $test): bool {
return $test->type === TestResult::TODO;
})));
}
/**
* Gets the test case title color.
*/
public function getTestCaseFontColor(): string
{
if ($this->getTestCaseTitleColor() === 'blue') {
return 'white';
}
return $this->getTestCaseTitle() === 'FAIL' ? 'default' : 'black';
}
/**
* Gets the test case title color.
*/
public function getTestCaseTitleColor(): string
{
foreach ($this->testCaseTests as $test) {
if ($test->type === TestResult::FAIL) {
return 'red';
}
}
foreach ($this->testCaseTests as $test) {
if ($test->type !== TestResult::PASS && $test->type !== TestResult::TODO && $test->type !== TestResult::DEPRECATED) {
return 'yellow';
}
}
foreach ($this->testCaseTests as $test) {
if ($test->type === TestResult::DEPRECATED) {
return 'yellow';
}
}
foreach ($this->testCaseTests as $test) {
if ($test->type === TestResult::TODO) {
return 'blue';
}
}
return 'green';
}
/**
* Returns the number of tests on the current test case.
*/
public function testCaseTestsCount(): int
{
return count($this->testCaseTests);
}
/**
* Returns the number of tests on the complete test suite.
*/
public function testSuiteTestsCount(): int
{
return count($this->suiteTests);
}
/**
* Checks if the given test case is different from the current one.
*/
public function testCaseHasChanged(TestMethod $test): bool
{
return self::getPrintableTestCaseName($test) !== $this->testCaseName;
}
/**
* Moves the an new test case.
*/
public function moveTo(TestMethod $test): void
{
$this->testCaseName = self::getPrintableTestCaseName($test);
$this->testCaseTests = [];
$this->headerPrinted = false;
}
/**
* Foreach test in the test case.
*/
public function eachTestCaseTests(callable $callback): void
{
foreach ($this->toBePrintedCaseTests as $test) {
$callback($test);
}
$this->toBePrintedCaseTests = [];
}
public function countTestsInTestSuiteBy(string $type): int
{
return count(array_filter($this->suiteTests, function (TestResult $testResult) use ($type) {
return $testResult->type === $type;
}));
}
/**
* Returns the printable test case name from the given `TestCase`.
*/
public static function getPrintableTestCaseName(TestMethod $test): string
{
$className = explode('::', $test->id())[0];
if (is_subclass_of($className, HasPrintableTestCaseName::class)) {
return $className::getPrintableTestCaseName();
}
return $className;
}
}

View File

@@ -0,0 +1,555 @@
<?php
declare(strict_types=1);
namespace NunoMaduro\Collision\Adapters\Phpunit;
use Closure;
use NunoMaduro\Collision\Adapters\Phpunit\Printers\DefaultPrinter;
use NunoMaduro\Collision\Adapters\Phpunit\Support\ResultReflection;
use NunoMaduro\Collision\Exceptions\ShouldNotHappen;
use NunoMaduro\Collision\Exceptions\TestException;
use NunoMaduro\Collision\Exceptions\TestOutcome;
use NunoMaduro\Collision\Writer;
use Pest\Expectation;
use PHPUnit\Event\Code\Throwable;
use PHPUnit\Event\Telemetry\Info;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\IncompleteTestError;
use PHPUnit\Framework\SkippedWithMessageException;
use PHPUnit\TestRunner\TestResult\TestResult as PHPUnitTestResult;
use PHPUnit\TextUI\Configuration\Registry;
use ReflectionClass;
use ReflectionFunction;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Termwind\Terminal;
use Whoops\Exception\Frame;
use Whoops\Exception\Inspector;
use function Termwind\render;
use function Termwind\renderUsing;
use function Termwind\terminal;
/**
* @internal
*/
final class Style
{
private int $compactProcessed = 0;
private int $compactSymbolsPerLine = 0;
private readonly Terminal $terminal;
private readonly ConsoleOutput $output;
/**
* @var string[]
*/
private const TYPES = [TestResult::DEPRECATED, TestResult::FAIL, TestResult::WARN, TestResult::RISKY, TestResult::INCOMPLETE, TestResult::NOTICE, TestResult::TODO, TestResult::SKIPPED, TestResult::PASS];
/**
* Style constructor.
*/
public function __construct(ConsoleOutputInterface $output)
{
if (! $output instanceof ConsoleOutput) {
throw new ShouldNotHappen;
}
$this->terminal = terminal();
$this->output = $output;
$this->compactSymbolsPerLine = $this->terminal->width() - 4;
}
/**
* Prints the content similar too:.
*
* ```
* WARN Your XML configuration validates against a deprecated schema...
* ```
*/
public function writeWarning(string $message): void
{
$this->output->writeln(['', ' <fg=black;bg=yellow;options=bold> WARN </> '.$message]);
}
/**
* Prints the content similar too:.
*
* ```
* WARN Your XML configuration validates against a deprecated schema...
* ```
*/
public function writeThrowable(\Throwable $throwable): void
{
$this->output->writeln(['', ' <fg=white;bg=red;options=bold> ERROR </> '.$throwable->getMessage()]);
}
/**
* Prints the content similar too:.
*
* ```
* PASS Unit\ExampleTest
* basic test
* ```
*/
public function writeCurrentTestCaseSummary(State $state): void
{
if ($state->testCaseTestsCount() === 0 || is_null($state->testCaseName)) {
return;
}
if (! $state->headerPrinted && ! DefaultPrinter::compact()) {
$this->output->writeln($this->titleLineFrom(
$state->getTestCaseFontColor(),
$state->getTestCaseTitleColor(),
$state->getTestCaseTitle(),
$state->testCaseName,
$state->todosCount(),
));
$state->headerPrinted = true;
}
$state->eachTestCaseTests(function (TestResult $testResult): void {
if ($testResult->description !== '') {
if (DefaultPrinter::compact()) {
$this->writeCompactDescriptionLine($testResult);
} else {
$this->writeDescriptionLine($testResult);
}
}
});
}
/**
* Prints the content similar too:.
*
* ```
* PASS Unit\ExampleTest
* basic test
* ```
*/
public function writeErrorsSummary(State $state): void
{
$configuration = Registry::get();
$failTypes = [
TestResult::FAIL,
];
if ($configuration->displayDetailsOnTestsThatTriggerNotices()) {
$failTypes[] = TestResult::NOTICE;
}
if ($configuration->displayDetailsOnTestsThatTriggerDeprecations()) {
$failTypes[] = TestResult::DEPRECATED;
}
if ($configuration->failOnWarning() || $configuration->displayDetailsOnTestsThatTriggerWarnings()) {
$failTypes[] = TestResult::WARN;
}
if ($configuration->failOnRisky()) {
$failTypes[] = TestResult::RISKY;
}
if ($configuration->failOnIncomplete() || $configuration->displayDetailsOnIncompleteTests()) {
$failTypes[] = TestResult::INCOMPLETE;
}
if ($configuration->failOnSkipped() || $configuration->displayDetailsOnSkippedTests()) {
$failTypes[] = TestResult::SKIPPED;
}
$failTypes = array_unique($failTypes);
$errors = array_values(array_filter($state->suiteTests, fn (TestResult $testResult) => in_array(
$testResult->type,
$failTypes,
true
)));
array_map(function (TestResult $testResult): void {
if (! $testResult->throwable instanceof Throwable) {
throw new ShouldNotHappen;
}
renderUsing($this->output);
render(<<<'HTML'
<div class="mx-2 text-red">
<hr/>
</div>
HTML
);
$testCaseName = $testResult->testCaseName;
$description = $testResult->description;
/** @var class-string $throwableClassName */
$throwableClassName = $testResult->throwable->className();
$throwableClassName = ! in_array($throwableClassName, [
ExpectationFailedException::class,
IncompleteTestError::class,
SkippedWithMessageException::class,
TestOutcome::class,
], true) ? sprintf('<span class="px-1 bg-red font-bold">%s</span>', (new ReflectionClass($throwableClassName))->getShortName())
: '';
$truncateClasses = $this->output->isVerbose() ? '' : 'flex-1 truncate';
renderUsing($this->output);
render(sprintf(<<<'HTML'
<div class="flex justify-between mx-2">
<span class="%s">
<span class="px-1 bg-%s %s font-bold uppercase">%s</span> <span class="font-bold">%s</span><span class="text-gray mx-1">></span><span>%s</span>
</span>
<span class="ml-1">
%s
</span>
</div>
HTML, $truncateClasses, $testResult->color === 'yellow' ? 'yellow-400' : $testResult->color, $testResult->color === 'yellow' ? 'text-black' : '', $testResult->type, $testCaseName, $description, $throwableClassName));
$this->writeError($testResult->throwable);
}, $errors);
}
/**
* Writes the final recap.
*/
public function writeRecap(State $state, Info $telemetry, PHPUnitTestResult $result): void
{
$tests = [];
foreach (self::TYPES as $type) {
if (($countTests = $state->countTestsInTestSuiteBy($type)) !== 0) {
$color = TestResult::makeColor($type);
if ($type === TestResult::WARN && $countTests < 2) {
$type = 'warning';
}
if ($type === TestResult::NOTICE && $countTests > 1) {
$type = 'notices';
}
if ($type === TestResult::TODO && $countTests > 1) {
$type = 'todos';
}
$tests[] = "<fg=$color;options=bold>$countTests $type</>";
}
}
$pending = ResultReflection::numberOfTests($result) - $result->numberOfTestsRun();
if ($pending > 0) {
$tests[] = "\e[2m$pending pending\e[22m";
}
$timeElapsed = number_format($telemetry->durationSinceStart()->asFloat(), 2, '.', '');
$this->output->writeln(['']);
if (! empty($tests)) {
$this->output->writeln([
sprintf(
' <fg=gray>Tests:</> <fg=default>%s</><fg=gray> (%s assertions)</>',
implode('<fg=gray>,</> ', $tests),
$result->numberOfAssertions()
),
]);
}
$this->output->writeln([
sprintf(
' <fg=gray>Duration:</> <fg=default>%ss</>',
$timeElapsed
),
]);
$this->output->writeln('');
}
/**
* @param array<int, TestResult> $slowTests
*/
public function writeSlowTests(array $slowTests, Info $telemetry): void
{
$this->output->writeln(' <fg=gray>Top 10 slowest tests:</>');
$timeElapsed = $telemetry->durationSinceStart()->asFloat();
foreach ($slowTests as $testResult) {
$seconds = number_format($testResult->duration / 1000, 2, '.', '');
$color = ($testResult->duration / 1000) > $timeElapsed * 0.25 ? 'red' : ($testResult->duration > $timeElapsed * 0.1 ? 'yellow' : 'gray');
renderUsing($this->output);
render(sprintf(<<<'HTML'
<div class="flex justify-between space-x-1 mx-2">
<span class="flex-1">
<span class="font-bold">%s</span><span class="text-gray mx-1">></span><span class="text-gray">%s</span>
</span>
<span class="ml-1 font-bold text-%s">
%ss
</span>
</div>
HTML, $testResult->testCaseName, $testResult->description, $color, $seconds));
}
$timeElapsedInSlowTests = array_sum(array_map(fn (TestResult $testResult) => $testResult->duration / 1000, $slowTests));
$timeElapsedAsString = number_format($timeElapsed, 2, '.', '');
$percentageInSlowTestsAsString = number_format($timeElapsedInSlowTests * 100 / $timeElapsed, 2, '.', '');
$timeElapsedInSlowTestsAsString = number_format($timeElapsedInSlowTests, 2, '.', '');
renderUsing($this->output);
render(sprintf(<<<'HTML'
<div class="mx-2 mb-1 flex">
<div class="text-gray">
<hr/>
</div>
<div class="flex space-x-1 justify-between">
<span>
</span>
<span>
<span class="text-gray">(%s%% of %ss)</span>
<span class="ml-1 font-bold">%ss</span>
</span>
</div>
</div>
HTML, $percentageInSlowTestsAsString, $timeElapsedAsString, $timeElapsedInSlowTestsAsString));
}
/**
* Displays the error using Collision's writer and terminates with exit code === 1.
*/
public function writeError(Throwable $throwable): void
{
$writer = (new Writer)->setOutput($this->output);
$throwable = new TestException($throwable, $this->output->isVerbose());
$writer->showTitle(false);
$writer->ignoreFilesIn([
'/vendor\/nunomaduro\/collision/',
'/vendor\/bin\/pest/',
'/bin\/pest/',
'/vendor\/pestphp\/pest/',
'/vendor\/pestphp\/pest-plugin-arch/',
'/vendor\/phpspec\/prophecy-phpunit/',
'/vendor\/phpspec\/prophecy/',
'/vendor\/phpunit\/phpunit\/src/',
'/vendor\/mockery\/mockery/',
'/vendor\/laravel\/dusk/',
'/Illuminate\/Testing/',
'/Illuminate\/Foundation\/Testing/',
'/Illuminate\/Foundation\/Bootstrap\/HandleExceptions/',
'/vendor\/symfony\/framework-bundle\/Test/',
'/vendor\/symfony\/phpunit-bridge/',
'/vendor\/symfony\/dom-crawler/',
'/vendor\/symfony\/browser-kit/',
'/vendor\/symfony\/css-selector/',
'/vendor\/bin\/.phpunit/',
'/bin\/.phpunit/',
'/vendor\/bin\/simple-phpunit/',
'/bin\/phpunit/',
'/vendor\/coduo\/php-matcher\/src\/PHPUnit/',
'/vendor\/sulu\/sulu\/src\/Sulu\/Bundle\/TestBundle\/Testing/',
'/vendor\/webmozart\/assert/',
$this->ignorePestPipes(...),
$this->ignorePestExtends(...),
$this->ignorePestInterceptors(...),
]);
/** @var \Throwable $throwable */
$inspector = new Inspector($throwable);
$writer->write($inspector);
}
/**
* Returns the title contents.
*/
private function titleLineFrom(string $fg, string $bg, string $title, string $testCaseName, int $todos): string
{
return sprintf(
"\n <fg=%s;bg=%s;options=bold> %s </><fg=default> %s</>%s",
$fg,
$bg,
$title,
$testCaseName,
$todos > 0 ? sprintf('<fg=gray> - %s todo%s</>', $todos, $todos > 1 ? 's' : '') : '',
);
}
/**
* Writes a description line.
*/
private function writeCompactDescriptionLine(TestResult $result): void
{
$symbolsOnCurrentLine = $this->compactProcessed % $this->compactSymbolsPerLine;
if ($symbolsOnCurrentLine >= $this->terminal->width() - 4) {
$symbolsOnCurrentLine = 0;
}
if ($symbolsOnCurrentLine === 0) {
$this->output->writeln('');
$this->output->write(' ');
}
$this->output->write(sprintf('<fg=%s;options=bold>%s</>', $result->compactColor, $result->compactIcon));
$this->compactProcessed++;
}
/**
* Writes a description line.
*/
private function writeDescriptionLine(TestResult $result): void
{
if (! empty($warning = $result->warning)) {
if (! str_contains($warning, "\n")) {
$warning = sprintf(
' → %s',
$warning
);
} else {
$warningLines = explode("\n", $warning);
$warning = '';
foreach ($warningLines as $w) {
$warning .= sprintf(
"\n <fg=yellow;options=bold>⇂ %s</>",
trim($w)
);
}
}
}
$seconds = '';
if (($result->duration / 1000) > 0.0) {
$seconds = number_format($result->duration / 1000, 2, '.', '');
$seconds = $seconds !== '0.00' ? sprintf('<span class="text-gray mr-2">%ss</span>', $seconds) : '';
}
if (isset($_SERVER['REBUILD_SNAPSHOTS']) || (isset($_SERVER['COLLISION_IGNORE_DURATION']) && $_SERVER['COLLISION_IGNORE_DURATION'] === 'true')) {
$seconds = '';
}
$truncateClasses = $this->output->isVerbose() ? '' : 'flex-1 truncate';
if ($warning !== '') {
$warning = sprintf('<span class="ml-1 text-yellow">%s</span>', $warning);
if (! empty($result->warningSource)) {
$warning .= ' // '.$result->warningSource;
}
}
$description = preg_replace('/`([^`]+)`/', '<span class="text-white">$1</span>', $result->description);
renderUsing($this->output);
render(sprintf(<<<'HTML'
<div class="%s ml-2">
<span class="%s text-gray">
<span class="text-%s font-bold">%s</span><span class="ml-1 text-gray">%s</span>%s
</span>%s
</div>
HTML, $seconds === '' ? '' : 'flex space-x-1 justify-between', $truncateClasses, $result->color, $result->icon, $description, $warning, $seconds));
}
/**
* @param Frame $frame
*/
private function ignorePestPipes($frame): bool
{
if (class_exists(Expectation::class)) {
$reflection = new ReflectionClass(Expectation::class);
/** @var array<string, array<Closure(Closure, mixed ...$arguments): void>> $expectationPipes */
$expectationPipes = $reflection->getStaticPropertyValue('pipes', []);
foreach ($expectationPipes as $pipes) {
foreach ($pipes as $pipeClosure) {
if ($this->isFrameInClosure($frame, $pipeClosure)) {
return true;
}
}
}
}
return false;
}
/**
* @param Frame $frame
*/
private function ignorePestExtends($frame): bool
{
if (class_exists(Expectation::class)) {
$reflection = new ReflectionClass(Expectation::class);
/** @var array<string, Closure> $extends */
$extends = $reflection->getStaticPropertyValue('extends', []);
foreach ($extends as $extendClosure) {
if ($this->isFrameInClosure($frame, $extendClosure)) {
return true;
}
}
}
return false;
}
/**
* @param Frame $frame
*/
private function ignorePestInterceptors($frame): bool
{
if (class_exists(Expectation::class)) {
$reflection = new ReflectionClass(Expectation::class);
/** @var array<string, array<Closure(Closure, mixed ...$arguments): void>> $expectationInterceptors */
$expectationInterceptors = $reflection->getStaticPropertyValue('interceptors', []);
foreach ($expectationInterceptors as $pipes) {
foreach ($pipes as $pipeClosure) {
if ($this->isFrameInClosure($frame, $pipeClosure)) {
return true;
}
}
}
}
return false;
}
/**
* @param Frame $frame
*/
private function isFrameInClosure($frame, Closure $closure): bool
{
$reflection = new ReflectionFunction($closure);
$sanitizedPath = (string) str_replace('\\', '/', (string) $frame->getFile());
/** @phpstan-ignore-next-line */
$sanitizedClosurePath = (string) str_replace('\\', '/', $reflection->getFileName());
if ($sanitizedPath === $sanitizedClosurePath) {
if ($reflection->getStartLine() <= $frame->getLine() && $frame->getLine() <= $reflection->getEndLine()) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,310 @@
<?php
declare(strict_types=1);
namespace NunoMaduro\Collision\Adapters\Phpunit\Subscribers;
use NunoMaduro\Collision\Adapters\Phpunit\Printers\DefaultPrinter;
use NunoMaduro\Collision\Adapters\Phpunit\Printers\ReportablePrinter;
use PHPUnit\Event\Application\Started;
use PHPUnit\Event\Application\StartedSubscriber;
use PHPUnit\Event\Facade;
use PHPUnit\Event\Test\BeforeFirstTestMethodErrored;
use PHPUnit\Event\Test\BeforeFirstTestMethodErroredSubscriber;
use PHPUnit\Event\Test\ConsideredRisky;
use PHPUnit\Event\Test\ConsideredRiskySubscriber;
use PHPUnit\Event\Test\DeprecationTriggered;
use PHPUnit\Event\Test\DeprecationTriggeredSubscriber;
use PHPUnit\Event\Test\Errored;
use PHPUnit\Event\Test\ErroredSubscriber;
use PHPUnit\Event\Test\Failed;
use PHPUnit\Event\Test\FailedSubscriber;
use PHPUnit\Event\Test\Finished;
use PHPUnit\Event\Test\FinishedSubscriber;
use PHPUnit\Event\Test\MarkedIncomplete;
use PHPUnit\Event\Test\MarkedIncompleteSubscriber;
use PHPUnit\Event\Test\NoticeTriggered;
use PHPUnit\Event\Test\NoticeTriggeredSubscriber;
use PHPUnit\Event\Test\Passed;
use PHPUnit\Event\Test\PassedSubscriber;
use PHPUnit\Event\Test\PhpDeprecationTriggered;
use PHPUnit\Event\Test\PhpDeprecationTriggeredSubscriber;
use PHPUnit\Event\Test\PhpNoticeTriggered;
use PHPUnit\Event\Test\PhpNoticeTriggeredSubscriber;
use PHPUnit\Event\Test\PhpunitDeprecationTriggered;
use PHPUnit\Event\Test\PhpunitDeprecationTriggeredSubscriber;
use PHPUnit\Event\Test\PhpunitErrorTriggered;
use PHPUnit\Event\Test\PhpunitErrorTriggeredSubscriber;
use PHPUnit\Event\Test\PhpunitWarningTriggered;
use PHPUnit\Event\Test\PhpunitWarningTriggeredSubscriber;
use PHPUnit\Event\Test\PhpWarningTriggered;
use PHPUnit\Event\Test\PhpWarningTriggeredSubscriber;
use PHPUnit\Event\Test\PreparationStarted;
use PHPUnit\Event\Test\PreparationStartedSubscriber;
use PHPUnit\Event\Test\PrintedUnexpectedOutput;
use PHPUnit\Event\Test\PrintedUnexpectedOutputSubscriber;
use PHPUnit\Event\Test\Skipped;
use PHPUnit\Event\Test\SkippedSubscriber;
use PHPUnit\Event\Test\WarningTriggered;
use PHPUnit\Event\Test\WarningTriggeredSubscriber;
use PHPUnit\Event\TestRunner\Configured;
use PHPUnit\Event\TestRunner\ConfiguredSubscriber;
use PHPUnit\Event\TestRunner\DeprecationTriggered as TestRunnerDeprecationTriggered;
use PHPUnit\Event\TestRunner\DeprecationTriggeredSubscriber as TestRunnerDeprecationTriggeredSubscriber;
use PHPUnit\Event\TestRunner\ExecutionFinished;
use PHPUnit\Event\TestRunner\ExecutionFinishedSubscriber;
use PHPUnit\Event\TestRunner\ExecutionStarted;
use PHPUnit\Event\TestRunner\ExecutionStartedSubscriber;
use PHPUnit\Event\TestRunner\WarningTriggered as TestRunnerWarningTriggered;
use PHPUnit\Event\TestRunner\WarningTriggeredSubscriber as TestRunnerWarningTriggeredSubscriber;
use PHPUnit\Runner\Version;
if (class_exists(Version::class) && (int) Version::series() >= 10) {
/**
* @internal
*/
final class EnsurePrinterIsRegisteredSubscriber implements StartedSubscriber
{
/**
* If this subscriber has been registered on PHPUnit's facade.
*/
private static bool $registered = false;
/**
* Runs the subscriber.
*/
public function notify(Started $event): void
{
$printer = new ReportablePrinter(new DefaultPrinter(true));
if (isset($_SERVER['COLLISION_PRINTER_COMPACT'])) {
DefaultPrinter::compact(true);
}
if (isset($_SERVER['COLLISION_PRINTER_PROFILE'])) {
DefaultPrinter::profile(true);
}
$subscribers = [
// Configured
new class($printer) extends Subscriber implements ConfiguredSubscriber
{
public function notify(Configured $event): void
{
$this->printer()->setDecorated(
$event->configuration()->colors()
);
}
},
// Test
new class($printer) extends Subscriber implements PrintedUnexpectedOutputSubscriber
{
public function notify(PrintedUnexpectedOutput $event): void
{
$this->printer()->testPrintedUnexpectedOutput($event);
}
},
// Test Runner
new class($printer) extends Subscriber implements ExecutionStartedSubscriber
{
public function notify(ExecutionStarted $event): void
{
$this->printer()->testRunnerExecutionStarted($event);
}
},
new class($printer) extends Subscriber implements ExecutionFinishedSubscriber
{
public function notify(ExecutionFinished $event): void
{
$this->printer()->testRunnerExecutionFinished($event);
}
},
// Test > Hook Methods
new class($printer) extends Subscriber implements BeforeFirstTestMethodErroredSubscriber
{
public function notify(BeforeFirstTestMethodErrored $event): void
{
$this->printer()->testBeforeFirstTestMethodErrored($event);
}
},
// Test > Lifecycle ...
new class($printer) extends Subscriber implements FinishedSubscriber
{
public function notify(Finished $event): void
{
$this->printer()->testFinished($event);
}
},
new class($printer) extends Subscriber implements PreparationStartedSubscriber
{
public function notify(PreparationStarted $event): void
{
$this->printer()->testPreparationStarted($event);
}
},
// Test > Issues ...
new class($printer) extends Subscriber implements ConsideredRiskySubscriber
{
public function notify(ConsideredRisky $event): void
{
$this->printer()->testConsideredRisky($event);
}
},
new class($printer) extends Subscriber implements DeprecationTriggeredSubscriber
{
public function notify(DeprecationTriggered $event): void
{
$this->printer()->testDeprecationTriggered($event);
}
},
new class($printer) extends Subscriber implements TestRunnerDeprecationTriggeredSubscriber
{
public function notify(TestRunnerDeprecationTriggered $event): void
{
$this->printer()->testRunnerDeprecationTriggered($event);
}
},
new class($printer) extends Subscriber implements TestRunnerWarningTriggeredSubscriber
{
public function notify(TestRunnerWarningTriggered $event): void
{
$this->printer()->testRunnerWarningTriggered($event);
}
},
new class($printer) extends Subscriber implements PhpDeprecationTriggeredSubscriber
{
public function notify(PhpDeprecationTriggered $event): void
{
$this->printer()->testPhpDeprecationTriggered($event);
}
},
new class($printer) extends Subscriber implements PhpunitDeprecationTriggeredSubscriber
{
public function notify(PhpunitDeprecationTriggered $event): void
{
$this->printer()->testPhpunitDeprecationTriggered($event);
}
},
new class($printer) extends Subscriber implements PhpNoticeTriggeredSubscriber
{
public function notify(PhpNoticeTriggered $event): void
{
$this->printer()->testPhpNoticeTriggered($event);
}
},
new class($printer) extends Subscriber implements PhpWarningTriggeredSubscriber
{
public function notify(PhpWarningTriggered $event): void
{
$this->printer()->testPhpWarningTriggered($event);
}
},
new class($printer) extends Subscriber implements PhpunitWarningTriggeredSubscriber
{
public function notify(PhpunitWarningTriggered $event): void
{
$this->printer()->testPhpunitWarningTriggered($event);
}
},
new class($printer) extends Subscriber implements PhpunitErrorTriggeredSubscriber
{
public function notify(PhpunitErrorTriggered $event): void
{
$this->printer()->testPhpunitErrorTriggered($event);
}
},
// Test > Outcome ...
new class($printer) extends Subscriber implements ErroredSubscriber
{
public function notify(Errored $event): void
{
$this->printer()->testErrored($event);
}
},
new class($printer) extends Subscriber implements FailedSubscriber
{
public function notify(Failed $event): void
{
$this->printer()->testFailed($event);
}
},
new class($printer) extends Subscriber implements MarkedIncompleteSubscriber
{
public function notify(MarkedIncomplete $event): void
{
$this->printer()->testMarkedIncomplete($event);
}
},
new class($printer) extends Subscriber implements NoticeTriggeredSubscriber
{
public function notify(NoticeTriggered $event): void
{
$this->printer()->testNoticeTriggered($event);
}
},
new class($printer) extends Subscriber implements PassedSubscriber
{
public function notify(Passed $event): void
{
$this->printer()->testPassed($event);
}
},
new class($printer) extends Subscriber implements SkippedSubscriber
{
public function notify(Skipped $event): void
{
$this->printer()->testSkipped($event);
}
},
new class($printer) extends Subscriber implements WarningTriggeredSubscriber
{
public function notify(WarningTriggered $event): void
{
$this->printer()->testWarningTriggered($event);
}
},
];
Facade::instance()->registerSubscribers(...$subscribers);
}
/**
* Registers the subscriber on PHPUnit's facade.
*/
public static function register(): void
{
$shouldRegister = self::$registered === false
&& isset($_SERVER['COLLISION_PRINTER']);
if ($shouldRegister) {
self::$registered = true;
Facade::instance()->registerSubscriber(new self);
}
}
}
}

View File

@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
/**
* This file is part of Collision.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NunoMaduro\Collision\Adapters\Phpunit\Subscribers;
use NunoMaduro\Collision\Adapters\Phpunit\Printers\ReportablePrinter;
/**
* @internal
*/
abstract class Subscriber
{
/**
* The printer instance.
*/
private ReportablePrinter $printer;
/**
* Creates a new subscriber.
*/
public function __construct(ReportablePrinter $printer)
{
$this->printer = $printer;
}
/**
* Returns the printer instance.
*/
protected function printer(): ReportablePrinter
{
return $this->printer;
}
}

View File

@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace NunoMaduro\Collision\Adapters\Phpunit\Support;
use PHPUnit\TestRunner\TestResult\TestResult;
/**
* @internal
*/
final class ResultReflection
{
/**
* The number of processed tests.
*/
public static function numberOfTests(TestResult $testResult): int
{
return (fn () => $this->numberOfTests)->call($testResult);
}
}

View File

@@ -0,0 +1,324 @@
<?php
declare(strict_types=1);
namespace NunoMaduro\Collision\Adapters\Phpunit;
use NunoMaduro\Collision\Contracts\Adapters\Phpunit\HasPrintableTestCaseName;
use NunoMaduro\Collision\Exceptions\ShouldNotHappen;
use PHPUnit\Event\Code\Test;
use PHPUnit\Event\Code\TestMethod;
use PHPUnit\Event\Code\Throwable;
use PHPUnit\Event\Test\BeforeFirstTestMethodErrored;
/**
* @internal
*/
final class TestResult
{
public const FAIL = 'failed';
public const SKIPPED = 'skipped';
public const INCOMPLETE = 'incomplete';
public const TODO = 'todo';
public const RISKY = 'risky';
public const DEPRECATED = 'deprecated';
public const NOTICE = 'notice';
public const WARN = 'warnings';
public const RUNS = 'pending';
public const PASS = 'passed';
public string $id;
public string $testCaseName;
public string $description;
public string $type;
public string $compactIcon;
public string $icon;
public string $compactColor;
public string $color;
public float $duration;
public ?Throwable $throwable;
public string $warning = '';
public string $warningSource = '';
/**
* Creates a new TestResult instance.
*/
private function __construct(string $id, string $testCaseName, string $description, string $type, string $icon, string $compactIcon, string $color, string $compactColor, ?Throwable $throwable = null)
{
$this->id = $id;
$this->testCaseName = $testCaseName;
$this->description = $description;
$this->type = $type;
$this->icon = $icon;
$this->compactIcon = $compactIcon;
$this->color = $color;
$this->compactColor = $compactColor;
$this->throwable = $throwable;
$this->duration = 0.0;
$asWarning = $this->type === TestResult::WARN
|| $this->type === TestResult::RISKY
|| $this->type === TestResult::SKIPPED
|| $this->type === TestResult::DEPRECATED
|| $this->type === TestResult::NOTICE
|| $this->type === TestResult::INCOMPLETE;
if ($throwable instanceof Throwable && $asWarning) {
if (in_array($this->type, [TestResult::DEPRECATED, TestResult::NOTICE])) {
foreach (explode("\n", $throwable->stackTrace()) as $line) {
if (strpos($line, 'vendor/nunomaduro/collision') === false) {
$this->warningSource = str_replace(getcwd().'/', '', $line);
break;
}
}
}
$this->warning .= trim((string) preg_replace("/\r|\n/", ' ', $throwable->message()));
// pest specific
$this->warning = str_replace('__pest_evaluable_', '', $this->warning);
$this->warning = str_replace('This test depends on "P\\', 'This test depends on "', $this->warning);
}
}
/**
* Sets the telemetry information.
*/
public function setDuration(float $duration): void
{
$this->duration = $duration;
}
/**
* Creates a new test from the given test case.
*/
public static function fromTestCase(Test $test, string $type, ?Throwable $throwable = null): self
{
if (! $test instanceof TestMethod) {
throw new ShouldNotHappen;
}
if (is_subclass_of($test->className(), HasPrintableTestCaseName::class)) {
$testCaseName = $test->className()::getPrintableTestCaseName();
} else {
$testCaseName = $test->className();
}
$description = self::makeDescription($test);
$icon = self::makeIcon($type);
$compactIcon = self::makeCompactIcon($type);
$color = self::makeColor($type);
$compactColor = self::makeCompactColor($type);
return new self($test->id(), $testCaseName, $description, $type, $icon, $compactIcon, $color, $compactColor, $throwable);
}
/**
* Creates a new test from the given Pest Parallel Test Case.
*/
public static function fromPestParallelTestCase(Test $test, string $type, ?Throwable $throwable = null): self
{
if (! $test instanceof TestMethod) {
throw new ShouldNotHappen;
}
if (is_subclass_of($test->className(), HasPrintableTestCaseName::class)) {
$testCaseName = $test->className()::getPrintableTestCaseName();
} else {
$testCaseName = $test->className();
}
if (is_subclass_of($test->className(), HasPrintableTestCaseName::class)) {
$description = $test->testDox()->prettifiedMethodName();
} else {
$description = self::makeDescription($test);
}
$icon = self::makeIcon($type);
$compactIcon = self::makeCompactIcon($type);
$color = self::makeColor($type);
$compactColor = self::makeCompactColor($type);
return new self($test->id(), $testCaseName, $description, $type, $icon, $compactIcon, $color, $compactColor, $throwable);
}
/**
* Creates a new test from the given test case.
*/
public static function fromBeforeFirstTestMethodErrored(BeforeFirstTestMethodErrored $event): self
{
if (is_subclass_of($event->testClassName(), HasPrintableTestCaseName::class)) {
$testCaseName = $event->testClassName()::getPrintableTestCaseName();
} else {
$testCaseName = $event->testClassName();
}
$description = '';
$icon = self::makeIcon(self::FAIL);
$compactIcon = self::makeCompactIcon(self::FAIL);
$color = self::makeColor(self::FAIL);
$compactColor = self::makeCompactColor(self::FAIL);
return new self($testCaseName, $testCaseName, $description, self::FAIL, $icon, $compactIcon, $color, $compactColor, $event->throwable());
}
/**
* Get the test case description.
*/
public static function makeDescription(TestMethod $test): string
{
if (is_subclass_of($test->className(), HasPrintableTestCaseName::class)) {
return $test->className()::getLatestPrintableTestCaseMethodName();
}
$name = $test->name();
// First, lets replace underscore by spaces.
$name = str_replace('_', ' ', $name);
// Then, replace upper cases by spaces.
$name = (string) preg_replace('/([A-Z])/', ' $1', $name);
// Finally, if it starts with `test`, we remove it.
$name = (string) preg_replace('/^test/', '', $name);
// Removes spaces
$name = trim($name);
// Lower case everything
$name = mb_strtolower($name);
return $name;
}
/**
* Get the test case icon.
*/
public static function makeIcon(string $type): string
{
switch ($type) {
case self::FAIL:
return '';
case self::SKIPPED:
return '-';
case self::DEPRECATED:
case self::WARN:
case self::RISKY:
case self::NOTICE:
return '!';
case self::INCOMPLETE:
return '…';
case self::TODO:
return '↓';
case self::RUNS:
return '•';
default:
return '✓';
}
}
/**
* Get the test case compact icon.
*/
public static function makeCompactIcon(string $type): string
{
switch ($type) {
case self::FAIL:
return '';
case self::SKIPPED:
return 's';
case self::DEPRECATED:
case self::NOTICE:
case self::WARN:
case self::RISKY:
return '!';
case self::INCOMPLETE:
return 'i';
case self::TODO:
return 't';
case self::RUNS:
return '•';
default:
return '.';
}
}
/**
* Get the test case compact color.
*/
public static function makeCompactColor(string $type): string
{
switch ($type) {
case self::FAIL:
return 'red';
case self::DEPRECATED:
case self::NOTICE:
case self::SKIPPED:
case self::INCOMPLETE:
case self::RISKY:
case self::WARN:
case self::RUNS:
return 'yellow';
case self::TODO:
return 'cyan';
default:
return 'gray';
}
}
/**
* Get the test case color.
*/
public static function makeColor(string $type): string
{
switch ($type) {
case self::TODO:
return 'cyan';
case self::FAIL:
return 'red';
case self::DEPRECATED:
case self::NOTICE:
case self::SKIPPED:
case self::INCOMPLETE:
case self::RISKY:
case self::WARN:
case self::RUNS:
return 'yellow';
default:
return 'green';
}
}
}