mirror of
https://github.com/pestphp/pest.git
synced 2026-12-05 15:22:17 +01:00
Compare commits
17 Commits
a6a919c32c
..
5.x
| Author | SHA1 | Date | |
|---|---|---|---|
| 0481044270 | |||
| d2c1b99236 | |||
| 59c1cb78f8 | |||
| cd5bae7e91 | |||
| 586add8ff2 | |||
| 13fc0a7890 | |||
| 2b2a1dab31 | |||
| 12bddc0137 | |||
| f5874c12ca | |||
| 557aca75a0 | |||
| 5b534641e4 | |||
| edb56ae412 | |||
| 8c635c5ba0 | |||
| b5851d67ff | |||
| d314fc0540 | |||
| 093ca57693 | |||
| cf21b7cd64 |
@@ -27,8 +27,12 @@ jobs:
|
||||
symfony: ['8.0']
|
||||
php: ['8.4', '8.5', '8.6']
|
||||
dependency_version: [prefer-stable]
|
||||
suite: [default, tia]
|
||||
exclude:
|
||||
- os: ubuntu-latest
|
||||
suite: tia
|
||||
|
||||
name: PHP ${{ matrix.php }} - Symfony ^${{ matrix.symfony }} - ${{ matrix.os }} - ${{ matrix.dependency_version }}
|
||||
name: PHP ${{ matrix.php }} - Symfony ^${{ matrix.symfony }} - ${{ matrix.os }} - ${{ matrix.dependency_version }}${{ matrix.suite != 'default' && format(' - {0}', matrix.suite) || '' }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -68,10 +72,21 @@ jobs:
|
||||
run: composer update --${{ matrix.dependency_version }} --no-interaction --no-progress --ansi --with="symfony/console:^${{ matrix.symfony }}"
|
||||
|
||||
- name: Unit Tests
|
||||
if: matrix.suite == 'default'
|
||||
run: composer test:unit
|
||||
|
||||
- name: Parallel Tests
|
||||
if: matrix.suite == 'default'
|
||||
run: composer test:parallel
|
||||
|
||||
- name: Integration Tests
|
||||
if: runner.os != 'macOS'
|
||||
run: composer test:integration
|
||||
|
||||
- name: TIA Integration Tests
|
||||
if: matrix.suite == 'tia'
|
||||
run: XDEBUG_MODE=off composer test:tia
|
||||
|
||||
- name: Visual Integration Tests
|
||||
if: runner.os == 'macOS' && matrix.suite == 'default'
|
||||
run: composer test:integration -- --exclude-group=tia
|
||||
|
||||
@@ -20,7 +20,6 @@ use Symfony\Component\Console\Input\ArgvInput;
|
||||
use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
|
||||
(static function () {
|
||||
// Ensures Collision's Printer is registered.
|
||||
$_SERVER['COLLISION_PRINTER'] = 'DefaultPrinter';
|
||||
|
||||
$arguments = $originalArguments = $_SERVER['argv'];
|
||||
@@ -123,8 +122,7 @@ use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
}
|
||||
|
||||
if ($value === '--teamcity') {
|
||||
unset($arguments[$key]);
|
||||
$arguments[] = '--no-output';
|
||||
$arguments[$key] = '--no-output';
|
||||
unset($_SERVER['COLLISION_PRINTER']);
|
||||
}
|
||||
}
|
||||
@@ -143,7 +141,6 @@ use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
|
||||
$isOptionValue = false;
|
||||
|
||||
// Convert namespace-style arguments (e.g. Tests\Unit\TestName) to file paths.
|
||||
foreach ($arguments as $key => $value) {
|
||||
if ($isOptionValue) {
|
||||
$isOptionValue = false;
|
||||
@@ -173,7 +170,6 @@ use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try lowercasing the first directory segment (e.g. Tests -> tests).
|
||||
$segments = explode(DIRECTORY_SEPARATOR, $path);
|
||||
$segments[0] = lcfirst($segments[0]);
|
||||
$lowercasedPath = implode(DIRECTORY_SEPARATOR, $segments);
|
||||
@@ -183,7 +179,6 @@ use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
}
|
||||
}
|
||||
|
||||
// Used when Pest is required using composer.
|
||||
$autoloadPath = $GLOBALS['_composer_autoload_path'] ?? dirname(__DIR__, 3).'/autoload.php';
|
||||
|
||||
if (! is_file($autoloadPath)) {
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
<directory suffix=".php">./tests-external</directory>
|
||||
<exclude>./tests/.snapshots</exclude>
|
||||
<exclude>./tests/Fixtures/Inheritance</exclude>
|
||||
<exclude>./tests/Fixtures/ParallelIncludePath</exclude>
|
||||
<exclude>./tests/Fixtures/Suites</exclude>
|
||||
<exclude>./tests/Fixtures/Tia</exclude>
|
||||
</testsuite>
|
||||
|
||||
@@ -28,6 +28,7 @@ return RectorConfig::configure()
|
||||
__DIR__.'/src/Plugins/Parallel/Paratest/WrapperRunner.php',
|
||||
__DIR__.'/tests/Fixtures/Arch',
|
||||
__DIR__.'/tests/Fixtures/Suites',
|
||||
__DIR__.'/tests/Fixtures/ParallelIncludePath',
|
||||
ReturnNeverTypeRector::class,
|
||||
ArrowFunctionDelegatingCallToFirstClassCallableRector::class,
|
||||
NarrowObjectReturnTypeRector::class,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Exceptions;
|
||||
|
||||
use NunoMaduro\Collision\Contracts\RenderlessEditor;
|
||||
use NunoMaduro\Collision\Contracts\RenderlessTrace;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Exception\ExceptionInterface;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class GitTimedOut extends RuntimeException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
|
||||
{
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
public function __construct(array $arguments, float $timeout)
|
||||
{
|
||||
parent::__construct(sprintf('Git did not answer within %s seconds: git %s', $timeout, implode(' ', $arguments)));
|
||||
}
|
||||
}
|
||||
@@ -48,12 +48,14 @@ final readonly class OppositeExpectation
|
||||
public function toHaveKeys(array $keys): Expectation
|
||||
{
|
||||
foreach ($keys as $k => $key) {
|
||||
if (is_array($key)) {
|
||||
$this->toHaveKeys(array_keys(Arr::dot($key, $k.'.')));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
if (is_array($key)) {
|
||||
$this->toHaveKeys(array_keys(Arr::dot($key, $k.'.')));
|
||||
} else {
|
||||
$this->original->toHaveKey($key);
|
||||
}
|
||||
$this->original->toHaveKey($key);
|
||||
} catch (ExpectationFailedException) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -847,7 +847,7 @@ final class Expectation
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (! class_exists($exception)) {
|
||||
if (! class_exists($exception) && ! interface_exists($exception)) {
|
||||
if ($e instanceof Error && "Class \"$exception\" not found" === $e->getMessage()) {
|
||||
Assert::assertTrue(true);
|
||||
|
||||
@@ -872,7 +872,7 @@ final class Expectation
|
||||
|
||||
Assert::assertTrue(true);
|
||||
|
||||
if (! $exception instanceof Throwable && ! class_exists($exception)) {
|
||||
if (! $exception instanceof Throwable && ! class_exists($exception) && ! interface_exists($exception)) {
|
||||
throw new ExpectationFailedException("Exception with message [$exception] not thrown.");
|
||||
}
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ final class TestCall
|
||||
{
|
||||
if (is_int($exception)) {
|
||||
$exceptionCode = $exception;
|
||||
} elseif (class_exists($exception)) {
|
||||
} elseif (class_exists($exception) || interface_exists($exception)) {
|
||||
$this->testCaseMethod
|
||||
->proxies
|
||||
->add(Backtrace::file(), Backtrace::line(), 'expectException', [$exception]);
|
||||
|
||||
@@ -33,7 +33,16 @@ trait HandleArguments
|
||||
*/
|
||||
public function pushArgument(string $argument, array $arguments): array
|
||||
{
|
||||
$arguments[] = $argument;
|
||||
$arguments = array_values($arguments);
|
||||
$endOfOptionsPosition = array_search('--', $arguments, true);
|
||||
|
||||
if ($endOfOptionsPosition === false) {
|
||||
$arguments[] = $argument;
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
array_splice($arguments, $endOfOptionsPosition, 0, [$argument]);
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
+55
-27
@@ -27,6 +27,16 @@ final class Coverage implements AddsOutput, HandlesArguments
|
||||
|
||||
private const string ONLY_COVERED_OPTION = 'only-covered';
|
||||
|
||||
/**
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
private const array OPTIONS = [
|
||||
self::COVERAGE_OPTION => false,
|
||||
self::MIN_OPTION => true,
|
||||
self::EXACTLY_OPTION => true,
|
||||
self::ONLY_COVERED_OPTION => false,
|
||||
];
|
||||
|
||||
public bool $coverage = false;
|
||||
|
||||
public bool $compact = false;
|
||||
@@ -37,33 +47,11 @@ final class Coverage implements AddsOutput, HandlesArguments
|
||||
|
||||
public bool $showOnlyCovered = false;
|
||||
|
||||
public function __construct(private readonly OutputInterface $output)
|
||||
{
|
||||
//
|
||||
}
|
||||
public function __construct(private readonly OutputInterface $output) {}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function handleArguments(array $originals): array
|
||||
{
|
||||
$arguments = [...[''], ...array_values(array_filter($originals, function (string $original): bool {
|
||||
foreach ([self::COVERAGE_OPTION, self::MIN_OPTION, self::EXACTLY_OPTION, self::ONLY_COVERED_OPTION] as $option) {
|
||||
if ($original === sprintf('--%s', $option)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Str::startsWith($original, sprintf('--%s=', $option))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}))];
|
||||
|
||||
foreach ($arguments as $argument) {
|
||||
$originals = $this->popArgument($argument, $originals);
|
||||
}
|
||||
[$arguments, $originals] = $this->extractOwnArguments($originals);
|
||||
|
||||
$inputs = [];
|
||||
$inputs[] = new InputOption(self::COVERAGE_OPTION, null, InputOption::VALUE_NONE);
|
||||
@@ -74,8 +62,8 @@ final class Coverage implements AddsOutput, HandlesArguments
|
||||
$input = new ArgvInput($arguments, new InputDefinition($inputs));
|
||||
if ((bool) $input->getOption(self::COVERAGE_OPTION)) {
|
||||
$this->coverage = true;
|
||||
$originals[] = '--coverage-php';
|
||||
$originals[] = \Pest\Support\Coverage::getPath();
|
||||
$originals = $this->pushArgument('--coverage-php', $originals);
|
||||
$originals = $this->pushArgument(\Pest\Support\Coverage::getPath(), $originals);
|
||||
|
||||
if (! \Pest\Support\Coverage::isAvailable()) {
|
||||
if (\Pest\Support\Coverage::usingXdebug()) {
|
||||
@@ -122,8 +110,48 @@ final class Coverage implements AddsOutput, HandlesArguments
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
* @param array<int, string> $originals
|
||||
* @return array{0: list<string>, 1: list<string>}
|
||||
*/
|
||||
private function extractOwnArguments(array $originals): array
|
||||
{
|
||||
$originals = array_values($originals);
|
||||
|
||||
$owned = [];
|
||||
$forwarded = [];
|
||||
|
||||
for ($index = 0, $total = count($originals); $index < $total; $index++) {
|
||||
$original = $originals[$index];
|
||||
|
||||
foreach (self::OPTIONS as $option => $requiresValue) {
|
||||
if (Str::startsWith($original, sprintf('--%s=', $option))) {
|
||||
$owned[] = $original;
|
||||
|
||||
continue 2;
|
||||
}
|
||||
|
||||
if ($original !== sprintf('--%s', $option)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$owned[] = $original;
|
||||
|
||||
$value = $originals[$index + 1] ?? null;
|
||||
|
||||
if ($requiresValue && $value !== null && ! Str::startsWith($value, '-')) {
|
||||
$owned[] = $value;
|
||||
$index++;
|
||||
}
|
||||
|
||||
continue 2;
|
||||
}
|
||||
|
||||
$forwarded[] = $original;
|
||||
}
|
||||
|
||||
return [['', ...$owned], $forwarded];
|
||||
}
|
||||
|
||||
public function addOutput(int $exitCode): int
|
||||
{
|
||||
if (Parallel::isWorker()) {
|
||||
|
||||
@@ -26,6 +26,7 @@ final class Parallel implements HandlesArguments
|
||||
private const string GLOBAL_PREFIX = 'PEST_PARALLEL_GLOBAL_';
|
||||
|
||||
private const array HANDLERS = [
|
||||
Parallel\Handlers\IncludePath::class,
|
||||
Parallel\Handlers\Parallel::class,
|
||||
Parallel\Handlers\Pest::class,
|
||||
Parallel\Handlers\Laravel::class,
|
||||
@@ -78,9 +79,6 @@ final class Parallel implements HandlesArguments
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function handleArguments(array $arguments): array
|
||||
{
|
||||
if ($this->hasArgumentsThatWouldBeFasterWithoutParallel()) {
|
||||
@@ -150,6 +148,7 @@ final class Parallel implements HandlesArguments
|
||||
$command->setVersion(version());
|
||||
|
||||
Parallel\Handlers\StopOn::configureOptions($command->find('paratest')->getDefinition());
|
||||
Parallel\Handlers\IncludePath::configureOptions($command->find('paratest')->getDefinition());
|
||||
|
||||
return $command;
|
||||
}
|
||||
@@ -180,7 +179,7 @@ final class Parallel implements HandlesArguments
|
||||
{
|
||||
$argv = new ArgvInput;
|
||||
if ($argv->hasParameterOption('--teamcity')) {
|
||||
$arguments[] = '--teamcity';
|
||||
$arguments = $this->pushArgument('--teamcity', $arguments);
|
||||
}
|
||||
|
||||
return $arguments;
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Parallel\Handlers;
|
||||
|
||||
use Pest\Contracts\Plugins\HandlesArguments;
|
||||
use Pest\Plugins\Parallel as ParallelPlugin;
|
||||
use Pest\Plugins\Parallel\Contracts\HandlersWorkerArguments;
|
||||
use Pest\Subscribers\EnsureCommandLineIncludePathComesFirst;
|
||||
use PHPUnit\Event\Facade as EventFacade;
|
||||
use PHPUnit\TextUI\CliArguments\Builder;
|
||||
use PHPUnit\TextUI\CliArguments\Configuration;
|
||||
use Symfony\Component\Console\Input\InputDefinition;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Throwable;
|
||||
|
||||
final class IncludePath implements HandlersWorkerArguments, HandlesArguments
|
||||
{
|
||||
private const string OPTION = '--include-path';
|
||||
|
||||
private const string GLOBAL_KEY = 'INCLUDE_PATH';
|
||||
|
||||
private const string PROGRAM = 'pest';
|
||||
|
||||
public function handleArguments(array $arguments): array
|
||||
{
|
||||
$arguments = array_values($arguments);
|
||||
$includePath = null;
|
||||
$argumentsForParatest = [];
|
||||
$separatorAndArgumentsAfterIt = [];
|
||||
|
||||
for ($index = 0; $index < count($arguments); $index++) {
|
||||
$argument = trim($arguments[$index]);
|
||||
|
||||
if ($argument === '--') {
|
||||
$separatorAndArgumentsAfterIt = array_slice($arguments, $index);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if ($argument === self::OPTION || str_starts_with($argument, self::OPTION.'=')) {
|
||||
$optionArguments = $this->optionArgumentsPhpunitReads($arguments, $index);
|
||||
$includePath = $this->includePathPhpunitReads($optionArguments);
|
||||
$index += count($optionArguments) - 1;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$argumentsForParatest[] = $arguments[$index];
|
||||
}
|
||||
|
||||
ParallelPlugin::setGlobal(self::GLOBAL_KEY, $includePath === null ? false : base64_encode($includePath));
|
||||
|
||||
if ($includePath !== null) {
|
||||
$commandLineIncludePathComesFirst = new EnsureCommandLineIncludePathComesFirst($includePath);
|
||||
$commandLineIncludePathComesFirst->apply();
|
||||
|
||||
EventFacade::instance()->registerSubscriber($commandLineIncludePathComesFirst);
|
||||
}
|
||||
|
||||
if ($includePath !== null && $this->survivesThePhpunitParser($includePath)) {
|
||||
array_push($argumentsForParatest, ...$this->argumentsPhpunitReadsAs($includePath));
|
||||
}
|
||||
|
||||
return [...$argumentsForParatest, ...$separatorAndArgumentsAfterIt];
|
||||
}
|
||||
|
||||
public static function configureOptions(InputDefinition $definition): void
|
||||
{
|
||||
$definition->addOption(new InputOption(substr(self::OPTION, 2), null, InputOption::VALUE_REQUIRED));
|
||||
}
|
||||
|
||||
public function handleWorkerArguments(array $arguments): array
|
||||
{
|
||||
$encodedIncludePath = ParallelPlugin::getGlobal(self::GLOBAL_KEY);
|
||||
$includePath = is_string($encodedIncludePath) ? base64_decode($encodedIncludePath, true) : false;
|
||||
|
||||
if (! is_string($includePath) || $includePath === '') {
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
return [...$arguments, ...$this->argumentsPhpunitReadsAs($includePath)];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $arguments
|
||||
* @return list<string>
|
||||
*/
|
||||
private function optionArgumentsPhpunitReads(array $arguments, int $index): array
|
||||
{
|
||||
if ($this->phpunitConfiguration([$arguments[$index]]) instanceof Configuration) {
|
||||
return [$arguments[$index]];
|
||||
}
|
||||
|
||||
return array_slice($arguments, $index, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $optionArguments
|
||||
*/
|
||||
private function includePathPhpunitReads(array $optionArguments): ?string
|
||||
{
|
||||
$configuration = $this->phpunitConfiguration($optionArguments);
|
||||
|
||||
return $configuration instanceof Configuration && $configuration->hasIncludePath() ? $configuration->includePath() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $parameters
|
||||
*/
|
||||
private function phpunitConfiguration(array $parameters): ?Configuration
|
||||
{
|
||||
try {
|
||||
return new Builder(EventFacade::emitter())->fromParameters([self::PROGRAM, ...$parameters]);
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function argumentsPhpunitReadsAs(string $includePath): array
|
||||
{
|
||||
if (! $this->survivesThePhpunitParser($includePath)) {
|
||||
return [self::OPTION, $includePath];
|
||||
}
|
||||
|
||||
return [self::OPTION.'='.$includePath.$this->closingEqualsSignThatStopsTheTrim($includePath)];
|
||||
}
|
||||
|
||||
private function closingEqualsSignThatStopsTheTrim(string $includePath): string
|
||||
{
|
||||
return rtrim($includePath) === $includePath ? '' : '=';
|
||||
}
|
||||
|
||||
private function survivesThePhpunitParser(string $includePath): bool
|
||||
{
|
||||
return $includePath !== '' && ! str_contains($includePath, '=');
|
||||
}
|
||||
}
|
||||
@@ -66,14 +66,14 @@ final class Laravel implements HandlesArguments
|
||||
*/
|
||||
private function ensureEnvironmentVariables(array $arguments): array
|
||||
{
|
||||
$_ENV['LARAVEL_PARALLEL_TESTING'] = 1;
|
||||
$_SERVER['LARAVEL_PARALLEL_TESTING'] = $_ENV['LARAVEL_PARALLEL_TESTING'] = 1;
|
||||
|
||||
if ($this->hasArgument('--recreate-databases', $arguments)) {
|
||||
$_ENV['LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES'] = 1;
|
||||
$_SERVER['LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES'] = $_ENV['LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES'] = 1;
|
||||
}
|
||||
|
||||
if ($this->hasArgument('--drop-databases', $arguments)) {
|
||||
$_ENV['LARAVEL_PARALLEL_TESTING_DROP_DATABASES'] = 1;
|
||||
$_SERVER['LARAVEL_PARALLEL_TESTING_DROP_DATABASES'] = $_ENV['LARAVEL_PARALLEL_TESTING_DROP_DATABASES'] = 1;
|
||||
}
|
||||
|
||||
$arguments = $this->popArgument('--recreate-databases', $arguments);
|
||||
|
||||
@@ -98,9 +98,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
|
||||
public function __construct(
|
||||
private readonly OutputInterface $output,
|
||||
) {
|
||||
//
|
||||
}
|
||||
) {}
|
||||
|
||||
public static function useTimingsFile(string $filename): void
|
||||
{
|
||||
@@ -144,9 +142,6 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
return self::$ownership[$unit];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function handleArguments(array $arguments): array
|
||||
{
|
||||
if ($this->hasArgument('--update-shards', $arguments)) {
|
||||
@@ -220,7 +215,8 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
|
||||
$this->ensureFilterLengthIsSafe($filter);
|
||||
|
||||
$arguments = [...$arguments, '--filter', $filter];
|
||||
$arguments = $this->pushArgument('--filter', $arguments);
|
||||
$arguments = $this->pushArgument($filter, $arguments);
|
||||
|
||||
if ($this->hasArgument('--do-not-fail-on-empty-test-suite', $arguments) || $this->hasArgument('--fail-on-empty-test-suite', $arguments)) {
|
||||
return $arguments;
|
||||
@@ -350,7 +346,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
}
|
||||
}
|
||||
|
||||
return [PHP_BINARY, ...$filtered, '--test-directory='.$testPath, '--list-tests'];
|
||||
return [PHP_BINARY, ...$this->pushArgument('--list-tests', $this->pushArgument('--test-directory='.$testPath, $filtered))];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+417
-57
@@ -10,6 +10,7 @@ use Pest\Contracts\Plugins\AddsOutput;
|
||||
use Pest\Contracts\Plugins\HandlesArguments;
|
||||
use Pest\Contracts\Plugins\HandlesOriginalArguments;
|
||||
use Pest\Contracts\Plugins\Terminable;
|
||||
use Pest\Exceptions\GitTimedOut;
|
||||
use Pest\Exceptions\InvalidOption;
|
||||
use Pest\Exceptions\MissingDependency;
|
||||
use Pest\Exceptions\NoAffectedTestsFound;
|
||||
@@ -27,6 +28,7 @@ use Pest\Plugins\Tia\CiBranch;
|
||||
use Pest\Plugins\Tia\ConfigurationFile;
|
||||
use Pest\Plugins\Tia\Contracts\State;
|
||||
use Pest\Plugins\Tia\CoverageCollector;
|
||||
use Pest\Plugins\Tia\ExternalSources;
|
||||
use Pest\Plugins\Tia\Fingerprint;
|
||||
use Pest\Plugins\Tia\Graph;
|
||||
use Pest\Plugins\Tia\JsModuleGraph;
|
||||
@@ -36,6 +38,7 @@ use Pest\Plugins\Tia\SourceScope;
|
||||
use Pest\Plugins\Tia\Storage;
|
||||
use Pest\Plugins\Tia\TableExtractor;
|
||||
use Pest\Plugins\Tia\WatchPatterns;
|
||||
use Pest\Support\Arr;
|
||||
use Pest\Support\Ci;
|
||||
use Pest\Support\Container;
|
||||
use Pest\Support\Git;
|
||||
@@ -191,6 +194,16 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
private ?string $startSha = null;
|
||||
|
||||
/**
|
||||
* @var array<string, string>|null
|
||||
*/
|
||||
private ?array $ignoredInputsAtStart = null;
|
||||
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private array $ignoredInputsChangedDuringRun = [];
|
||||
|
||||
private bool $piggybackCoverage = false;
|
||||
|
||||
private bool $recordingActive = false;
|
||||
@@ -203,8 +216,17 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
private bool $writesSuppressed = false;
|
||||
|
||||
private bool $dirtyExternalSourcesResolved = false;
|
||||
|
||||
/** @var array<int, string>|null */
|
||||
private ?array $dirtyExternalSources = null;
|
||||
|
||||
private bool $resultsOnlyWrites = false;
|
||||
|
||||
private bool $scoped = false;
|
||||
|
||||
private bool $announcesPartialRun = false;
|
||||
|
||||
private bool $flushesWorkerResults = false;
|
||||
|
||||
private bool $unreadableGraphReported = false;
|
||||
@@ -424,11 +446,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return null;
|
||||
}
|
||||
|
||||
$projectRoot = TestSuite::getInstance()->rootPath;
|
||||
$real = @realpath($filename);
|
||||
$rel = $real !== false
|
||||
? str_replace(DIRECTORY_SEPARATOR, '/', substr($real, strlen(rtrim($projectRoot, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR)))
|
||||
: null;
|
||||
$rel = $this->projectRelativeTestFile($filename);
|
||||
|
||||
if ($rel !== null && isset($this->affectedFiles[$rel])) {
|
||||
$this->affectedCount++;
|
||||
@@ -472,6 +490,31 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function projectRelativeTestFile(string $filename): ?string
|
||||
{
|
||||
$projectRoot = TestSuite::getInstance()->rootPath;
|
||||
$real = @realpath($filename);
|
||||
|
||||
return $real !== false
|
||||
? str_replace(DIRECTORY_SEPARATOR, '/', substr($real, strlen(rtrim($projectRoot, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR)))
|
||||
: null;
|
||||
}
|
||||
|
||||
private function refreshesEdgesOf(string $testFile): bool
|
||||
{
|
||||
$rel = $this->projectRelativeTestFile($testFile);
|
||||
|
||||
if ($rel === null || ! $this->replayGraph instanceof Graph) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! $this->replayGraph->knowsTest($rel)) {
|
||||
return ! $this->piggybackCoverage;
|
||||
}
|
||||
|
||||
return isset($this->affectedFiles[$rel]);
|
||||
}
|
||||
|
||||
public function getAssertionCount(string $testId): int
|
||||
{
|
||||
return $this->cachedAssertionsByTestId[$testId] ?? 0;
|
||||
@@ -493,6 +536,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$configurationPlugin = Container::getInstance()->get(Configuration::class);
|
||||
assert($configurationPlugin instanceof Configuration);
|
||||
$this->configuration = ConfigurationFile::fromArguments($arguments, $configurationPlugin->generatedConfigurationPath());
|
||||
ExternalSources::pinWorkingDirectory(TestSuite::getInstance()->rootPath);
|
||||
|
||||
$isWorker = Parallel::isWorker();
|
||||
$recordingGlobal = $isWorker && (string) Parallel::getGlobal(self::RECORDING_GLOBAL) === '1';
|
||||
@@ -514,19 +558,29 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
$hasExplicitPath = $this->hasExplicitPathArgument($arguments);
|
||||
$partial = ! $isWorker && ($hasExplicitPath || $this->hasPartialSelection($arguments));
|
||||
$disabled = $disabled || $partial || $this->hasListingOption($arguments);
|
||||
|
||||
$freshRequested = $this->hasArgument(self::FRESH_OPTION, $arguments);
|
||||
$refetchRequested = $this->hasArgument(self::REFETCH_OPTION, $arguments);
|
||||
$mutating = self::isMutationRun($this->originalArguments);
|
||||
$this->scoped = $partial
|
||||
&& ! $freshRequested
|
||||
&& ! $refetchRequested
|
||||
&& ! $mutating
|
||||
&& ! $this->coverageReportActive();
|
||||
$disabled = $disabled || ($partial && ! $this->scoped) || $this->hasListingOption($arguments);
|
||||
|
||||
if ($partial) {
|
||||
$this->resultsOnlyWrites = true;
|
||||
}
|
||||
|
||||
if (getenv(self::ENV_MUTATION_TESTING) !== false) {
|
||||
$this->writesSuppressed = true;
|
||||
}
|
||||
$enabled = ! $disabled && ($cliEnabled || $alwaysEnabled);
|
||||
$this->filteredMode = ($this->hasArgument(self::FILTERED_OPTION, $arguments) || self::envFlagEnabled(self::ENV_FILTERED) || $watchPatterns->isFiltered())
|
||||
&& ! $hasExplicitPath
|
||||
$filteredRequested = $this->hasArgument(self::FILTERED_OPTION, $arguments) || self::envFlagEnabled(self::ENV_FILTERED) || $watchPatterns->isFiltered();
|
||||
$this->filteredMode = $filteredRequested
|
||||
&& ! $partial
|
||||
&& ! $this->coverageReportActive();
|
||||
$freshRequested = $this->hasArgument(self::FRESH_OPTION, $arguments);
|
||||
$this->forceRefetch = $this->hasArgument(self::REFETCH_OPTION, $arguments);
|
||||
$this->forceRefetch = $refetchRequested;
|
||||
|
||||
$arguments = $this->popArgument(self::OPTION, $arguments);
|
||||
$arguments = $this->popArgument(self::NO_OPTION, $arguments);
|
||||
@@ -536,22 +590,14 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$arguments = $this->popArgument(self::LOCALLY_OPTION, $arguments);
|
||||
$arguments = $this->popArgument(self::BASELINED_OPTION, $arguments);
|
||||
|
||||
$this->announcesPartialRun = $partial
|
||||
&& ($cliEnabled || $freshRequested || $refetchRequested || ($filteredRequested && ! $hasExplicitPath && ! $this->coverageReportActive()));
|
||||
|
||||
if ($disabled) {
|
||||
$this->requestWorkerResults();
|
||||
|
||||
if ($partial) {
|
||||
$this->resultsOnlyWrites = true;
|
||||
|
||||
if ($cliEnabled || $freshRequested || $this->forceRefetch || $this->filteredMode) {
|
||||
$this->output->writeln('');
|
||||
$this->renderChild('TIA does not apply to partial runs — running the selected tests directly.');
|
||||
}
|
||||
}
|
||||
|
||||
$this->forceRefetch = false;
|
||||
$this->filteredMode = false;
|
||||
|
||||
return $arguments;
|
||||
return $this->runSelectionDirectly($arguments);
|
||||
}
|
||||
|
||||
if (! $isWorker && $mutating && ($enabled || $this->forceRefetch)) {
|
||||
@@ -619,7 +665,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
$projectRoot = TestSuite::getInstance()->rootPath;
|
||||
$perTest = $this->piggybackCoverage
|
||||
? $this->mergePerTestFiles($this->coverageCollector->perTestFiles(), $recorder->perTestFiles())
|
||||
? $this->mergePerTestFiles(array_filter($this->coverageCollector->perTestFiles(), $this->refreshesEdgesOf(...), ARRAY_FILTER_USE_KEY), $recorder->perTestFiles())
|
||||
: $recorder->perTestFiles();
|
||||
|
||||
if ($perTest === []) {
|
||||
@@ -652,7 +698,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$changedFiles = new ChangedFiles($projectRoot);
|
||||
$currentSha = $changedFiles->currentSha();
|
||||
|
||||
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration);
|
||||
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration, $this->originalArguments);
|
||||
|
||||
if ($this->structuralFingerprintShifted($currentFingerprint)) {
|
||||
$this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.');
|
||||
@@ -671,12 +717,20 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->externalSourcesChangedDuringRun($projectRoot)) {
|
||||
$this->renderExternalSourcesChangedDuringRun('discarding recorded edges');
|
||||
$recorder->reset();
|
||||
$this->coverageCollector->reset();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$graph = $this->loadGraph($projectRoot) ?? new Graph($projectRoot);
|
||||
$graph->setFingerprint($currentFingerprint);
|
||||
$graph->setRecordedAtSha($this->branch, $currentSha);
|
||||
$graph->setLastRunTree(
|
||||
$this->branch,
|
||||
$changedFiles->snapshotTree($changedFiles->since($currentSha) ?? []),
|
||||
$changedFiles->baselineTree($currentSha, ExternalSources::ignoredInputs($projectRoot, $this->originalArguments)),
|
||||
);
|
||||
$graph->replaceEdges($perTest, keepExisting: $this->piggybackCoverage);
|
||||
$graph->replaceTestTables($perTestTables);
|
||||
@@ -746,7 +800,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$changedFiles = new ChangedFiles($projectRoot);
|
||||
$currentSha = $changedFiles->currentSha();
|
||||
|
||||
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration);
|
||||
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration, $this->originalArguments);
|
||||
|
||||
if ($this->structuralFingerprintShifted($currentFingerprint)) {
|
||||
$this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.');
|
||||
@@ -769,12 +823,22 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $exitCode;
|
||||
}
|
||||
|
||||
if ($this->externalSourcesChangedDuringRun($projectRoot)) {
|
||||
$this->renderExternalSourcesChangedDuringRun('discarding recorded edges');
|
||||
|
||||
foreach ($partialKeys as $key) {
|
||||
$this->state->delete($key);
|
||||
}
|
||||
|
||||
return $exitCode;
|
||||
}
|
||||
|
||||
$graph = $this->loadGraph($projectRoot) ?? new Graph($projectRoot);
|
||||
$graph->setFingerprint($currentFingerprint);
|
||||
$graph->setRecordedAtSha($this->branch, $currentSha);
|
||||
$graph->setLastRunTree(
|
||||
$this->branch,
|
||||
$changedFiles->snapshotTree($changedFiles->since($currentSha) ?? []),
|
||||
$changedFiles->baselineTree($currentSha, ExternalSources::ignoredInputs($projectRoot, $this->originalArguments)),
|
||||
);
|
||||
|
||||
[$finalised, $finalisedTables, $finalisedInertia] = $this->consumePartials($partialKeys);
|
||||
@@ -876,6 +940,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
try {
|
||||
$this->resolveBranch($projectRoot);
|
||||
} catch (MissingDependency|TiaGitFailed $missingGit) {
|
||||
if ($this->scoped) {
|
||||
return $this->runSelectionDirectly($arguments);
|
||||
}
|
||||
|
||||
$repository = new ChangedFiles($projectRoot);
|
||||
|
||||
if ($repository->isRepository() && ! $repository->hasCommits()) {
|
||||
@@ -886,14 +954,19 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
}
|
||||
|
||||
if (! $this->fallbackBranchResolved) {
|
||||
if ($this->scoped) {
|
||||
return $this->runSelectionDirectly($arguments);
|
||||
}
|
||||
|
||||
Panic::with(new ChangedFiles($projectRoot)->hasRemote()
|
||||
? new TiaRequiresDefaultBranch
|
||||
: new TiaRequiresRemote);
|
||||
}
|
||||
|
||||
$fingerprint = Fingerprint::compute($projectRoot, $this->configuration);
|
||||
$fingerprint = Fingerprint::compute($projectRoot, $this->configuration, $this->originalArguments);
|
||||
$this->startFingerprint = $fingerprint;
|
||||
$this->startSha = new ChangedFiles($projectRoot)->currentSha();
|
||||
$this->ignoredInputsAtStart = $this->ignoredInputHashes($projectRoot);
|
||||
|
||||
if ($forceRebuild && $this->canRebuildGraph()) {
|
||||
$this->purgeState();
|
||||
@@ -901,6 +974,17 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
$graph = ($forceRebuild || $this->forceRefetch) ? null : $this->loadGraph($projectRoot);
|
||||
|
||||
if ($graph instanceof Graph && $this->scoped) {
|
||||
$drift = [
|
||||
...Fingerprint::structuralDrift($graph->fingerprint(), $fingerprint),
|
||||
...Fingerprint::environmentalDrift($graph->fingerprint(), $fingerprint),
|
||||
];
|
||||
|
||||
if ($drift !== []) {
|
||||
return $this->runSelectionLeavingTheGraph($drift, $arguments);
|
||||
}
|
||||
}
|
||||
|
||||
if ($graph instanceof Graph) {
|
||||
$graph = $this->reconcileFingerprint($graph, $fingerprint);
|
||||
}
|
||||
@@ -929,6 +1013,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->holdsDirtyExternalSources($projectRoot) || $this->holdsUnverifiableExternalSources($projectRoot)) {
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$uncommittedPhpChanges = $this->uncommittedPhpChangesOutsideProject($projectRoot);
|
||||
|
||||
if ($uncommittedPhpChanges !== []) {
|
||||
@@ -943,6 +1031,13 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$this->state->write(self::KEY_COVERAGE_MARKER, '');
|
||||
}
|
||||
|
||||
if (! $graph instanceof Graph && $this->scoped) {
|
||||
$this->requestWorkerResults();
|
||||
$this->emitScopedRecordSkipped();
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
if (! $graph instanceof Graph && $this->piggybackCoverage) {
|
||||
$this->emitCoverageScopedRecordSkipped();
|
||||
|
||||
@@ -964,6 +1059,134 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $this->enterRecordMode($arguments);
|
||||
}
|
||||
|
||||
private function holdsUnverifiableExternalSources(string $projectRoot): bool
|
||||
{
|
||||
$unverifiable = ExternalSources::unverifiable($projectRoot, $this->originalArguments);
|
||||
|
||||
if ($unverifiable === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->writesSuppressed = true;
|
||||
|
||||
$this->renderBadge('WARN', sprintf(
|
||||
'This project loads %d path%s whose changes git cannot report.',
|
||||
count($unverifiable),
|
||||
count($unverifiable) === 1 ? '' : 's',
|
||||
));
|
||||
|
||||
foreach (array_slice($unverifiable, 0, $this->output->isVerbose() ? count($unverifiable) : 5) as $path) {
|
||||
$this->output->writeln(sprintf(' <fg=gray>%s</>', $path));
|
||||
}
|
||||
|
||||
$this->renderChild($this->runningScope().', and recording nothing — git reports no change there, so no result could stand behind a replay.');
|
||||
$this->renderChild('Move what the project loads into the repository to let TIA select tests again.');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function holdsDirtyExternalSources(string $projectRoot): bool
|
||||
{
|
||||
$dirty = $this->dirtyExternalSources($projectRoot);
|
||||
|
||||
if ($dirty === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->writesSuppressed = true;
|
||||
|
||||
if ($dirty === null) {
|
||||
$this->renderBadge('WARN', 'Git could not read the working tree of the code this project loads from outside its root.');
|
||||
$this->renderChild($this->runningScope().', and recording nothing.');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->renderBadge('WARN', sprintf(
|
||||
'Detected %d uncommitted change%s this project loads from outside its root.',
|
||||
count($dirty),
|
||||
count($dirty) === 1 ? '' : 's',
|
||||
));
|
||||
|
||||
foreach (array_slice($dirty, 0, $this->output->isVerbose() ? count($dirty) : 5) as $file) {
|
||||
$this->output->writeln(sprintf(' <fg=gray>%s</>', $file));
|
||||
}
|
||||
|
||||
$this->renderChild($this->runningScope().', and recording nothing — git stops reporting such an edit once it is undone.');
|
||||
$this->renderChild('Commit what you changed there to let a run leave a baseline behind.');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function externalSourcesChangedDuringRun(string $projectRoot): bool
|
||||
{
|
||||
$this->dirtyExternalSourcesResolved = false;
|
||||
$this->ignoredInputsChangedDuringRun = $this->ignoredInputsAtStart === null
|
||||
? []
|
||||
: new ChangedFiles($projectRoot)->changedExternalInputs($this->ignoredInputsAtStart, $this->ignoredInputHashes($projectRoot));
|
||||
|
||||
return $this->dirtyExternalSources($projectRoot) !== [] || $this->ignoredInputsChangedDuringRun !== [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function ignoredInputHashes(string $projectRoot): array
|
||||
{
|
||||
$ignored = ExternalSources::ignoredState($projectRoot, $this->originalArguments);
|
||||
|
||||
return new ChangedFiles($projectRoot)->externalInputHashes($ignored['inputs'], $ignored['repositories'], [...$ignored['failed'], ...$ignored['unreadable']]);
|
||||
}
|
||||
|
||||
private function renderExternalSourcesChangedDuringRun(string $consequence): void
|
||||
{
|
||||
$this->renderBadge('WARN', 'Code this project loads from outside its root changed during the run — '.$consequence.'.');
|
||||
|
||||
if ($this->ignoredInputsChangedDuringRun !== []) {
|
||||
foreach (array_slice($this->ignoredInputsChangedDuringRun, 0, $this->output->isVerbose() ? count($this->ignoredInputsChangedDuringRun) : 5) as $file) {
|
||||
$this->output->writeln(sprintf(' <fg=gray>%s</>', $file));
|
||||
}
|
||||
|
||||
$this->renderChild('These files changed during the run, or git stopped ignoring them. Keep what the run writes out of the paths this project loads to let TIA record again.');
|
||||
}
|
||||
|
||||
if ($this->ignoredInputsChangedDuringRun === [] || $this->dirtyExternalSources !== []) {
|
||||
$this->renderChild('Re-run --tia after your edits settle to record a fresh dependency graph.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>|null
|
||||
*/
|
||||
private function dirtyExternalSources(string $projectRoot): ?array
|
||||
{
|
||||
if ($this->dirtyExternalSourcesResolved) {
|
||||
return $this->dirtyExternalSources;
|
||||
}
|
||||
|
||||
$this->dirtyExternalSourcesResolved = true;
|
||||
|
||||
if (ExternalSources::rootsFor($projectRoot, $this->originalArguments) === []) {
|
||||
return $this->dirtyExternalSources = [];
|
||||
}
|
||||
|
||||
$changedFiles = new ChangedFiles($projectRoot);
|
||||
|
||||
try {
|
||||
$changedFiles->since(null);
|
||||
} catch (MissingDependency) {
|
||||
return $this->dirtyExternalSources = [];
|
||||
} catch (TiaGitFailed) {
|
||||
return $this->dirtyExternalSources = null;
|
||||
}
|
||||
|
||||
return $this->dirtyExternalSources = ExternalSources::matching(
|
||||
$projectRoot,
|
||||
$changedFiles->outsideProjectDirty(),
|
||||
$this->originalArguments,
|
||||
);
|
||||
}
|
||||
|
||||
private function purgeState(): void
|
||||
{
|
||||
foreach ([
|
||||
@@ -1027,7 +1250,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$recorder->activate();
|
||||
$recorder->activate($this->configuration);
|
||||
$this->recordingActive = true;
|
||||
|
||||
return $arguments;
|
||||
@@ -1077,6 +1300,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
*/
|
||||
private function activateWorkerRecorderForReplay(array $arguments): array
|
||||
{
|
||||
$this->recorder->recordOnly($this->refreshesEdgesOf(...));
|
||||
|
||||
if ($this->piggybackCoverage) {
|
||||
$this->recorder->activateLinkTracking();
|
||||
$this->recordingActive = true;
|
||||
@@ -1087,15 +1312,17 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$recorder = $this->recorder;
|
||||
|
||||
if (! $recorder->driverAvailable()) {
|
||||
$this->state->write(
|
||||
self::KEY_WORKER_NO_DRIVER_PREFIX.$this->workerToken().'.json',
|
||||
'{}',
|
||||
);
|
||||
if ($this->affectedFiles !== []) {
|
||||
$this->state->write(
|
||||
self::KEY_WORKER_NO_DRIVER_PREFIX.$this->workerToken().'.json',
|
||||
'{}',
|
||||
);
|
||||
}
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$recorder->activate();
|
||||
$recorder->activate($this->configuration);
|
||||
$this->recordingActive = true;
|
||||
|
||||
return $arguments;
|
||||
@@ -1118,17 +1345,67 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
$outsideProject = $changedFiles->outsideProject();
|
||||
|
||||
[$changed, $changedExternalInputs] = $changedFiles->changedSinceLastRun(
|
||||
$changed,
|
||||
ExternalSources::ignoredInputs($projectRoot, $this->originalArguments),
|
||||
$graph->lastRunTree($this->branch),
|
||||
);
|
||||
|
||||
$externalChanges = array_values(array_unique([
|
||||
...ExternalSources::matching($projectRoot, $outsideProject, $this->originalArguments),
|
||||
...$changedExternalInputs,
|
||||
]));
|
||||
|
||||
if ($externalChanges !== []) {
|
||||
$this->renderBadge('WARN', sprintf(
|
||||
'Detected changes in %d file%s this project loads from outside its root.',
|
||||
count($externalChanges),
|
||||
count($externalChanges) === 1 ? '' : 's',
|
||||
));
|
||||
|
||||
foreach (array_slice($externalChanges, 0, $this->output->isVerbose() ? count($externalChanges) : 5) as $file) {
|
||||
$this->output->writeln(sprintf(' <fg=gray>%s</>', $file));
|
||||
}
|
||||
|
||||
if ($this->canRebuildGraph()) {
|
||||
$this->deleteState(self::KEY_GRAPH);
|
||||
$this->deleteState(self::KEY_COVERAGE_CACHE);
|
||||
|
||||
$this->freshGraphReason = 'code this project loads from outside its root changed';
|
||||
|
||||
return $this->enterRecordMode($arguments);
|
||||
}
|
||||
|
||||
$this->requestWorkerResults();
|
||||
|
||||
if ($this->scoped) {
|
||||
$this->renderChild('Running the selected tests directly — the dependency graph only reaches files under the project root.');
|
||||
$this->renderChild('Run a plain --tia run to record a fresh dependency graph.');
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$this->renderChild('Running the full suite — the dependency graph only reaches files under the project root.');
|
||||
|
||||
if ($this->piggybackCoverage) {
|
||||
$this->renderChild('Run --tia without --coverage to record a fresh dependency graph.');
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$this->fullSuiteFallbackRan = true;
|
||||
|
||||
$this->renderChild('Install / enable pcov or xdebug (mode: coverage) so edges can be safely refreshed after changes outside the project root.');
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$phpChangesOutsideProject = $this->phpFiles($outsideProject);
|
||||
|
||||
if ($phpChangesOutsideProject !== []) {
|
||||
return $this->runFullSuiteForPhpChangesOutsideProject($phpChangesOutsideProject, $arguments);
|
||||
}
|
||||
|
||||
$changed = $changedFiles->filterUnchangedSinceLastRun(
|
||||
$changed,
|
||||
$graph->lastRunTree($this->branch),
|
||||
);
|
||||
|
||||
$hasProjectPhpSourceChanges = $this->hasProjectPhpSourceChanges($changed);
|
||||
$coverageAvailable = $this->piggybackCoverage || $this->recorder->driverAvailable();
|
||||
|
||||
@@ -1137,7 +1414,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$this->requestWorkerResults();
|
||||
|
||||
$this->renderBadge('WARN', 'Detected PHP source changes but no coverage driver is available.');
|
||||
$this->renderChild('Running the full suite to avoid using a stale dependency graph.');
|
||||
$this->renderChild($this->runningScope().' to avoid using a stale dependency graph.');
|
||||
$this->renderChild('Install / enable pcov or xdebug (mode: coverage) so edges can be safely refreshed after PHP refactors.');
|
||||
|
||||
return $arguments;
|
||||
@@ -1165,7 +1442,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$this->reportAffectedSummary($changed, $affectedFromChanges, $rerunFromCache, $affected, $outsideProject);
|
||||
|
||||
$affectedSet = array_fill_keys($affected, true);
|
||||
$canRefreshReplayEdges = $affected !== [] && $coverageAvailable;
|
||||
$canRefreshReplayEdges = $coverageAvailable && ! $this->scoped;
|
||||
|
||||
$this->replayRan = true;
|
||||
$this->replayGraph = $graph;
|
||||
@@ -1185,10 +1462,12 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
if (! Parallel::isEnabled()) {
|
||||
if ($canRefreshReplayEdges) {
|
||||
$this->recorder->recordOnly($this->refreshesEdgesOf(...));
|
||||
|
||||
if ($this->piggybackCoverage) {
|
||||
$this->recorder->activateLinkTracking();
|
||||
} else {
|
||||
$this->recorder->activate();
|
||||
$this->recorder->activate($this->configuration);
|
||||
}
|
||||
|
||||
$this->recordingActive = true;
|
||||
@@ -1330,7 +1609,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$this->writesSuppressed = true;
|
||||
|
||||
$this->renderPhpChangesOutsideProject($uncommittedPhpChanges);
|
||||
$this->renderChild('Running the full suite, and recording nothing — the project may load that code, and git stops reporting an uncommitted edit once it is undone.');
|
||||
$this->renderChild($this->runningScope().', and recording nothing — the project may load that code, and git stops reporting an uncommitted edit once it is undone.');
|
||||
$this->renderChild('Commit what you changed there to let a run leave a baseline behind.');
|
||||
}
|
||||
|
||||
@@ -1354,6 +1633,13 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
$this->requestWorkerResults();
|
||||
|
||||
if ($this->scoped) {
|
||||
$this->renderChild('Running the selected tests directly — the project may load that code, and a partial run cannot refresh the dependency graph.');
|
||||
$this->renderChild('Run a plain --tia run to record a fresh dependency graph.');
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
if ($this->piggybackCoverage) {
|
||||
$this->renderChild('Running the full suite — the project may load that code, and a coverage run cannot refresh the dependency graph.');
|
||||
$this->renderChild('Run --tia without --coverage to record a fresh dependency graph.');
|
||||
@@ -1448,7 +1734,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
}
|
||||
|
||||
if (! $this->piggybackCoverage && ! in_array('--no-coverage', $arguments, true)) {
|
||||
$arguments[] = '--no-coverage';
|
||||
$arguments = $this->pushArgument('--no-coverage', $arguments);
|
||||
}
|
||||
|
||||
if (Parallel::isEnabled()) {
|
||||
@@ -1476,7 +1762,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$recorder->activate();
|
||||
$recorder->activate($this->configuration);
|
||||
$this->recordingActive = true;
|
||||
|
||||
if ($this->driftLabel !== null || $this->freshGraphReason !== null) {
|
||||
@@ -1493,7 +1779,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
private function canRebuildGraph(): bool
|
||||
{
|
||||
return ! $this->piggybackCoverage && $this->recorder->driverAvailable();
|
||||
return ! $this->scoped && ! $this->piggybackCoverage && $this->recorder->driverAvailable();
|
||||
}
|
||||
|
||||
private function renderFreshGraph(): void
|
||||
@@ -1534,6 +1820,53 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$this->renderChild('Record the baseline with a plain --tia run first; coverage runs then reuse it.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function runSelectionDirectly(array $arguments): array
|
||||
{
|
||||
$this->requestWorkerResults();
|
||||
|
||||
if ($this->announcesPartialRun) {
|
||||
$this->output->writeln('');
|
||||
$this->renderChild('TIA does not apply to partial runs — running the selected tests directly.');
|
||||
}
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $drift
|
||||
* @param array<int, string> $arguments
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function runSelectionLeavingTheGraph(array $drift, array $arguments): array
|
||||
{
|
||||
$this->writesSuppressed = true;
|
||||
|
||||
$this->renderBadge('WARN', sprintf(
|
||||
'The graph was recorded in a different environment (%s).',
|
||||
implode(', ', $drift),
|
||||
));
|
||||
$this->renderChild('Running the selected tests directly, and recording nothing — a plain --tia run records the graph again.');
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
private function runningScope(): string
|
||||
{
|
||||
return $this->scoped ? 'Running the selected tests directly' : 'Running the full suite';
|
||||
}
|
||||
|
||||
private function emitScopedRecordSkipped(): void
|
||||
{
|
||||
$this->output->writeln('');
|
||||
|
||||
$this->renderChild('Running the selected tests directly, as a partial run cannot record the dependency graph of the whole suite.');
|
||||
$this->renderChild('Record the baseline with a plain --tia run first; partial runs then replay it.');
|
||||
}
|
||||
|
||||
private function emitMutationScopedRecordSkipped(): void
|
||||
{
|
||||
$this->output->writeln('');
|
||||
@@ -1765,7 +2098,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return [
|
||||
array_map(array_keys(...), $merged['files']),
|
||||
array_map(static fn (array $tables): array => array_map(strval(...), array_keys($tables)), $merged['tables']),
|
||||
array_map(array_keys(...), $merged['inertia']),
|
||||
array_map(Arr::stringKeys(...), $merged['inertia']),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1873,12 +2206,20 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->externalSourcesChangedDuringRun($projectRoot)) {
|
||||
$this->renderExternalSourcesChangedDuringRun('keeping the baseline from before the run');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($currentSha !== null) {
|
||||
$graph->setRecordedAtSha($this->branch, $currentSha);
|
||||
}
|
||||
|
||||
$workingTreeFiles = $changedFiles->since($currentSha) ?? [];
|
||||
$graph->setLastRunTree($this->branch, $changedFiles->snapshotTree($workingTreeFiles));
|
||||
$graph->setLastRunTree(
|
||||
$this->branch,
|
||||
$changedFiles->baselineTree($currentSha, ExternalSources::ignoredInputs($projectRoot, $this->originalArguments)),
|
||||
);
|
||||
|
||||
$this->saveGraph($graph);
|
||||
}
|
||||
@@ -1954,7 +2295,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
);
|
||||
}
|
||||
|
||||
$graph->markKnownTestFiles(array_keys($touchedFiles));
|
||||
$graph->markKnownTestFiles(array_values(array_filter(array_keys($touchedFiles), $this->refreshesEdgesOf(...))));
|
||||
$graph->pruneStaleResults($this->branch, array_keys($touchedFiles), array_keys($results));
|
||||
$this->reclaim($graph);
|
||||
|
||||
@@ -1970,7 +2311,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$graph->pruneMissingTests();
|
||||
$graph->pruneResultsForMissingFiles($this->branch);
|
||||
|
||||
$branches = new ChangedFiles(TestSuite::getInstance()->rootPath)->branchNames();
|
||||
try {
|
||||
$branches = new ChangedFiles(TestSuite::getInstance()->rootPath)->branchNames();
|
||||
} catch (GitTimedOut) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($branches === null) {
|
||||
return;
|
||||
@@ -2002,9 +2347,18 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->externalSourcesChangedDuringRun($projectRoot)
|
||||
|| ExternalSources::unverifiable($projectRoot, $this->originalArguments) !== []) {
|
||||
$collector->reset();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->resolveBranch($projectRoot);
|
||||
} catch (MissingDependency|TiaGitFailed) {
|
||||
} catch (MissingDependency) {
|
||||
} catch (TiaGitFailed|GitTimedOut) {
|
||||
return;
|
||||
}
|
||||
|
||||
$graph->setFallbackBranch($this->fallbackBranch);
|
||||
@@ -2042,7 +2396,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
}
|
||||
|
||||
if ($markKnownTestFiles) {
|
||||
$graph->markKnownTestFiles(array_keys($touchedFiles));
|
||||
$graph->markKnownTestFiles(array_values(array_filter(array_keys($touchedFiles), $this->refreshesEdgesOf(...))));
|
||||
}
|
||||
|
||||
if ($complete) {
|
||||
@@ -2165,8 +2519,6 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return;
|
||||
}
|
||||
|
||||
$this->branchResolved = true;
|
||||
|
||||
$changedFiles = new ChangedFiles($projectRoot);
|
||||
|
||||
$resolved = $this->resolveFallbackBranch($changedFiles);
|
||||
@@ -2179,6 +2531,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$this->branch = $changedFiles->currentBranch()
|
||||
?? CiBranch::detectCurrent()
|
||||
?? $this->workspaceBranch($projectRoot);
|
||||
|
||||
$this->branchResolved = true;
|
||||
}
|
||||
|
||||
private function workspaceBranch(string $projectRoot): string
|
||||
@@ -2389,6 +2743,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
'pest_factory' => 'Pest internals',
|
||||
'pest_method_factory' => 'Pest internals',
|
||||
'project_prefix' => 'project location in the repository',
|
||||
'external_roots' => 'the roots this project loads from outside itself',
|
||||
'include_path' => 'the include path',
|
||||
];
|
||||
|
||||
$seen = [];
|
||||
@@ -2412,7 +2768,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
$git = new Git($projectRoot);
|
||||
|
||||
$baseline = $git->show($sha, $git->pathPrefix().'composer.lock');
|
||||
try {
|
||||
$baseline = $git->show($sha, $git->pathPrefix().'composer.lock');
|
||||
} catch (GitTimedOut) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($baseline === null) {
|
||||
return '';
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace Pest\Plugins\Tia;
|
||||
|
||||
use Pest\Exceptions\MissingDependency;
|
||||
use Pest\Exceptions\TiaGitFailed;
|
||||
use Pest\Support\Arr;
|
||||
use Pest\Support\Git;
|
||||
use Symfony\Component\Process\ExecutableFinder;
|
||||
|
||||
@@ -76,17 +77,17 @@ final class ChangedFiles
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function outsideProject(): array
|
||||
public function outsideProjectDirty(): array
|
||||
{
|
||||
return array_map(strval(...), array_keys($this->outsideProject));
|
||||
return Arr::stringKeys($this->outsideProjectDirty);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function outsideProjectDirty(): array
|
||||
public function outsideProject(): array
|
||||
{
|
||||
return array_map(strval(...), array_keys($this->outsideProjectDirty));
|
||||
return Arr::stringKeys($this->outsideProject);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,13 +103,13 @@ final class ChangedFiles
|
||||
|
||||
$candidates = array_fill_keys($files, true);
|
||||
|
||||
foreach (array_keys($lastRunTree) as $snapshotted) {
|
||||
foreach (Arr::stringKeys($lastRunTree) as $snapshotted) {
|
||||
$candidates[$snapshotted] = true;
|
||||
}
|
||||
|
||||
$remaining = [];
|
||||
|
||||
foreach (array_keys($candidates) as $file) {
|
||||
foreach (Arr::stringKeys($candidates) as $file) {
|
||||
$snapshot = $lastRunTree[$file] ?? null;
|
||||
$current = $this->currentHash($file);
|
||||
|
||||
@@ -120,6 +121,100 @@ final class ChangedFiles
|
||||
return $remaining;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $repositoryRelativeInputs
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function baselineTree(?string $sha, array $repositoryRelativeInputs): array
|
||||
{
|
||||
return $this->snapshotTree([...($this->since($sha) ?? []), ...$this->externalKeys($repositoryRelativeInputs)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $repositoryRelativeInputs
|
||||
* @param array<int, string> $repositoryRelativeRepositories
|
||||
* @param array<int, string> $repositoryRelativeUnlisted
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function externalInputHashes(array $repositoryRelativeInputs, array $repositoryRelativeRepositories = [], array $repositoryRelativeUnlisted = []): array
|
||||
{
|
||||
$hashes = $this->snapshotTree($this->externalKeys($repositoryRelativeInputs));
|
||||
|
||||
foreach ($this->externalKeys($repositoryRelativeRepositories) as $key) {
|
||||
$hashes[$key] = 'repository';
|
||||
}
|
||||
|
||||
foreach ($this->externalKeys($repositoryRelativeUnlisted) as $key) {
|
||||
$hashes[$key] = 'unlisted';
|
||||
}
|
||||
|
||||
return $hashes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $before
|
||||
* @param array<string, string> $after
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function changedExternalInputs(array $before, array $after): array
|
||||
{
|
||||
$parent = $this->parentPath();
|
||||
$changed = [];
|
||||
|
||||
foreach (Arr::stringKeys([...$before, ...$after]) as $key) {
|
||||
if (($before[$key] ?? null) !== ($after[$key] ?? null)) {
|
||||
$changed[] = $parent !== '' && str_starts_with($key, $parent) ? substr($key, strlen($parent)) : $key;
|
||||
}
|
||||
}
|
||||
|
||||
sort($changed);
|
||||
|
||||
return $changed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $files
|
||||
* @param array<int, string> $repositoryRelativeInputs
|
||||
* @param array<string, string> $lastRunTree
|
||||
* @return array{0: array<int, string>, 1: array<int, string>}
|
||||
*/
|
||||
public function changedSinceLastRun(array $files, array $repositoryRelativeInputs, array $lastRunTree): array
|
||||
{
|
||||
$parent = $this->parentPath();
|
||||
$projectFiles = [];
|
||||
$externalInputsChanged = [];
|
||||
|
||||
foreach ($this->filterUnchangedSinceLastRun([...$files, ...$this->externalKeys($repositoryRelativeInputs)], $lastRunTree) as $file) {
|
||||
if ($parent !== '' && str_starts_with($file, $parent)) {
|
||||
$externalInputsChanged[] = substr($file, strlen($parent));
|
||||
} else {
|
||||
$projectFiles[] = $file;
|
||||
}
|
||||
}
|
||||
|
||||
return [$projectFiles, $externalInputsChanged];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $repositoryRelativeInputs
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function externalKeys(array $repositoryRelativeInputs): array
|
||||
{
|
||||
$parent = $this->parentPath();
|
||||
|
||||
if ($parent === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_map(static fn (string $input): string => $parent.$input, $repositoryRelativeInputs);
|
||||
}
|
||||
|
||||
private function parentPath(): string
|
||||
{
|
||||
return str_repeat('../', substr_count($this->gitPrefix(), '/'));
|
||||
}
|
||||
|
||||
private function currentHash(string $relativePath): ?string
|
||||
{
|
||||
$absolute = $this->projectRoot.DIRECTORY_SEPARATOR.$relativePath;
|
||||
@@ -128,11 +223,22 @@ final class ChangedFiles
|
||||
return null;
|
||||
}
|
||||
|
||||
$hash = ContentHash::of($absolute);
|
||||
$hash = $this->hashOf($relativePath, $absolute);
|
||||
|
||||
return $hash === false ? null : $hash;
|
||||
}
|
||||
|
||||
private function hashOf(string $relativePath, string $absolute): string|false
|
||||
{
|
||||
$parent = $this->parentPath();
|
||||
|
||||
if ($parent !== '' && str_starts_with($relativePath, $parent)) {
|
||||
return @hash_file('xxh128', $absolute);
|
||||
}
|
||||
|
||||
return ContentHash::of($absolute);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $files
|
||||
* @return array<string, string> path → xxh128 content hash
|
||||
@@ -150,7 +256,7 @@ final class ChangedFiles
|
||||
continue;
|
||||
}
|
||||
|
||||
$hash = ContentHash::of($absolute);
|
||||
$hash = $this->hashOf($file, $absolute);
|
||||
|
||||
if ($hash !== false) {
|
||||
$out[$file] = $hash;
|
||||
@@ -189,7 +295,7 @@ final class ChangedFiles
|
||||
$unique[$file] = true;
|
||||
}
|
||||
|
||||
$candidates = array_keys($this->filterIgnored($unique));
|
||||
$candidates = Arr::stringKeys($this->filterIgnored($unique));
|
||||
|
||||
$this->filterIgnoredOutsideProject();
|
||||
|
||||
@@ -206,36 +312,47 @@ final class ChangedFiles
|
||||
*/
|
||||
private function filterBehaviourallyUnchanged(array $files, string $sha): array
|
||||
{
|
||||
$remaining = [];
|
||||
$files = array_values($files);
|
||||
$currentHashes = array_map($this->currentHash(...), $files);
|
||||
$present = array_filter($currentHashes, static fn (?string $hash): bool => $hash !== null);
|
||||
$indexes = array_keys($present);
|
||||
$matches = $this->matchesAtSha($sha, array_map(static fn (int $index): string => $files[$index], $indexes), array_values($present));
|
||||
$unchanged = [];
|
||||
|
||||
foreach ($files as $file) {
|
||||
$currentHash = $this->currentHash($file);
|
||||
|
||||
if ($currentHash === null) {
|
||||
$remaining[] = $file;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$baselineContent = $this->contentAtSha($sha, $file);
|
||||
|
||||
if ($baselineContent === null) {
|
||||
$remaining[] = $file;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($currentHash !== ContentHash::ofContent($file, $baselineContent)) {
|
||||
$remaining[] = $file;
|
||||
foreach ($indexes as $position => $index) {
|
||||
if ($matches[$position] ?? false) {
|
||||
$unchanged[$index] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $remaining;
|
||||
return array_values(array_filter($files, static fn (int $index): bool => ! isset($unchanged[$index]), ARRAY_FILTER_USE_KEY));
|
||||
}
|
||||
|
||||
private function contentAtSha(string $sha, string $path): ?string
|
||||
/**
|
||||
* @param list<string> $paths
|
||||
* @param list<string> $hashes
|
||||
* @return array<int, bool>
|
||||
*/
|
||||
private function matchesAtSha(string $sha, array $paths, array $hashes): array
|
||||
{
|
||||
return $this->git->show($sha, $this->gitPrefix().$path);
|
||||
if ($paths === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$matches = [];
|
||||
$compare = static function (int $position, ?string $content) use (&$matches, $paths, $hashes): void {
|
||||
$matches[$position] = $content !== null && $hashes[$position] === ContentHash::ofContent($paths[$position], $content);
|
||||
};
|
||||
|
||||
$repositoryPaths = array_map(fn (string $path): string => $this->gitPrefix().$path, $paths);
|
||||
|
||||
if (! $this->scan()->showEach($sha, $repositoryPaths, $compare)) {
|
||||
foreach ($repositoryPaths as $position => $path) {
|
||||
$compare($position, $this->git->show($sha, $path));
|
||||
}
|
||||
}
|
||||
|
||||
return $matches;
|
||||
}
|
||||
|
||||
private function filterIgnoredOutsideProject(): void
|
||||
@@ -275,25 +392,14 @@ final class ChangedFiles
|
||||
return $candidates;
|
||||
}
|
||||
|
||||
$result = $git->result(
|
||||
['check-ignore', '-z', '--stdin'],
|
||||
implode("\x00", array_keys($candidates)),
|
||||
);
|
||||
$result = $git->checkIgnore(Arr::stringKeys($candidates));
|
||||
|
||||
if ($result['exitCode'] !== 0 && $result['exitCode'] !== 1) {
|
||||
throw $this->gitFailure($result);
|
||||
throw $this->gitFailure(['exitCode' => $result['exitCode'], 'output' => '', 'errorOutput' => $result['errorOutput']]);
|
||||
}
|
||||
|
||||
$output = $result['output'];
|
||||
|
||||
if ($output === '') {
|
||||
return $candidates;
|
||||
}
|
||||
|
||||
foreach (explode("\x00", rtrim($output, "\x00")) as $ignored) {
|
||||
if ($ignored !== '') {
|
||||
unset($candidates[$ignored]);
|
||||
}
|
||||
foreach ($result['ignored'] as $ignored) {
|
||||
unset($candidates[$ignored]);
|
||||
}
|
||||
|
||||
return $candidates;
|
||||
@@ -374,7 +480,7 @@ final class ChangedFiles
|
||||
}
|
||||
}
|
||||
|
||||
return array_keys($names);
|
||||
return Arr::stringKeys($names);
|
||||
}
|
||||
|
||||
public function hasRemote(): bool
|
||||
|
||||
@@ -4,9 +4,20 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use PHPUnit\Event\Dispatcher;
|
||||
use PHPUnit\Event\DispatchingEmitter;
|
||||
use PHPUnit\Event\Emitter;
|
||||
use PHPUnit\Event\Event;
|
||||
use PHPUnit\Event\Facade as EventFacade;
|
||||
use PHPUnit\Event\Telemetry\System;
|
||||
use PHPUnit\Event\Telemetry\SystemCpuTimeMeter;
|
||||
use PHPUnit\Event\Telemetry\SystemGarbageCollectorStatusProvider;
|
||||
use PHPUnit\Event\Telemetry\SystemMemoryMeter;
|
||||
use PHPUnit\Event\Telemetry\SystemStopWatch;
|
||||
use PHPUnit\TextUI\CliArguments\Builder;
|
||||
use PHPUnit\TextUI\CliArguments\XmlConfigurationFileFinder;
|
||||
use PHPUnit\TextUI\XmlConfiguration\DefaultConfiguration;
|
||||
use PHPUnit\TextUI\XmlConfiguration\Loader;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@@ -18,16 +29,18 @@ final readonly class ConfigurationFile
|
||||
|
||||
private const array DEFAULT_NAMES = ['phpunit.xml', 'phpunit.dist.xml', 'phpunit.xml.dist'];
|
||||
|
||||
private const array VALUE_OPTIONS = ['--configuration', '--bootstrap', '--include-path'];
|
||||
private const array VALUE_OPTIONS = ['--configuration', '--bootstrap', '--include-path', '--coverage-filter'];
|
||||
|
||||
/**
|
||||
* @param list<string>|null $includePaths
|
||||
* @param list<string> $coverageFilter
|
||||
*/
|
||||
private function __construct(
|
||||
private ?string $path,
|
||||
private bool $suppressed,
|
||||
private ?string $bootstrap = null,
|
||||
private ?array $includePaths = null,
|
||||
private array $coverageFilter = [],
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -45,19 +58,20 @@ final readonly class ConfigurationFile
|
||||
$includePaths = $configuration->hasIncludePath()
|
||||
? array_map(self::resolved(...), explode(PATH_SEPARATOR, $configuration->includePath()))
|
||||
: null;
|
||||
$coverageFilter = $configuration->hasCoverageFilter() ? $configuration->coverageFilter() : [];
|
||||
|
||||
if (! $configuration->hasConfigurationFile() && ! $configuration->useDefaultConfiguration()) {
|
||||
return new self(null, true, $bootstrap, $includePaths);
|
||||
return new self(null, true, $bootstrap, $includePaths, $coverageFilter);
|
||||
}
|
||||
|
||||
$file = new XmlConfigurationFileFinder()->find($configuration);
|
||||
$path = $file === false ? false : realpath($file);
|
||||
|
||||
if ($path !== false && $generatedPath !== null && $path === realpath($generatedPath)) {
|
||||
return new self(null, false, $bootstrap, $includePaths);
|
||||
return new self(null, false, $bootstrap, $includePaths, $coverageFilter);
|
||||
}
|
||||
|
||||
return new self($path === false ? null : $path, false, $bootstrap, $includePaths);
|
||||
return new self($path === false ? null : $path, false, $bootstrap, $includePaths, $coverageFilter);
|
||||
}
|
||||
|
||||
public static function at(string $path): self
|
||||
@@ -70,6 +84,23 @@ final readonly class ConfigurationFile
|
||||
return new self(null, false);
|
||||
}
|
||||
|
||||
public function sourceScope(string $projectRoot): ?SourceScope
|
||||
{
|
||||
$path = $this->suppressed ? null : ($this->path ?? $this->defaultIn($projectRoot));
|
||||
|
||||
if ($path === null) {
|
||||
return SourceScope::fromSource($projectRoot, DefaultConfiguration::create()->source(), $this->coverageFilter);
|
||||
}
|
||||
|
||||
try {
|
||||
$source = new Loader($this->silentEmitter())->load($path)->source();
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return SourceScope::fromSource($projectRoot, $source, $this->coverageFilter);
|
||||
}
|
||||
|
||||
public function bootstrapFingerprint(string $projectRoot): ?string
|
||||
{
|
||||
return $this->bootstrap === null ? null : $this->relativeTo($projectRoot, $this->bootstrap);
|
||||
@@ -174,6 +205,22 @@ final readonly class ConfigurationFile
|
||||
return $argument;
|
||||
}
|
||||
|
||||
private function silentEmitter(): Emitter
|
||||
{
|
||||
return new DispatchingEmitter(
|
||||
new class implements Dispatcher
|
||||
{
|
||||
public function dispatch(Event $event): void {}
|
||||
},
|
||||
new System(
|
||||
new SystemStopWatch,
|
||||
new SystemMemoryMeter,
|
||||
new SystemGarbageCollectorStatusProvider,
|
||||
new SystemCpuTimeMeter,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private function withForwardSlashes(string $path): string
|
||||
{
|
||||
return DIRECTORY_SEPARATOR === '\\' ? str_replace('\\', '/', $path) : $path;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use Pest\Exceptions\GitTimedOut;
|
||||
use Pest\Plugins\Tia\Contracts\Lockfile;
|
||||
use Pest\Support\Git;
|
||||
use Symfony\Component\Process\Exception\ExceptionInterface as ProcessException;
|
||||
@@ -23,12 +24,13 @@ final readonly class Fingerprint
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
* @return array{
|
||||
* structural: array<string, int|string|null>,
|
||||
* environmental: array<string, int|string|null>,
|
||||
* }
|
||||
*/
|
||||
public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null): array
|
||||
public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null, array $arguments = []): array
|
||||
{
|
||||
$configuration ??= ConfigurationFile::projectDefault();
|
||||
|
||||
@@ -48,6 +50,18 @@ final readonly class Fingerprint
|
||||
$structural['project_prefix'] = $prefix;
|
||||
}
|
||||
|
||||
$externalRoots = ExternalSources::rootsFor($projectRoot, $arguments);
|
||||
|
||||
if ($externalRoots !== []) {
|
||||
$structural['external_roots'] = hash('xxh128', serialize($externalRoots));
|
||||
}
|
||||
|
||||
$includePaths = ExternalSources::includePaths($projectRoot, $arguments);
|
||||
|
||||
if ($includePaths !== []) {
|
||||
$structural['include_path'] = hash('xxh128', serialize($includePaths));
|
||||
}
|
||||
|
||||
return [
|
||||
'structural' => $structural,
|
||||
'environmental' => [
|
||||
@@ -302,10 +316,12 @@ final readonly class Fingerprint
|
||||
}
|
||||
|
||||
try {
|
||||
return $cache[$key] = ! new Git($projectRoot)->succeeds(['check-ignore', '-q', '--', $relativePath]);
|
||||
} catch (ProcessException) {
|
||||
$result = new Git($projectRoot)->checkIgnore([$relativePath]);
|
||||
} catch (ProcessException|GitTimedOut) {
|
||||
return $cache[$key] = true;
|
||||
}
|
||||
|
||||
return $cache[$key] = $result['exitCode'] !== 0;
|
||||
}
|
||||
|
||||
private static function projectPrefix(string $projectRoot): string
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace Pest\Plugins\Tia;
|
||||
use JsonException;
|
||||
use Pest\Factories\TestCaseFactory;
|
||||
use Pest\Factories\TestCaseMethodFactory;
|
||||
use Pest\Support\Arr;
|
||||
use Pest\Support\Container;
|
||||
use Pest\Support\View;
|
||||
use Pest\TestSuite;
|
||||
@@ -594,7 +595,7 @@ final class Graph
|
||||
{
|
||||
$generated = [];
|
||||
|
||||
foreach ($this->fileIds as $path => $id) {
|
||||
foreach ($this->files as $id => $path) {
|
||||
$hash = $this->livewireGeneratedHash($path);
|
||||
|
||||
if ($hash === null) {
|
||||
@@ -1131,7 +1132,7 @@ final class Graph
|
||||
}
|
||||
}
|
||||
|
||||
$names = array_keys($normalised);
|
||||
$names = Arr::stringKeys($normalised);
|
||||
sort($names);
|
||||
|
||||
$this->testInertiaComponents[$testRel] = $names;
|
||||
@@ -1161,7 +1162,7 @@ final class Graph
|
||||
continue;
|
||||
}
|
||||
|
||||
$keys = array_keys($names);
|
||||
$keys = Arr::stringKeys($names);
|
||||
sort($keys);
|
||||
$out[$path] = $keys;
|
||||
}
|
||||
@@ -1645,7 +1646,7 @@ final class Graph
|
||||
{
|
||||
$survivors = array_fill_keys($keep, true);
|
||||
|
||||
foreach (array_keys($this->baselines) as $branch) {
|
||||
foreach (Arr::stringKeys($this->baselines) as $branch) {
|
||||
if (str_starts_with($branch, self::WORKSPACE_BRANCH_PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
@@ -1711,8 +1712,8 @@ final class Graph
|
||||
|
||||
$branches = [];
|
||||
|
||||
foreach (array_keys($data['baselines']) as $branch) {
|
||||
if (is_string($branch) && $branch !== '') {
|
||||
foreach (Arr::stringKeys($data['baselines']) as $branch) {
|
||||
if ($branch !== '') {
|
||||
$branches[] = $branch;
|
||||
}
|
||||
}
|
||||
@@ -1847,8 +1848,8 @@ final class Graph
|
||||
|
||||
if (is_array($baseline['tree'] ?? null)) {
|
||||
foreach ($baseline['tree'] as $path => $hash) {
|
||||
if (is_string($path) && is_string($hash)) {
|
||||
$tree[$path] = $hash;
|
||||
if (is_string($hash)) {
|
||||
$tree[(string) $path] = $hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,7 +314,7 @@ final class ReadCapture
|
||||
*/
|
||||
private function openNatively(string $path, string $mode, int $options): mixed
|
||||
{
|
||||
return ($options & STREAM_REPORT_ERRORS) !== 0
|
||||
return ($options & (STREAM_REPORT_ERRORS | self::STREAM_OPEN_FOR_INCLUDE)) !== 0
|
||||
? fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0, $this->context)
|
||||
: @fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0, $this->context);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use Closure;
|
||||
use Pest\Support\Arr;
|
||||
use Pest\Support\Container;
|
||||
use Pest\TestSuite;
|
||||
use ReflectionClass;
|
||||
@@ -45,10 +47,19 @@ final class Recorder
|
||||
|
||||
private ?SourceScope $sourceScope = null;
|
||||
|
||||
public function activate(): void
|
||||
private bool $coverageFilterApplied = false;
|
||||
|
||||
/** @var (Closure(string): bool)|null */
|
||||
private ?Closure $recordsTestFile = null;
|
||||
|
||||
public function activate(?ConfigurationFile $configuration = null): void
|
||||
{
|
||||
$this->active = true;
|
||||
$this->captureCoverage = true;
|
||||
|
||||
if ($configuration instanceof ConfigurationFile) {
|
||||
$this->restrictCoverageToSourceScope($configuration);
|
||||
}
|
||||
}
|
||||
|
||||
public function activateLinkTracking(): void
|
||||
@@ -56,6 +67,14 @@ final class Recorder
|
||||
$this->active = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Closure(string): bool $recordsTestFile
|
||||
*/
|
||||
public function recordOnly(Closure $recordsTestFile): void
|
||||
{
|
||||
$this->recordsTestFile = $recordsTestFile;
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->active;
|
||||
@@ -102,6 +121,10 @@ final class Recorder
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->recordsTestFile instanceof Closure && ! ($this->recordsTestFile)($file)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->currentTestFile = $file;
|
||||
|
||||
if ($this->watchPatterns()->isReadCaptureEnabled()) {
|
||||
@@ -329,7 +352,7 @@ final class Recorder
|
||||
$out = [];
|
||||
|
||||
foreach ($this->perTestInertiaComponents as $testFile => $components) {
|
||||
$names = array_keys($components);
|
||||
$names = Arr::stringKeys($components);
|
||||
sort($names);
|
||||
$out[$testFile] = $names;
|
||||
}
|
||||
@@ -410,6 +433,30 @@ final class Recorder
|
||||
return $out;
|
||||
}
|
||||
|
||||
private function restrictCoverageToSourceScope(ConfigurationFile $configuration): void
|
||||
{
|
||||
if ($this->coverageFilterApplied || ! $this->driverAvailable() || $this->driver !== 'xdebug') {
|
||||
return;
|
||||
}
|
||||
|
||||
$projectRoot = TestSuite::getInstance()->rootPath;
|
||||
$scope = $configuration->sourceScope($projectRoot);
|
||||
|
||||
if (! $scope instanceof SourceScope) {
|
||||
return;
|
||||
}
|
||||
|
||||
$excludedPaths = $scope->coverageExcludePaths($projectRoot);
|
||||
|
||||
if ($excludedPaths === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
\xdebug_set_filter(\XDEBUG_FILTER_CODE_COVERAGE, \XDEBUG_PATH_EXCLUDE, $excludedPaths);
|
||||
|
||||
$this->coverageFilterApplied = true;
|
||||
}
|
||||
|
||||
private function sourceScope(): SourceScope
|
||||
{
|
||||
return $this->sourceScope ??= SourceScope::fromProjectRoot(TestSuite::getInstance()->rootPath);
|
||||
@@ -419,6 +466,11 @@ final class Recorder
|
||||
{
|
||||
ReadCapture::stop();
|
||||
|
||||
if ($this->coverageFilterApplied) {
|
||||
\xdebug_set_filter(\XDEBUG_FILTER_CODE_COVERAGE, \XDEBUG_FILTER_NONE, []);
|
||||
$this->coverageFilterApplied = false;
|
||||
}
|
||||
|
||||
$this->currentTestFile = null;
|
||||
$this->perTestFiles = [];
|
||||
$this->perTestTables = [];
|
||||
@@ -427,6 +479,7 @@ final class Recorder
|
||||
$this->classFileCache = [];
|
||||
$this->classUsesDatabaseCache = [];
|
||||
$this->sourceScope = null;
|
||||
$this->recordsTestFile = null;
|
||||
$this->active = false;
|
||||
$this->captureCoverage = false;
|
||||
}
|
||||
|
||||
+121
-16
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use PHPUnit\TextUI\Configuration\Registry;
|
||||
use PHPUnit\TextUI\Configuration\Source;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@@ -33,6 +34,14 @@ final class SourceScope
|
||||
'bootstrap/cache',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function noiseDirectories(): array
|
||||
{
|
||||
return [...self::TOP_LEVEL_NOISE, ...self::NESTED_NOISE];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $includes Absolute, normalised directory paths.
|
||||
* @param list<array{path: string, prefix: string, suffix: string}> $excludes Absolute, normalised directory paths with the file name prefix and suffix they apply to.
|
||||
@@ -44,27 +53,44 @@ final class SourceScope
|
||||
|
||||
public static function fromProjectRoot(string $projectRoot): self
|
||||
{
|
||||
$phpunitIncludes = [];
|
||||
$phpunitExcludes = [];
|
||||
|
||||
try {
|
||||
$source = Registry::get()->source();
|
||||
|
||||
foreach ($source->includeDirectories() as $dir) {
|
||||
$phpunitIncludes[] = self::normalise($dir->path());
|
||||
}
|
||||
|
||||
foreach ($source->excludeDirectories() as $dir) {
|
||||
$phpunitExcludes[] = [
|
||||
'path' => self::normalise(@realpath($dir->path()) ?: $dir->path()),
|
||||
'prefix' => $dir->prefix(),
|
||||
'suffix' => $dir->suffix(),
|
||||
];
|
||||
}
|
||||
} catch (Throwable) {
|
||||
//
|
||||
return self::build($projectRoot, [], []);
|
||||
}
|
||||
|
||||
return self::fromSource($projectRoot, $source, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $coverageFilter
|
||||
*/
|
||||
public static function fromSource(string $projectRoot, Source $source, array $coverageFilter): self
|
||||
{
|
||||
$phpunitIncludes = array_map(self::normalise(...), $coverageFilter);
|
||||
$phpunitExcludes = [];
|
||||
|
||||
foreach ($source->includeDirectories() as $dir) {
|
||||
$phpunitIncludes[] = self::normalise($dir->path());
|
||||
}
|
||||
|
||||
foreach ($source->excludeDirectories() as $dir) {
|
||||
$phpunitExcludes[] = [
|
||||
'path' => self::normalise(@realpath($dir->path()) ?: $dir->path()),
|
||||
'prefix' => $dir->prefix(),
|
||||
'suffix' => $dir->suffix(),
|
||||
];
|
||||
}
|
||||
|
||||
return self::build($projectRoot, $phpunitIncludes, $phpunitExcludes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $phpunitIncludes
|
||||
* @param list<array{path: string, prefix: string, suffix: string}> $phpunitExcludes
|
||||
*/
|
||||
private static function build(string $projectRoot, array $phpunitIncludes, array $phpunitExcludes): self
|
||||
{
|
||||
$rootIncludes = self::topLevelProjectDirs($projectRoot);
|
||||
|
||||
$includes = array_values(array_unique([...$phpunitIncludes, ...$rootIncludes]));
|
||||
@@ -104,6 +130,30 @@ final class SourceScope
|
||||
return array_values(array_unique($out));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function coverageExcludePaths(string $projectRoot): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach (self::noiseDirectories() as $relative) {
|
||||
$real = @realpath($projectRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative));
|
||||
|
||||
if ($real === false || ! is_dir($real)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$directory = self::normalise($real);
|
||||
|
||||
if ($this->rejectsEveryFileIn($directory) && ! $this->hasCaseTwin($directory)) {
|
||||
$out[] = $directory.DIRECTORY_SEPARATOR;
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function contains(string $absoluteFile): bool
|
||||
{
|
||||
if (isset($this->containsCache[$absoluteFile])) {
|
||||
@@ -186,6 +236,61 @@ final class SourceScope
|
||||
return $out;
|
||||
}
|
||||
|
||||
private function rejectsEveryFileIn(string $directory): bool
|
||||
{
|
||||
foreach ($this->includes as $included) {
|
||||
if ($this->overlapsIgnoringCase($directory, $included) && ! $this->overlaps($directory, $included)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->excludes as $excluded) {
|
||||
if ($excluded['prefix'] === '' && $excluded['suffix'] === '' && $this->startsWithDir($directory, $excluded['path'])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return array_all($this->includes, fn (string $included): bool => ! $this->overlapsIgnoringCase($directory, $included));
|
||||
}
|
||||
|
||||
private function hasCaseTwin(string $directory): bool
|
||||
{
|
||||
$segments = explode(DIRECTORY_SEPARATOR, $directory);
|
||||
$parent = array_shift($segments).DIRECTORY_SEPARATOR;
|
||||
|
||||
foreach ($segments as $segment) {
|
||||
if ($segment === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$entries = @scandir($parent);
|
||||
|
||||
if ($entries === false) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
if ($entry !== $segment && strtolower($entry) === strtolower($segment)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
$parent = rtrim($parent, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$segment;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function overlaps(string $first, string $second): bool
|
||||
{
|
||||
return $this->startsWithDir($first, $second) || $this->startsWithDir($second, $first);
|
||||
}
|
||||
|
||||
private function overlapsIgnoringCase(string $first, string $second): bool
|
||||
{
|
||||
return $this->overlaps(strtolower($first), strtolower($second));
|
||||
}
|
||||
|
||||
private static function normalise(string $path): string
|
||||
{
|
||||
return rtrim($path, '/\\');
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use Pest\Exceptions\GitTimedOut;
|
||||
use Pest\Support\Git;
|
||||
|
||||
/**
|
||||
@@ -134,12 +135,20 @@ final class Storage
|
||||
|
||||
private static function rawOriginUrl(string $projectRoot): ?string
|
||||
{
|
||||
return new Git($projectRoot)->originUrl();
|
||||
try {
|
||||
return new Git($projectRoot)->originUrl();
|
||||
} catch (GitTimedOut) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static function gitPrefix(string $projectRoot): string
|
||||
{
|
||||
return new Git($projectRoot)->pathPrefix();
|
||||
try {
|
||||
return new Git($projectRoot)->pathPrefix();
|
||||
} catch (GitTimedOut) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
private static function slug(string $name): string
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use Pest\Plugins\Tia\Contracts\WatchDefault;
|
||||
use Pest\Support\Arr;
|
||||
use Pest\TestSuite;
|
||||
|
||||
/**
|
||||
@@ -173,7 +174,7 @@ final class WatchPatterns
|
||||
}
|
||||
}
|
||||
|
||||
return array_keys($matched);
|
||||
return Arr::stringKeys($matched);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -184,17 +185,17 @@ final class WatchPatterns
|
||||
{
|
||||
$matched = [];
|
||||
|
||||
foreach ($patterns as $key => $dirs) {
|
||||
foreach (Arr::stringKeys($patterns) as $key) {
|
||||
if (! $this->keyMatches($key, $file)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($dirs as $dir) {
|
||||
foreach ($patterns[$key] as $dir) {
|
||||
$matched[$dir] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return array_keys($matched);
|
||||
return Arr::stringKeys($matched);
|
||||
}
|
||||
|
||||
private function usesDefaultsFor(string $file): bool
|
||||
|
||||
@@ -115,7 +115,7 @@ final class XdebugRestarter implements Restarter
|
||||
|
||||
return Fingerprint::structuralMatches(
|
||||
$graph->fingerprint(),
|
||||
Fingerprint::compute($projectRoot, ConfigurationFile::fromArguments($arguments)),
|
||||
Fingerprint::compute($projectRoot, ConfigurationFile::fromArguments($arguments), $arguments),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Subscribers;
|
||||
|
||||
use PHPUnit\Event\TestRunner\EventFacadeSealed;
|
||||
use PHPUnit\Event\TestRunner\EventFacadeSealedSubscriber;
|
||||
|
||||
final readonly class EnsureCommandLineIncludePathComesFirst implements EventFacadeSealedSubscriber
|
||||
{
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
private array $directories;
|
||||
|
||||
public function __construct(string $includePath)
|
||||
{
|
||||
$this->directories = array_values(array_filter(
|
||||
explode(PATH_SEPARATOR, $includePath),
|
||||
fn (string $directory): bool => $directory !== '',
|
||||
));
|
||||
}
|
||||
|
||||
public function notify(EventFacadeSealed $event): void
|
||||
{
|
||||
$this->apply();
|
||||
}
|
||||
|
||||
public function apply(): void
|
||||
{
|
||||
if ($this->directories === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$otherDirectories = array_filter(
|
||||
explode(PATH_SEPARATOR, (string) get_include_path()),
|
||||
fn (string $directory): bool => ! in_array($directory, $this->directories, true),
|
||||
);
|
||||
|
||||
ini_set('include_path', implode(PATH_SEPARATOR, [...$this->directories, ...$otherDirectories]));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,15 @@ namespace Pest\Support;
|
||||
*/
|
||||
final class Arr
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $array
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function stringKeys(array $array): array
|
||||
{
|
||||
return array_map(strval(...), array_keys($array));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $array
|
||||
*/
|
||||
|
||||
@@ -20,9 +20,14 @@ final class ComposerProject
|
||||
return $rootPath;
|
||||
}
|
||||
|
||||
/** @var array{root: array{install_path: string}} $installed */
|
||||
$installed = require $metadataPath;
|
||||
$root = is_array($installed) ? ($installed['root'] ?? null) : null;
|
||||
$installPath = is_array($root) ? ($root['install_path'] ?? null) : null;
|
||||
|
||||
return realpath($installed['root']['install_path']) ?: $rootPath;
|
||||
if (! is_string($installPath)) {
|
||||
return $rootPath;
|
||||
}
|
||||
|
||||
return realpath($installPath) ?: $rootPath;
|
||||
}
|
||||
}
|
||||
|
||||
+240
-3
@@ -4,6 +4,9 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Support;
|
||||
|
||||
use Closure;
|
||||
use Pest\Exceptions\GitTimedOut;
|
||||
use Symfony\Component\Process\Exception\ProcessTimedOutException;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
/**
|
||||
@@ -13,6 +16,8 @@ final readonly class Git
|
||||
{
|
||||
private const float TIMEOUT = 5.0;
|
||||
|
||||
private const int BATCH_BYTES = 8_388_608;
|
||||
|
||||
public function __construct(
|
||||
private ?string $directory = null,
|
||||
private float $timeout = self::TIMEOUT,
|
||||
@@ -73,20 +78,45 @@ final readonly class Git
|
||||
return $this->result($arguments)['exitCode'] === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $paths
|
||||
* @return array{exitCode: int, ignored: array<int, string>, errorOutput: string}
|
||||
*/
|
||||
public function checkIgnore(array $paths): array
|
||||
{
|
||||
$result = $this->result(
|
||||
['check-ignore', '-z', '--stdin'],
|
||||
implode("\x00", array_map(static fn (string $path): string => './'.$path, $paths)),
|
||||
);
|
||||
|
||||
$ignored = [];
|
||||
|
||||
foreach (explode("\x00", rtrim($result['output'], "\x00")) as $path) {
|
||||
if ($path !== '') {
|
||||
$ignored[] = str_starts_with($path, './') ? substr($path, 2) : $path;
|
||||
}
|
||||
}
|
||||
|
||||
return ['exitCode' => $result['exitCode'], 'ignored' => $ignored, 'errorOutput' => $result['errorOutput']];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
* @return array{exitCode: int, output: string, errorOutput: string}
|
||||
*/
|
||||
public function result(array $arguments, ?string $input = null): array
|
||||
{
|
||||
$process = new Process(['git', ...$arguments], $this->directory, ['LC_ALL' => 'C', 'LANGUAGE' => '']);
|
||||
$process->setTimeout($this->timeout);
|
||||
$process = $this->process($arguments);
|
||||
|
||||
if ($input !== null) {
|
||||
$process->setInput($input);
|
||||
}
|
||||
|
||||
$process->run();
|
||||
try {
|
||||
$process->run();
|
||||
} catch (ProcessTimedOutException) {
|
||||
throw new GitTimedOut($arguments, $this->timeout);
|
||||
}
|
||||
|
||||
return [
|
||||
'exitCode' => $process->getExitCode() ?? 1,
|
||||
@@ -95,6 +125,17 @@ final readonly class Git
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
private function process(array $arguments): Process
|
||||
{
|
||||
$process = new Process(['git', ...$arguments], $this->directory, ['GIT_LITERAL_PATHSPECS' => '0', 'LC_ALL' => 'C', 'LANGUAGE' => '']);
|
||||
$process->setTimeout($this->timeout);
|
||||
|
||||
return $process;
|
||||
}
|
||||
|
||||
public function isRepository(): bool
|
||||
{
|
||||
return $this->succeeds(['rev-parse', '--git-dir']);
|
||||
@@ -120,6 +161,202 @@ final readonly class Git
|
||||
return $this->raw(['show', $sha.':'.$path]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $paths
|
||||
* @param Closure(int, string|null): void $receive
|
||||
*/
|
||||
public function showEach(string $sha, array $paths, Closure $receive): bool
|
||||
{
|
||||
$batched = [];
|
||||
|
||||
foreach ($paths as $position => $path) {
|
||||
if ($this->fitsBatchLine($path)) {
|
||||
$batched[] = $position;
|
||||
} else {
|
||||
$receive($position, $this->show($sha, $path));
|
||||
}
|
||||
}
|
||||
|
||||
if ($batched === []) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$objects = $this->batchCheck($sha, array_map(static fn (int $position): string => $paths[$position], $batched));
|
||||
|
||||
if ($objects === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$blobs = [];
|
||||
|
||||
foreach ($objects as $line => $object) {
|
||||
$position = $batched[$line];
|
||||
|
||||
if ($object === null) {
|
||||
$receive($position, null);
|
||||
} elseif ($object['type'] !== 'blob') {
|
||||
$receive($position, $this->show($sha, $paths[$position]));
|
||||
} else {
|
||||
$blobs[$position] = $object;
|
||||
}
|
||||
}
|
||||
|
||||
return array_all($this->groupBlobs($blobs), fn (array $group): bool => $this->readBlobs($group, $receive));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $paths
|
||||
* @return list<array{oid: string, type: string, bytes: int}|null>|null
|
||||
*/
|
||||
private function batchCheck(string $sha, array $paths): ?array
|
||||
{
|
||||
$result = $this->result(['cat-file', '--batch-check'], implode('', array_map(static fn (string $path): string => $sha.':'.$path."\n", $paths)));
|
||||
$headers = $result['exitCode'] === 0 ? explode("\n", $result['output']) : [];
|
||||
|
||||
if (array_pop($headers) !== '' || count($headers) !== count($paths)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$objects = [];
|
||||
|
||||
foreach ($headers as $header) {
|
||||
$object = $this->parseCheckLine($header);
|
||||
|
||||
if ($object === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$objects[] = $object;
|
||||
}
|
||||
|
||||
return $objects;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{oid: string, type: string, bytes: int}|false|null
|
||||
*/
|
||||
private function parseCheckLine(string $header): array|false|null
|
||||
{
|
||||
if (preg_match('/^([0-9a-f]+) ([a-z]+) (\d+)$/', $header, $matches) !== 1) {
|
||||
return str_ends_with($header, ' missing') || str_ends_with($header, ' ambiguous') ? null : false;
|
||||
}
|
||||
|
||||
return ['oid' => $matches[1], 'type' => $matches[2], 'bytes' => (int) $matches[3] + strlen($header) + 2];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array{oid: string, type: string, bytes: int}> $blobs
|
||||
* @return list<non-empty-array<int, string>>
|
||||
*/
|
||||
private function groupBlobs(array $blobs): array
|
||||
{
|
||||
$groups = [];
|
||||
$group = [];
|
||||
$groupBytes = 0;
|
||||
|
||||
foreach ($blobs as $position => $blob) {
|
||||
if ($group !== [] && $groupBytes + $blob['bytes'] > self::BATCH_BYTES) {
|
||||
$groups[] = $group;
|
||||
$group = [];
|
||||
$groupBytes = 0;
|
||||
}
|
||||
|
||||
$group[$position] = $blob['oid'];
|
||||
$groupBytes += $blob['bytes'];
|
||||
}
|
||||
|
||||
if ($group !== []) {
|
||||
$groups[] = $group;
|
||||
}
|
||||
|
||||
return $groups;
|
||||
}
|
||||
|
||||
private function fitsBatchLine(string $path): bool
|
||||
{
|
||||
return ! str_contains($path, "\n") && ! str_ends_with($path, "\r");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param non-empty-array<int, string> $blobs
|
||||
* @param Closure(int, string|null): void $receive
|
||||
*/
|
||||
private function readBlobs(array $blobs, Closure $receive): bool
|
||||
{
|
||||
$arguments = ['cat-file', '--batch'];
|
||||
$process = $this->process($arguments);
|
||||
$process->setInput(implode("\n", $blobs)."\n");
|
||||
$process->start();
|
||||
|
||||
try {
|
||||
return $this->streamBlobs($process, $blobs, $receive);
|
||||
} catch (ProcessTimedOutException) {
|
||||
throw new GitTimedOut($arguments, $this->timeout);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param non-empty-array<int, string> $blobs
|
||||
* @param Closure(int, string|null): void $receive
|
||||
*/
|
||||
private function streamBlobs(Process $process, array $blobs, Closure $receive): bool
|
||||
{
|
||||
$positions = array_keys($blobs);
|
||||
$buffer = '';
|
||||
$next = 0;
|
||||
|
||||
foreach ($process->getIterator(Process::ITER_SKIP_ERR) as $chunk) {
|
||||
$buffer .= $chunk;
|
||||
|
||||
while ($next < count($positions) && ($blob = $this->takeBlob($buffer)) !== null) {
|
||||
$position = $positions[$next++];
|
||||
|
||||
if ($blob === false || $blob['oid'] !== $blobs[$position]) {
|
||||
$process->stop(0);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$receive($position, $blob['content']);
|
||||
}
|
||||
}
|
||||
|
||||
$process->wait();
|
||||
|
||||
return $next === count($positions) && $buffer === '' && $process->getExitCode() === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{oid: string, content: string}|false|null
|
||||
*/
|
||||
private function takeBlob(string &$buffer): array|false|null
|
||||
{
|
||||
$headerEnd = strpos($buffer, "\n");
|
||||
|
||||
if ($headerEnd === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match('/^([0-9a-f]+) blob (\d+)$/', substr($buffer, 0, $headerEnd), $matches) !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$end = $headerEnd + 1 + (int) $matches[2];
|
||||
|
||||
if (strlen($buffer) <= $end) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($buffer[$end] !== "\n") {
|
||||
return false;
|
||||
}
|
||||
|
||||
$content = substr($buffer, $headerEnd + 1, (int) $matches[2]);
|
||||
$buffer = substr($buffer, $end + 1);
|
||||
|
||||
return ['oid' => $matches[1], 'content' => $content];
|
||||
}
|
||||
|
||||
public function repositoryRoot(): ?string
|
||||
{
|
||||
$root = $this->outputLine(['rev-parse', '--show-toplevel']);
|
||||
|
||||
@@ -362,6 +362,7 @@
|
||||
✓ it catch exceptions
|
||||
✓ it catch exceptions and messages
|
||||
✓ it catch exceptions, messages and code
|
||||
✓ it catch exceptions by interface
|
||||
✓ it can just define the message
|
||||
✓ it can just define the code
|
||||
✓ it not catch exceptions if given condition is false
|
||||
@@ -1021,6 +1022,8 @@
|
||||
✓ failures with multi-dimensional arrays and custom message
|
||||
✓ not failures
|
||||
✓ not failures with multi-dimensional arrays
|
||||
✓ not pass with multi-dimensional arrays
|
||||
✓ not failures with only multi-dimensional arrays
|
||||
|
||||
PASS Tests\Features\Expect\toHaveLength
|
||||
✓ it passes with ('Fortaleza')
|
||||
@@ -1199,8 +1202,11 @@
|
||||
✓ failures 6
|
||||
✓ failures 7
|
||||
✓ failures 8
|
||||
✓ failures 9
|
||||
✓ failures 10
|
||||
✓ failures with custom message
|
||||
✓ not failures
|
||||
✓ not failures with interface
|
||||
✓ closure missing parameter
|
||||
✓ closure missing type-hint
|
||||
✓ it can handle a non-defined exception
|
||||
@@ -1827,6 +1833,13 @@
|
||||
✓ compute comparable coverage with (32.53333333333333, 32.5)
|
||||
✓ compute comparable coverage with (32.57777771232132, 32.5)
|
||||
✓ compute comparable coverage with (100.0, 100.0)
|
||||
✓ coverage options accept a space separated value with dataset "min with equals sign"
|
||||
✓ coverage options accept a space separated value with dataset "min with space"
|
||||
✓ coverage options accept a space separated value with dataset "exactly with equals sign"
|
||||
✓ coverage options accept a space separated value with dataset "exactly with space"
|
||||
✓ coverage options accept a space separated value with dataset "both with space"
|
||||
✓ coverage options do not consume arguments owned by phpunit
|
||||
✓ value less coverage options do not consume the next argument
|
||||
|
||||
PASS Tests\Plugins\Traits
|
||||
✓ it allows global uses
|
||||
@@ -1880,6 +1893,9 @@
|
||||
✓ popArgument preserves duplicate values when removing a missing argument
|
||||
✓ popArgument preserves duplicate values when removing an existing argument
|
||||
|
||||
PASS Tests\Unit\Plugins\Concerns\PushArgument
|
||||
✓ pushArgument inserts before the option separator when the keys have gaps
|
||||
|
||||
PASS Tests\Unit\Plugins\Environment
|
||||
✓ environment is set to CI when --ci option is used
|
||||
✓ environment is set to Local when --ci option is not used
|
||||
@@ -2002,6 +2018,31 @@
|
||||
✓ it keeps a tracked outside change and drops an untracked ignored one
|
||||
✓ it keeps a tracked project change that the ignore rules match
|
||||
✓ it reads committed paths from the repository root even when git is told to be relative
|
||||
✓ it tells a working tree change outside the project from a committed one
|
||||
✓ it keeps a changed file whose name is a number as a string
|
||||
✓ it keeps a changed file outside the project whose name is a number as a string
|
||||
✓ it matches no external root for a changed file whose name is a number
|
||||
✓ it hashes an external input without reading it into memory
|
||||
✓ it sees a whitespace change inside an external input
|
||||
✓ it reports a changed file whose name looks like a pathspec
|
||||
✓ it reports an external input that the listing no longer names
|
||||
✓ it reports no change for an external input it cannot read
|
||||
✓ it keeps a snapshotted file whose name is a number as a string
|
||||
✓ it keeps a branch whose name is a number as a string
|
||||
✓ it reads the baseline of many changed files and keeps their order
|
||||
✓ it reads many baselines with one call and gives the same content as one call per file
|
||||
✓ it reads no baseline when the commit does not exist
|
||||
✓ it reads the baseline of each file again when the batch fails with dataset "a failed check"
|
||||
✓ it reads the baseline of each file again when the batch fails with dataset "a check line that does not parse"
|
||||
✓ it reads the baseline of each file again when the batch fails with dataset "a check without a line"
|
||||
✓ it reads the baseline of each file again when the batch fails with dataset "a failed read"
|
||||
✓ it reads the baseline of each file again when the batch fails with dataset "a header that does not parse after one blob"
|
||||
✓ it reads the baseline of each file again when the batch fails with dataset "a missing blob"
|
||||
✓ it reads the baseline of each file again when the batch fails with dataset "bytes after the last blob"
|
||||
✓ it reads the baseline of each file again when the batch fails with dataset "a blob without its line feed"
|
||||
✓ it reads the baseline of each file again when the batch fails with dataset "another blob than the one asked"
|
||||
✓ it raises a timed out read of the baseline blobs instead of answering
|
||||
✓ it reads the baseline of many large changed files within a small memory limit
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\ConfigurationFile
|
||||
✓ it fingerprints the path and the content of the configuration file
|
||||
@@ -2024,6 +2065,8 @@
|
||||
✓ it keeps an empty include path entry empty
|
||||
✓ it keeps the fingerprint of a relative bootstrap when the working directory changes during the run
|
||||
✓ it tells an include path through a symlink to a directory with a separator in its name apart from two include paths
|
||||
✓ it builds the source scope from the coverage filter and the source of the configuration
|
||||
✓ it gives no source scope when the configuration cannot be read
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\ContentHash
|
||||
✓ of() → it returns false when file does not exist
|
||||
@@ -2069,6 +2112,89 @@
|
||||
WARN Tests\Unit\Plugins\Tia\DeletedTestCoverage
|
||||
- cached hits of a deleted test are dropped while a replayed test stays → Coverage is not available
|
||||
|
||||
WARN Tests\Unit\Plugins\Tia\ExternalSources
|
||||
✓ it finds a psr-4 root that escapes the project
|
||||
✓ it finds a path repository
|
||||
✓ it finds a phpunit source directory outside the project
|
||||
✓ it finds nothing when the project only loads its own code
|
||||
✓ it finds nothing for a project at the repository root
|
||||
✓ it reports a root that sits outside the repository as unverifiable
|
||||
✓ it reports nothing unverifiable when every declaration stays inside the repository
|
||||
✓ it reports a bootstrap outside the repository as unverifiable
|
||||
✓ it matches only the changes that fall under an external root
|
||||
✓ it finds an autoload file that escapes the project and matches it exactly
|
||||
✓ it finds a phpunit bootstrap that escapes the project
|
||||
✓ it keeps a declared root that no longer exists on disk
|
||||
✓ it treats a classmap entry as a file only when it names one
|
||||
✓ it finds a testsuite directory outside the project
|
||||
✓ it keeps the directory before a wildcard in a path repository
|
||||
✓ it keeps the directory before a single character wildcard
|
||||
✓ it matches a deleted package that a wildcard declared
|
||||
✓ it covers the whole repository when a declaration reaches its root
|
||||
✓ it reads the configuration that the command line selects
|
||||
✓ it accepts the configuration argument in its joined form
|
||||
✓ it resolves a configuration path against its own directory
|
||||
✓ it follows a symlink that leaves the project
|
||||
✓ it keeps a real directory inside the project out of the roots
|
||||
✓ it finds a bootstrap file that the command line names
|
||||
✓ it finds every directory that an include path names
|
||||
✓ it resolves a command line path against the directory the command ran in
|
||||
✓ it keeps a declaration that a commit deleted under the directory the command ran in
|
||||
✓ it watches the paths of the configuration Pest generates in the directory the command ran in
|
||||
✓ it treats a classmap directory that carries a dot as a directory
|
||||
✓ it accepts the configuration argument attached to its short flag
|
||||
✓ it reads no configuration when the run asks for none
|
||||
✓ it reads no default configuration when the command line names one
|
||||
✓ it finds an include path that the configuration names
|
||||
✓ it matches a submodule that a commit moved
|
||||
✓ it matches a submodule that holds a declared file
|
||||
✓ it reads the configuration of the directory the command ran in
|
||||
✓ it reads a configuration that a directory argument names
|
||||
✓ it reads the dist name that phpunit tries before the older one
|
||||
✓ it finds a bootstrap that a single test suite names
|
||||
✓ it watches the directory before a wildcard that a configuration names
|
||||
✓ it lists the files of a root that the repository ignores as ignored inputs
|
||||
✓ it lists the ignored files under a declared root as ignored inputs
|
||||
✓ it lists an ignored bootstrap file inside vendor as an ignored input
|
||||
✓ it lists the ignored files under a declared root inside a dot directory
|
||||
✓ it lists an ignored link to a file but no ignored link to a directory or to nothing
|
||||
✓ it watches the path that composer resolved for a path repository
|
||||
✓ it watches the path that composer installed when the project has no lock file
|
||||
✓ it watches the path that composer installed into a custom vendor directory
|
||||
✓ it watches the path that composer installed into the vendor directory the run loaded
|
||||
✓ it watches the installed path and the locked path when they differ
|
||||
✓ it reads a path that composer resolved as a literal path
|
||||
✓ it reads the manifest and the lock file that the COMPOSER variable names
|
||||
✓ it lists the ignored files when git is told to read every pathspec literally
|
||||
- it treats a network path as absolute on Windows → Network paths only exist on Windows.
|
||||
✓ it reports an ignored repository under a declared root as unverifiable
|
||||
✓ it finds a root that the repository ignores next to a file whose name looks like a pathspec
|
||||
✓ it reports no repository that sits in a noise directory under a declared root as unverifiable
|
||||
✓ it reports a repository under an inner declared root even when an outer root counts it as noise
|
||||
✓ it reports a root inside an ignored repository as unverifiable
|
||||
✓ it reads a bootstrap whose name holds a wildcard character as a literal file
|
||||
✓ it reads a psr-4 directory whose name holds a wildcard character as a literal directory
|
||||
✓ it reads an include path whose name holds a wildcard character as a literal directory
|
||||
✓ it reads every path of an include path list
|
||||
✓ it watches the configuration directory when an include path list starts with a separator
|
||||
✓ it watches nothing for an empty include path, as PHPUnit adds nothing
|
||||
✓ it resolves every path of an include path list after the first one from the working directory
|
||||
✓ it watches the directory before a bracket and a brace path as it is
|
||||
✓ it watches the directory an escaped brace names
|
||||
✓ it watches every directory a double star pattern reaches like PHPUnit
|
||||
✓ it also watches a directory whose real name looks like a pattern
|
||||
✓ it keeps an existing absolute directory with brackets in its path as it is
|
||||
✓ it watches the directories a bracket pattern matches even when its literal name also exists
|
||||
✓ it cuts a path at a brace only when the glob of its reader expands braces
|
||||
✓ it lists no ignored file of the project itself as an ignored input
|
||||
✓ it keeps the roots of the run when a test changes the working directory
|
||||
- it keeps the drive letter when it resolves a missing directory against a Windows base → Drive letters exist only on Windows.
|
||||
✓ it resolves a path that starts with a drive letter against its base outside Windows
|
||||
- it treats a path from the root of the current drive as absolute on Windows → Paths from the root of the current drive exist only on Windows.
|
||||
- it keeps the current drive when it resolves a missing path from the root of that drive → Paths from the root of the current drive exist only on Windows.
|
||||
- it keeps the network share when it resolves a missing directory against a UNC base → UNC paths exist only on Windows.
|
||||
✓ it reads a leading double slash as the root outside Windows
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\FileState
|
||||
✓ keysWithPrefix() → it lists keys matching the prefix
|
||||
✓ keysWithPrefix() → it ignores in-flight temporary files from concurrent writes
|
||||
@@ -2079,6 +2205,9 @@
|
||||
✓ compute() → it excludes gitignored untracked files from the fingerprint
|
||||
✓ compute() → it keeps the command line bootstrap and include path out of a run that sets neither
|
||||
✓ compute() → it tells a bootstrap whose name looks like an include path apart from a bootstrap and an include path
|
||||
✓ compute() → it tells a relative include path from the absolute path it names
|
||||
✓ compute() → it stores an include path whose name is not utf-8 as text json can encode
|
||||
✓ compute() → it changes when the order of the include path changes and not when its spelling does
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\Graph
|
||||
✓ shouldRerunStatus() → it re-runs failures and errors, replays successes
|
||||
@@ -2111,6 +2240,8 @@
|
||||
✓ Laravel boot files → it watches the config and bootstrap files in the Laravel defaults
|
||||
✓ clearResults() → it drops the results of the fallback branch too
|
||||
✓ branch baseline over the fallback → it reads results written after an earlier read
|
||||
✓ pruneMissingBranches() → it keeps a branch whose name is a number
|
||||
✓ decode() → it keeps a file of the last run tree whose name is a number
|
||||
✓ encode() and decode() → it round-trips paths that are not valid UTF-8
|
||||
✓ encode() and decode() → it lists a branch whose name is not valid UTF-8
|
||||
✓ legacy schema → it reads a graph of the previous schema without unescaping its strings
|
||||
@@ -2142,12 +2273,26 @@
|
||||
✓ it detects an added or removed non-platform dependency
|
||||
✓ it is independent of package ordering
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\NumericInertiaPages
|
||||
✓ it selects the tests of a changed Inertia page whose name is a number
|
||||
✓ it keeps an Inertia page whose name is a number after the graph is decoded
|
||||
✓ it records an Inertia page whose name is a number as a string
|
||||
✓ it selects the tests of a shared module of an Inertia page whose name is a number
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\NumericSourceFileNames
|
||||
✓ it selects the tests of a changed source file whose name is a number
|
||||
✓ it selects the tests of a numeric source file after the graph is decoded
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\NumericTableDependencies
|
||||
✓ it exports numeric table dependencies from the recorder as strings
|
||||
✓ it persists numeric tables as JSON strings and selects only their migration readers after reload
|
||||
✓ it preserves numeric worker tables through payload cleaning union and graph reload
|
||||
✓ it preserves observed and migration added numeric tables when augmenting database tests
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\NumericWatchPatterns
|
||||
✓ it matches a watch pattern whose key is a number
|
||||
✓ it selects the tests under a watch target whose name is a number
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\ReadCapture
|
||||
✓ reads → it links a project file the test reads with dataset "file_get_contents"
|
||||
✓ reads → it links a project file the test reads with dataset "file"
|
||||
@@ -2163,6 +2308,7 @@
|
||||
✓ the file wrapper → it passes filesystem operations through while a test records
|
||||
✓ the file wrapper → it writes with LOCK_EX while a test records
|
||||
✓ the file wrapper → it reports a missing path to the error handler as plain PHP does while a test records
|
||||
✓ the file wrapper → it reports why an include failed as plain PHP does while a test records
|
||||
✓ the file wrapper → it keeps no memory for each filesystem call while a test records
|
||||
✓ the file wrapper → it keeps no memory for each test it records
|
||||
✓ the file wrapper → it is restored quietly when the test already restored it
|
||||
@@ -2181,11 +2327,14 @@
|
||||
✓ withoutReadCapture() → it keeps the explicit links when called without globs
|
||||
✓ withoutReadCapture() → it leaves a wrapper already registered for file:// untouched when called without globs
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\Recorder
|
||||
WARN Tests\Unit\Plugins\Tia\Recorder
|
||||
✓ activateLinkTracking() → it tracks tables without a coverage driver
|
||||
✓ activateLinkTracking() → it tracks inertia components without a coverage driver
|
||||
✓ activateLinkTracking() → it tracks linked sources across consecutive tests
|
||||
✓ activateLinkTracking() → it records nothing while inactive
|
||||
- activate() → it keeps xdebug from tracing the vendor directory of the project → Xdebug is not installed.
|
||||
✓ recordOnly() → it records only the test files it accepts
|
||||
✓ recordOnly() → it records each test file again after a reset
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\ResultKey
|
||||
✓ it keys a result per dataset row rather than per method
|
||||
@@ -2196,6 +2345,13 @@
|
||||
✓ contains() → it excludes only the files matching the suffix of an excluded directory
|
||||
✓ contains() → it excludes only the files matching the prefix of an excluded directory
|
||||
✓ contains() → it excludes every file of an excluded directory without a prefix or suffix
|
||||
✓ coverageExcludePaths() → it excludes each noise directory of the project that the scope rejects
|
||||
✓ coverageExcludePaths() → it keeps a noise directory that holds an included directory
|
||||
✓ coverageExcludePaths() → it keeps a noise directory below an included directory
|
||||
✓ coverageExcludePaths() → it keeps a noise directory whose name an included directory shares in another case
|
||||
✓ coverageExcludePaths() → it keeps a noise directory that has a sibling with the same name in another case
|
||||
✓ coverageExcludePaths() → it keeps each noise directory when an included directory is the project root in another case
|
||||
✓ coverageExcludePaths() → it keeps a linked noise directory whose target has a sibling with the same name in another case
|
||||
|
||||
WARN Tests\Unit\Plugins\Tia\StaleCoverageLines
|
||||
- a remeasured file drops line numbers that the current file no longer has → Coverage is not available
|
||||
@@ -2415,10 +2571,15 @@
|
||||
✓ last → it should return the last element for an array without changing the internal pointer
|
||||
✓ last → it should return the last element for an associative array without changing the internal pointer
|
||||
✓ last → it should return the last element for an mixed key array without changing the internal pointer
|
||||
✓ stringKeys → it returns every key as a string
|
||||
|
||||
PASS Tests\Unit\Support\Backtrace
|
||||
✓ it gets file name from called file
|
||||
|
||||
PASS Tests\Unit\Support\ComposerProject
|
||||
✓ it reads the project root that composer recorded
|
||||
✓ it falls back to the parent of the vendor directory when composer recorded no install path
|
||||
|
||||
PASS Tests\Unit\Support\Container
|
||||
✓ it exists
|
||||
✓ it gets an instance
|
||||
@@ -2463,6 +2624,12 @@
|
||||
✓ it ensures the given closures reports the correct class name
|
||||
✓ it ensures the given closures reports the correct class name and suggests the [pest()] function
|
||||
|
||||
PASS Tests\Unit\Support\Git
|
||||
✓ it raises a timed out command instead of answering with ('result')
|
||||
✓ it raises a timed out command instead of answering with ('raw')
|
||||
✓ it raises a timed out command instead of answering with ('output')
|
||||
✓ it raises a timed out command instead of answering with ('succeeds')
|
||||
|
||||
PASS Tests\Unit\Support\HigherOrderMessage
|
||||
✓ undefined method exceptions
|
||||
|
||||
@@ -2588,6 +2755,9 @@
|
||||
✓ a parallel test can extend another test with same name
|
||||
✓ parallel reports invalid datasets as failures
|
||||
✓ parallel lets extensions register event subscribers
|
||||
✓ sets Laravel parallel flags with dataset "without database options"
|
||||
✓ sets Laravel parallel flags with dataset "recreate databases"
|
||||
✓ sets Laravel parallel flags with dataset "drop databases"
|
||||
✓ parallel can have multiple exclude-groups
|
||||
✓ parallel can have multiple groups
|
||||
✓ parallel accepts the options that the workers ignore with ('--no-results')
|
||||
@@ -2598,6 +2768,35 @@
|
||||
✓ parallel does not record the test run history when asked not to with ('--do-not-record-test-run-history')
|
||||
✓ parallel group-filtered run is not considered empty when a worker ends on a fully filtered file
|
||||
✓ parallel group-filtered run still fails when the selection matches no tests
|
||||
✓ parallel accepts a path after the option separator
|
||||
|
||||
PASS Tests\Visual\ParallelIncludePath
|
||||
✓ parallel resolves requires through the include path with dataset "value in the same argument"
|
||||
✓ parallel resolves requires through the include path with dataset "value as a separate argument"
|
||||
✓ parallel resolves requires through the include path with dataset "absolute path"
|
||||
✓ parallel resolves requires through the include path with dataset "several paths"
|
||||
✓ parallel resolves requires through the include path with dataset "directory name with an equals sign"
|
||||
✓ parallel resolves requires through the include path with dataset "absolute directory name with an equals sign"
|
||||
✓ parallel resolves requires through the include path with dataset "require in the bootstrap file"
|
||||
✓ parallel resolves requires through the include path with dataset "command line before the XML include path"
|
||||
✓ parallel resolves requires through the include path with dataset "command line before the XML include path in the bootstrap file"
|
||||
✓ parallel places the include path before the argument separator
|
||||
✓ parallel fails to resolve requires without the include path
|
||||
|
||||
PASS Tests\Visual\ParallelIncludePathLeadingSpace
|
||||
✓ parallel keeps the leading space of an include path in the same argument as serial phpunit does
|
||||
|
||||
PASS Tests\Visual\ParallelIncludePathOptionWithLeadingSpace
|
||||
✓ parallel reads an include path option with a leading space as serial phpunit does
|
||||
|
||||
PASS Tests\Visual\ParallelIncludePathTrailingSpace
|
||||
✓ parallel workers keep the trailing space of an include path as serial phpunit does
|
||||
|
||||
PASS Tests\Visual\ParallelIncludePathWhitespace
|
||||
✓ parallel accepts an include path of whitespace as serial phpunit does
|
||||
|
||||
PASS Tests\Visual\ParallelIncludePathWithoutValue
|
||||
✓ parallel keeps the pest runner when the include path option has no value
|
||||
|
||||
PASS Tests\Visual\ParallelNestedDatasets
|
||||
✓ parallel loads nested datasets from nested directories
|
||||
@@ -2680,6 +2879,7 @@
|
||||
✓ an empty shard runs no tests with dataset "parallel with fail-on-empty-test-suite"
|
||||
✓ an empty shard lists no tests
|
||||
✓ a non-empty shard runs its assigned test
|
||||
✓ shard accepts a path after the option separator
|
||||
|
||||
PASS Tests\Visual\SingleTestOrDirectory
|
||||
✓ allows to run a single test
|
||||
@@ -2688,6 +2888,7 @@
|
||||
✓ keeps namespace filters unchanged
|
||||
✓ converts a namespace after the retry flag
|
||||
✓ it disable decorating printer when colors is set to never
|
||||
✓ allows to run a single test after the option separator
|
||||
|
||||
WARN Tests\Visual\Success
|
||||
- visual snapshot of test suite on success
|
||||
@@ -2717,4 +2918,4 @@
|
||||
✓ pass with dataset with ('my-datas-set-value')
|
||||
✓ within describe → pass with dataset with ('my-datas-set-value')
|
||||
|
||||
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 39 skipped, 2000 passed (4505 assertions)
|
||||
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 45 skipped, 2169 passed (4762 assertions)
|
||||
@@ -14,6 +14,7 @@ arch()->preset()->php()->ignoring([
|
||||
'xdebug_start_code_coverage',
|
||||
'xdebug_stop_code_coverage',
|
||||
'xdebug_get_code_coverage',
|
||||
'xdebug_set_filter',
|
||||
]);
|
||||
|
||||
arch()->preset()->strict()->ignoring([
|
||||
|
||||
@@ -16,6 +16,10 @@ it('catch exceptions, messages and code', function (): void {
|
||||
throw new Exception('Something bad happened', 1);
|
||||
})->throws(Exception::class, 'Something bad happened', 1);
|
||||
|
||||
it('catch exceptions by interface', function (): void {
|
||||
throw new Exception('Something bad happened');
|
||||
})->throws(Throwable::class, 'Something bad happened');
|
||||
|
||||
it('can just define the message', function (): void {
|
||||
throw new Exception('Something bad happened');
|
||||
})->throws('Something bad happened');
|
||||
|
||||
@@ -33,3 +33,11 @@ test('not failures', function (): void {
|
||||
test('not failures with multi-dimensional arrays', function (): void {
|
||||
expect(['a' => 1, 'b', 'c' => 'world', 'foo' => ['bar' => ['bir' => 'biz']]])->not->toHaveKeys(['foo' => ['bar' => 'bir'], 'c', 'z']);
|
||||
})->throws(ExpectationFailedException::class);
|
||||
|
||||
test('not pass with multi-dimensional arrays', function (): void {
|
||||
expect(['a' => 1, 'b', 'c' => 'world', 'foo' => ['bar' => ['bir' => 'biz']]])->not->toHaveKeys(['foo' => ['bar' => ['baz']], 'z']);
|
||||
});
|
||||
|
||||
test('not failures with only multi-dimensional arrays', function (): void {
|
||||
expect(['a' => 1, 'b', 'c' => 'world', 'foo' => ['bar' => ['bir' => 'biz']]])->not->toHaveKeys(['foo' => ['bar' => ['bir']]]);
|
||||
})->throws(ExpectationFailedException::class);
|
||||
|
||||
@@ -28,7 +28,12 @@ test('passes', function (): void {
|
||||
->toThrow(function (RuntimeException $e): void {}, 'actual message')
|
||||
->and(function (): void {
|
||||
throw new CustomException('foo');
|
||||
})->toThrow(new CustomException('foo'));
|
||||
})->toThrow(new CustomException('foo'))
|
||||
->and(function (): void {
|
||||
throw new RuntimeException('actual message');
|
||||
})->toThrow(Throwable::class)
|
||||
->toThrow(function (Throwable $e): void {})
|
||||
->toThrow(Throwable::class, 'actual message');
|
||||
});
|
||||
|
||||
test('failures 1', function (): void {
|
||||
@@ -78,6 +83,16 @@ test('failures 8', function (): void {
|
||||
})->toThrow(new CustomException('expected message'));
|
||||
})->throws(ExpectationFailedException::class);
|
||||
|
||||
test('failures 9', function (): void {
|
||||
expect(function (): void {})->toThrow(Throwable::class);
|
||||
})->throws(ExpectationFailedException::class, 'Exception ['.Throwable::class.'] not thrown.');
|
||||
|
||||
test('failures 10', function (): void {
|
||||
expect(function (): void {
|
||||
throw new Exception('actual message');
|
||||
})->toThrow(JsonSerializable::class);
|
||||
})->throws(ExpectationFailedException::class, 'Failed asserting that an instance of class Exception is an instance of interface JsonSerializable.');
|
||||
|
||||
test('failures with custom message', function (): void {
|
||||
expect(function (): void {
|
||||
throw new RuntimeException('actual message');
|
||||
@@ -90,6 +105,12 @@ test('not failures', function (): void {
|
||||
})->not->toThrow(RuntimeException::class);
|
||||
})->throws(ExpectationFailedException::class);
|
||||
|
||||
test('not failures with interface', function (): void {
|
||||
expect(function (): void {
|
||||
throw new RuntimeException;
|
||||
})->not->toThrow(Throwable::class);
|
||||
})->throws(ExpectationFailedException::class);
|
||||
|
||||
test('closure missing parameter', function (): void {
|
||||
expect(function (): void {})->toThrow(function (): void {});
|
||||
})->throws(InvalidArgumentException::class, 'The given closure must have a single parameter type-hinted as the class string.');
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Support\Coverage;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
function addTestFileThatReadsOutsideTheCoverageSource(Project $project): void
|
||||
{
|
||||
$project->write('support/salutation.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
return 'visitor';
|
||||
PHP);
|
||||
|
||||
$project->write('tests/Integration/WelcomeTest.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Fixture\App\Greeter;
|
||||
|
||||
test('welcomes a visitor', function (): void {
|
||||
$name = require dirname(__DIR__, 2).'/support/salutation.php';
|
||||
|
||||
expect((new Greeter)->greet($name))->toBe('Hello, visitor!');
|
||||
});
|
||||
PHP);
|
||||
|
||||
$project->git()->commit('add a test file the graph does not know');
|
||||
$project->seed('master');
|
||||
}
|
||||
|
||||
function forgetWelcomeTest(Project $project): void
|
||||
{
|
||||
$project->mutateGraph(function (array $graph): array {
|
||||
unset($graph['edges']['tests/Integration/WelcomeTest.php']);
|
||||
|
||||
return $graph;
|
||||
});
|
||||
}
|
||||
|
||||
test('a coverage replay does not narrow the edges of a test file the graph does not know', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
addTestFileThatReadsOutsideTheCoverageSource($project);
|
||||
|
||||
$baseline = $project->pest('--tia', '--coverage', ...$arguments);
|
||||
|
||||
expect($baseline->exitCode)->toBe(0, $baseline->describe());
|
||||
|
||||
forgetWelcomeTest($project);
|
||||
|
||||
$coverage = $project->pest('--tia', '--coverage', ...$arguments);
|
||||
|
||||
expect($coverage->exitCode)->toBe(0, $coverage->describe())
|
||||
->and($coverage->uncached())->toBe(1, $coverage->describe())
|
||||
->and($project->graph()['edges'] ?? [])->not->toHaveKey('tests/Integration/WelcomeTest.php');
|
||||
|
||||
$project->write('support/salutation.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
return 'stranger';
|
||||
PHP);
|
||||
|
||||
$project->git()->commit('change the salutation');
|
||||
|
||||
$result = $project->pest('--tia', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(1, $result->describe());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a coverage replay with affected test files does not mark a test file the graph does not know as known', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
addTestFileThatReadsOutsideTheCoverageSource($project);
|
||||
|
||||
$baseline = $project->pest('--tia', '--coverage', ...$arguments);
|
||||
|
||||
expect($baseline->exitCode)->toBe(0, $baseline->describe());
|
||||
|
||||
forgetWelcomeTest($project);
|
||||
|
||||
$project->write('app/Calculator.php', str_replace(
|
||||
'return $a + $b;',
|
||||
'return ($a + $b);',
|
||||
(string) file_get_contents($project->path('app/Calculator.php')),
|
||||
));
|
||||
$project->git()->commit('touch the calculator');
|
||||
|
||||
$coverage = $project->pest('--tia', '--coverage', ...$arguments);
|
||||
|
||||
expect($coverage->exitCode)->toBe(0, $coverage->describe())
|
||||
->and($coverage->affected())->toBeGreaterThan(0, $coverage->describe())
|
||||
->and($coverage->uncached())->toBe(1, $coverage->describe())
|
||||
->and($project->graph()['edges'] ?? [])->not->toHaveKey('tests/Integration/WelcomeTest.php');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
test('a filtered configuration alone does not announce tia on a partial run without --tia', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->write('tests/Pest.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once __DIR__.'/../app/Calculator.php';
|
||||
require_once __DIR__.'/../app/Greeter.php';
|
||||
|
||||
pest()->tia()->filtered();
|
||||
PHP);
|
||||
$project->git()->commit('filter tia runs');
|
||||
|
||||
$result = $project->pest('--no-tia', 'tests/Unit');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain('4 passed')
|
||||
->and($result->output)->not->toContain('TIA does not apply to partial runs');
|
||||
})->skipOnWindows();
|
||||
@@ -29,10 +29,10 @@ test('an explicit path turns filtered mode off', function (): void {
|
||||
$result = $project->pest('--tia', '--filtered', 'tests/Unit');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->output)->toContain('TIA does not apply to partial runs')
|
||||
->and($result->output)->not->toContain('No affected tests found')
|
||||
expect($result->output)->not->toContain('No affected tests found')
|
||||
->and($result->tally())->toContain('4 passed')
|
||||
->and($delta->writtenCount())->toBe(4, $delta->summary())
|
||||
->and($result->replayed())->toBe(4, $result->describe())
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary())
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
test('a run without tia finishes when git cannot read the working tree', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
file_put_contents($project->path('.git/index'), 'not an index');
|
||||
|
||||
$result = $project->pest();
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->not->toContain('could not read the git repository')
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
|
||||
})->skipOnWindows();
|
||||
File diff suppressed because it is too large
Load Diff
@@ -21,28 +21,29 @@ test('a filtered run rewrites only the test that ran', function (): void {
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a filtered run under --tia announces that tia does not apply', function (): void {
|
||||
test('a filtered run under --tia replays the selected test', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$result = $project->pest('--tia', '--filter=adds two numbers');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->output)->toContain('TIA does not apply to partial runs')
|
||||
->and($delta->writtenCount())->toBe(1, $delta->summary())
|
||||
expect($result->output)->not->toContain('TIA does not apply to partial runs')
|
||||
->and($result->replayed())->toBe(1, $result->describe())
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary())
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a test suffix narrows the tier even though every test runs', function (): void {
|
||||
test('a test suffix narrows the tier and replays every selected test', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$result = $project->pest('--tia', '--test-suffix=Test.php');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->output)->toContain('TIA does not apply to partial runs')
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and($delta->writtenCount())->toBe(Project::TOTAL_TESTS, $delta->summary())
|
||||
expect($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe())
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary())
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
@@ -73,7 +74,7 @@ test('a dirty run narrows to the uncommitted test edit', function (): void {
|
||||
$result = $project->pest('--tia', '--dirty');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->output)->toContain('TIA does not apply to partial runs')
|
||||
expect($result->affected())->toBe(3, $result->describe())
|
||||
->and($result->tally())->toContain('3 passed')
|
||||
->and($delta->removed())->toBe(0, $delta->summary())
|
||||
->and($delta->structureMoved())->toBeFalse($delta->summary());
|
||||
@@ -86,13 +87,14 @@ test('filtered mode yields to an explicit filter', function (): void {
|
||||
$result = $project->pest('--tia', '--filtered', '--filter=adds two numbers');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->output)->toContain('TIA does not apply to partial runs')
|
||||
expect($result->output)->not->toContain('No affected tests found')
|
||||
->and($result->tally())->toContain('1 passed')
|
||||
->and($delta->writtenCount())->toBe(1, $delta->summary())
|
||||
->and($result->replayed())->toBe(1, $result->describe())
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary())
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('an env flag narrows exactly like the option it mirrors', function (string $variable): void {
|
||||
test('an env flag narrows exactly like the option it mirrors', function (string $variable, int $replayed): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
@@ -102,10 +104,14 @@ test('an env flag narrows exactly like the option it mirrors', function (string
|
||||
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->output)->toContain('TIA does not apply to partial runs')
|
||||
->and($delta->writtenCount())->toBe(1, $delta->summary())
|
||||
expect($result->output)->not->toContain('TIA does not apply to partial runs')
|
||||
->and($result->replayed())->toBe($replayed, $result->describe())
|
||||
->and($delta->writtenCount())->toBe(1 - $replayed, $delta->summary())
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->with(['PEST_TIA', 'PEST_TIA_FILTERED'])->skipOnWindows();
|
||||
})->with([
|
||||
'PEST_TIA' => ['PEST_TIA', 1],
|
||||
'PEST_TIA_FILTERED' => ['PEST_TIA_FILTERED', 0],
|
||||
])->skipOnWindows();
|
||||
|
||||
test('a partial run does not purge the graph even with --fresh', function (): void {
|
||||
$project = Project::make('master');
|
||||
@@ -151,20 +157,20 @@ test('a shard is a partial run', function (): void {
|
||||
$result = $project->pest('--tia', '--shard=1/2');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->output)->toContain('TIA does not apply to partial runs')
|
||||
expect($result->replayed())->toBeGreaterThan(0, $result->describe())
|
||||
->and($delta->removed())->toBe(0, $delta->summary())
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a parallel partial run records the test that ran, like a sequential one', function (): void {
|
||||
test('a parallel partial run replays the selected test, like a sequential one', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$result = $project->pest('--tia', '--parallel', '--processes=2', '--filter=adds two numbers');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->output)->toContain('TIA does not apply to partial runs')
|
||||
->and($result->tally())->toContain('1 passed')
|
||||
->and($delta->writtenCount())->toBe(1, $delta->summary())
|
||||
expect($result->tally())->toContain('1 passed')
|
||||
->and($result->replayed())->toBe(1, $result->describe())
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary())
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
test('a partial run without a coverage driver names its selection, not the full suite', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$project->write('app/Calculator.php', str_replace(
|
||||
'return $a + $b;',
|
||||
'return $b + $a;',
|
||||
(string) file_get_contents($project->path().'/app/Calculator.php'),
|
||||
));
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), ['XDEBUG_MODE' => 'off'], '--tia', 'tests/Unit');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->toContain('no coverage driver is available')
|
||||
->and($result->tally())->toContain('4 passed')
|
||||
->and($result->output)->not->toContain('Running the full suite');
|
||||
})->skipOnWindows();
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
function tiaEditGreeterTest(Project $project): void
|
||||
{
|
||||
$project->write('tests/Unit/GreeterTest.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Fixture\App\Greeter;
|
||||
|
||||
test('greets a person', function (): void {
|
||||
expect((new Greeter)->greet('Nuno'))->toBe('Hello, Nuno!');
|
||||
})->group('greeter');
|
||||
|
||||
test('greets the world', function (): void {
|
||||
expect((new Greeter)->greet('world'))->toBe('Hello, world!');
|
||||
})->group('greeter');
|
||||
|
||||
test('greets again', function (): void {
|
||||
expect((new Greeter)->greet('again'))->toBe('Hello, again!');
|
||||
})->group('greeter');
|
||||
PHP);
|
||||
}
|
||||
|
||||
test('a partial run replays the unaffected tests of its selection', function (array $selection, int $affected, int $replayed, array $mode): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
tiaEditGreeterTest($project);
|
||||
|
||||
$result = $project->pest('--tia', ...$selection, ...$mode);
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->not->toContain('TIA does not apply to partial runs')
|
||||
->and($result->tally())->toContain(($affected + $replayed).' passed')
|
||||
->and($result->affected())->toBe($affected, $result->describe())
|
||||
->and($result->replayed())->toBe($replayed, $result->describe())
|
||||
->and($delta->structureMoved())->toBeFalse($delta->summary())
|
||||
->and($delta->shaMoved())->toBeFalse($delta->summary())
|
||||
->and($delta->treeMoved())->toBeFalse($delta->summary())
|
||||
->and($delta->removed())->toBe(0, $delta->summary());
|
||||
})->with([
|
||||
'an explicit path' => [['tests/Unit'], 3, 2],
|
||||
'--filter' => [['--filter=greets a person|adds two numbers'], 1, 1],
|
||||
'--group' => [['--group=greeter'], 3, 0],
|
||||
'--exclude-group' => [['--exclude-group=greeter'], 0, 4],
|
||||
'--testsuite' => [['--testsuite=default'], 3, 4],
|
||||
'--dirty' => [['--dirty'], 3, 0],
|
||||
])->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a partial run re-runs a cached failure in its selection', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master', failing: ['adds two numbers']);
|
||||
|
||||
$result = $project->pest('--tia', 'tests/Unit');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->tally())->toContain('4 passed')
|
||||
->and($result->replayed())->toBe(3, $result->describe())
|
||||
->and($delta->writtenCount())->toBe(1, $delta->summary())
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a partial run leaves the affected tests to the next complete run', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
tiaEditGreeterTest($project);
|
||||
|
||||
$project->pest('--tia', '--exclude-group=greeter');
|
||||
$result = $project->pest('--tia');
|
||||
|
||||
expect($result->affected())->toBe(3, $result->describe())
|
||||
->and($result->replayed())->toBe(4, $result->describe());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a partial run without a graph runs its selection and records nothing', function (): void {
|
||||
$project = Project::make('master');
|
||||
|
||||
$result = $project->pest('--tia', 'tests/Unit');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->toContain('a partial run cannot record the dependency graph')
|
||||
->and($result->tally())->toContain('4 passed')
|
||||
->and($result->replayed())->toBe(0, $result->describe())
|
||||
->and($project->graphExists())->toBeFalse();
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a partial run with a coverage report runs its selection directly', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$result = $project->pest('--tia', 'tests/Unit', '--coverage-text');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->output)->toContain('TIA does not apply to partial runs')
|
||||
->and($result->replayed())->toBe(0, $result->describe())
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a partial run in a repository a complete run refuses runs its selection directly', function (Closure $prepare): void {
|
||||
$project = $prepare();
|
||||
|
||||
$result = $project->pest('--tia', 'tests/Unit');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain('4 passed')
|
||||
->and($result->output)->toContain('TIA does not apply to partial runs')
|
||||
->and($project->graphExists())->toBeFalse();
|
||||
})->with([
|
||||
'no remote' => [function (): Project {
|
||||
$project = Project::make('master');
|
||||
$project->git()->removeOrigin();
|
||||
$project->git()->switchTo('feature-x', new: true);
|
||||
|
||||
return $project;
|
||||
}],
|
||||
'no default branch' => [function (): Project {
|
||||
$project = Project::make('master');
|
||||
$project->git()->unsetOriginHead();
|
||||
$project->git()->config('init.defaultBranch', 'main');
|
||||
$project->git()->switchTo('feature-x', new: true);
|
||||
|
||||
return $project;
|
||||
}],
|
||||
'no commits' => [function (): Project {
|
||||
$project = Project::withoutGit();
|
||||
$project->git()->run(['init', '--quiet']);
|
||||
$project->git()->run(['checkout', '--quiet', '-b', 'master']);
|
||||
$project->git()->addOrigin();
|
||||
|
||||
return $project;
|
||||
}],
|
||||
'no git' => [fn (): Project => Project::withoutGit()],
|
||||
])->skipOnWindows();
|
||||
|
||||
test('a partial run leaves a graph recorded in a different environment alone', function (string $section, string $key, string $value): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
$project->mutateGraph(function (array $graph) use ($section, $key, $value): array {
|
||||
$graph['fingerprint'][$section][$key] = $value;
|
||||
|
||||
return $graph;
|
||||
});
|
||||
file_put_contents($project->graphDir().'/'.Tia::KEY_COVERAGE_CACHE, 'cached coverage');
|
||||
$project->snapshot();
|
||||
|
||||
$result = $project->pest('--tia', '--filter=adds two numbers');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->toContain('The graph was recorded in a different environment ('.$key.')')
|
||||
->and($result->tally())->toContain('1 passed')
|
||||
->and($result->replayed())->toBe(0, $result->describe())
|
||||
->and($delta->isHardSuppressed())->toBeTrue($delta->summary())
|
||||
->and($project->graphDir().'/'.Tia::KEY_COVERAGE_CACHE)->toBeFile();
|
||||
})->with([
|
||||
'another PHP minor version' => ['environmental', 'php_minor', '7.4'],
|
||||
'another lockfile' => ['structural', 'composer_lock', 'a-lockfile-this-project-never-had'],
|
||||
])->skipOnWindows();
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Symfony\Component\Process\ExecutableFinder;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
function fakeGitPath(Project $project, string $case): string
|
||||
{
|
||||
$git = (new ExecutableFinder)->find('git');
|
||||
|
||||
assert(is_string($git));
|
||||
|
||||
$directory = $project->path('.fake-git');
|
||||
$realGit = escapeshellarg($git);
|
||||
|
||||
mkdir($directory);
|
||||
file_put_contents($directory.'/git', <<<SH
|
||||
#!/bin/sh
|
||||
case "\$1 \$2" in
|
||||
{$case}
|
||||
esac
|
||||
exec {$realGit} "\$@"
|
||||
SH);
|
||||
chmod($directory.'/git', 0755);
|
||||
|
||||
if (! is_dir($project->path('.git/info'))) {
|
||||
mkdir($project->path('.git/info'));
|
||||
}
|
||||
|
||||
file_put_contents($project->path('.git/info/exclude'), "/.fake-git/\n", FILE_APPEND);
|
||||
|
||||
return $directory.PATH_SEPARATOR.getenv('PATH');
|
||||
}
|
||||
|
||||
test('a slow git while naming the branch records nothing without --tia', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$path = fakeGitPath($project, '"symbolic-ref "*) exec sleep 6 ;;');
|
||||
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and($result->output)->not->toContain('Git did not answer')
|
||||
->and($delta->baselineUntouched('master'))->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a slow branch listing after the suite keeps the run results without --tia', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$path = fakeGitPath($project, '"for-each-ref "*) exec sleep 6 ;;');
|
||||
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and($result->output)->not->toContain('Git did not answer')
|
||||
->and($project->branchKeys())->toBe(['master'])
|
||||
->and($delta->writtenCount())->toBe(Project::TOTAL_TESTS, $delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a run without --tia records nothing when git cannot name the current branch', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$path = fakeGitPath($project, '"rev-parse --abbrev-ref") exit 128 ;;');
|
||||
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and($project->branchKeys())->toBe(['master'])
|
||||
->and($delta->baselineUntouched('master'))->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a slow git stops a --tia run with the timeout', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$path = fakeGitPath($project, '"symbolic-ref "*) exec sleep 6 ;;');
|
||||
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path], '--tia');
|
||||
|
||||
expect($result->exitCode)->toBe(1, $result->describe())
|
||||
->and($result->output)->toContain('Git did not answer within 5 seconds: git symbolic-ref')
|
||||
->and($result->output)->not->toContain('default branch');
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a slow git check-ignore keeps composer.lock in the fingerprint', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$path = fakeGitPath($project, '"check-ignore -z") exec sleep 6 ;;');
|
||||
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path], '--tia');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->not->toContain('Git did not answer')
|
||||
->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe())
|
||||
->and($delta->structureMoved())->toBeFalse($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a slow git stops a --tia run with the command that timed out first', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$path = fakeGitPath($project, '"symbolic-ref "*|"rev-parse --git-dir") exec sleep 6 ;;');
|
||||
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path], '--tia');
|
||||
|
||||
expect($result->exitCode)->toBe(1, $result->describe())
|
||||
->and($result->output)->toContain('Git did not answer within 5 seconds: git symbolic-ref');
|
||||
})->skipOnWindows();
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Symfony\Component\Process\ExecutableFinder;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
function slowGitAtBootPath(Project $project, string $command): string
|
||||
{
|
||||
$git = (new ExecutableFinder)->find('git');
|
||||
|
||||
assert(is_string($git));
|
||||
|
||||
$directory = $project->path('.slow-git');
|
||||
$realGit = escapeshellarg($git);
|
||||
$slept = escapeshellarg($directory.'/slept');
|
||||
|
||||
mkdir($directory);
|
||||
file_put_contents($directory.'/git', <<<SH
|
||||
#!/bin/sh
|
||||
case "\$1 \$2" in
|
||||
"{$command}") [ -e {$slept} ] || { touch {$slept}; exec sleep 6; } ;;
|
||||
esac
|
||||
exec {$realGit} "\$@"
|
||||
SH);
|
||||
chmod($directory.'/git', 0755);
|
||||
|
||||
return $directory.PATH_SEPARATOR.getenv('PATH');
|
||||
}
|
||||
|
||||
test('a slow git while reading the origin url does not stop a run without --tia', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$path = slowGitAtBootPath($project, 'config --get');
|
||||
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and($project->path('.slow-git/slept'))->toBeFile('the slow git never ran');
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a slow git while reading the path prefix does not stop a run without --tia', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$path = slowGitAtBootPath($project, 'rev-parse --show-prefix');
|
||||
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and($project->path('.slow-git/slept'))->toBeFile('the slow git never ran');
|
||||
})->skipOnWindows();
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Support\Coverage;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
function addTestFileTheGraphDoesNotKnow(Project $project): void
|
||||
{
|
||||
$project->write('tests/Integration/WelcomeTest.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Fixture\App\Greeter;
|
||||
|
||||
test('welcomes a visitor', function (): void {
|
||||
expect((new Greeter)->greet('visitor'))->toBe('Hello, visitor!');
|
||||
});
|
||||
PHP);
|
||||
|
||||
$project->git()->commit('add a test file the graph does not know');
|
||||
}
|
||||
|
||||
test('a replay records a test file the graph does not know', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
addTestFileTheGraphDoesNotKnow($project);
|
||||
$project->seed('master');
|
||||
|
||||
$first = $project->pest('--tia', ...$arguments);
|
||||
|
||||
expect($first->exitCode)->toBe(0, $first->describe())
|
||||
->and($first->replayed())->toBe(Project::TOTAL_TESTS, $first->describe())
|
||||
->and($first->uncached())->toBe(1, $first->describe())
|
||||
->and($project->graph()['edges'] ?? [])->toHaveKey('tests/Integration/WelcomeTest.php');
|
||||
|
||||
$second = $project->pest('--tia', ...$arguments);
|
||||
|
||||
expect($second->exitCode)->toBe(0, $second->describe())
|
||||
->and($second->replayed())->toBe(Project::TOTAL_TESTS + 1, $second->describe())
|
||||
->and($second->uncached())->toBe(0, $second->describe());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a replay that records a test file the graph does not know keeps the edges of the known test files', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
addTestFileTheGraphDoesNotKnow($project);
|
||||
$project->seed('master', failing: ['greets a person']);
|
||||
$project->mutateGraph(function (array $graph): array {
|
||||
$graph['edges']['tests/Unit/GreeterTest.php'][] = array_search('app/Calculator.php', $graph['files'], true);
|
||||
|
||||
return $graph;
|
||||
});
|
||||
|
||||
$known = $project->graph()['edges'] ?? [];
|
||||
|
||||
$result = $project->pest('--tia', ...$arguments);
|
||||
$edges = $project->graph()['edges'] ?? [];
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($edges)->toHaveKey('tests/Integration/WelcomeTest.php');
|
||||
|
||||
unset($edges['tests/Integration/WelcomeTest.php']);
|
||||
|
||||
expect($edges)->toBe($known);
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit bootstrap="../../vendor/autoload.php">
|
||||
<php>
|
||||
<includePath>ParallelIncludePath/xml-lib</includePath>
|
||||
</php>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
$valueRequiredWhileLoading = require 'parallel-include-path.inc';
|
||||
|
||||
test('requires a file through the include path while loading', function () use ($valueRequiredWhileLoading) {
|
||||
expect($valueRequiredWhileLoading)->toBe('resolved through the include path');
|
||||
});
|
||||
|
||||
test('requires a file through the include path while running', function () {
|
||||
expect(require 'parallel-include-path.inc')->toBe('resolved through the include path');
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__.'/../../../vendor/autoload.php';
|
||||
|
||||
if ((require 'parallel-include-path.inc') !== 'resolved through the include path') {
|
||||
throw new RuntimeException('The bootstrap file did not resolve the command line include path first.');
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<?php
|
||||
|
||||
return 'resolved through the include path';
|
||||
@@ -0,0 +1,3 @@
|
||||
<?php
|
||||
|
||||
return 'resolved through the include path';
|
||||
@@ -0,0 +1,3 @@
|
||||
<?php
|
||||
|
||||
throw new RuntimeException('The XML include path came before the command line include path.');
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Composer\InstalledVersions;
|
||||
use Pest\Plugins\Parallel\Handlers\Laravel;
|
||||
|
||||
require dirname(__DIR__, 3).'/vendor/autoload.php';
|
||||
|
||||
final class ParallelRunnerStub
|
||||
{
|
||||
public static function resolveRunnerUsing(Closure $resolver): void {}
|
||||
}
|
||||
|
||||
class_alias(ParallelRunnerStub::class, 'Illuminate\\Testing\\ParallelRunner');
|
||||
|
||||
$installed = InstalledVersions::getAllRawData()[0];
|
||||
$installed['versions']['laravel/framework'] = ['dev_requirement' => false];
|
||||
InstalledVersions::reload($installed);
|
||||
|
||||
(new Laravel)->handleArguments($argv);
|
||||
|
||||
$flags = array_flip([
|
||||
'LARAVEL_PARALLEL_TESTING',
|
||||
'LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES',
|
||||
'LARAVEL_PARALLEL_TESTING_DROP_DATABASES',
|
||||
]);
|
||||
|
||||
echo json_encode([
|
||||
'server' => array_keys(array_filter(array_intersect_key($_SERVER, $flags))),
|
||||
'env' => array_keys(array_filter(array_intersect_key($_ENV, $flags))),
|
||||
], JSON_THROW_ON_ERROR);
|
||||
@@ -9,6 +9,7 @@ use Pest\Plugins\Tia;
|
||||
use Pest\Plugins\Tia\ByteSafeJson;
|
||||
use Pest\Plugins\Tia\ChangedFiles;
|
||||
use Pest\Plugins\Tia\ConfigurationFile;
|
||||
use Pest\Plugins\Tia\ExternalSources;
|
||||
use Pest\Plugins\Tia\FileState;
|
||||
use Pest\Plugins\Tia\Fingerprint;
|
||||
use Pest\Plugins\Tia\Graph;
|
||||
@@ -161,14 +162,28 @@ final class Project
|
||||
return $this->pestWithEnvironment($directory, [], ...$arguments);
|
||||
}
|
||||
|
||||
public function pestFrom(string $directory, string $workingDirectory, string ...$arguments): PestResult
|
||||
{
|
||||
return $this->run($directory, $workingDirectory, [], array_values($arguments));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string|false> $environment
|
||||
*/
|
||||
public function pestWithEnvironment(string $directory, array $environment, string ...$arguments): PestResult
|
||||
{
|
||||
return $this->run($directory, $directory, $environment, array_values($arguments));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string|false> $environment
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
private function run(string $directory, string $workingDirectory, array $environment, array $arguments): PestResult
|
||||
{
|
||||
$process = new Process(
|
||||
[PHP_BINARY, $directory.'/vendor/pestphp/pest/bin/pest', ...$arguments],
|
||||
$directory,
|
||||
$workingDirectory,
|
||||
[
|
||||
...GitRepo::ENV,
|
||||
'COLLISION_PRINTER' => 'DefaultPrinter',
|
||||
@@ -185,6 +200,7 @@ final class Project
|
||||
'GITHUB_REF_NAME' => false,
|
||||
'GITLAB_CI' => false,
|
||||
'CIRCLECI' => false,
|
||||
'COMPOSER' => false,
|
||||
...$environment,
|
||||
],
|
||||
);
|
||||
@@ -193,7 +209,7 @@ final class Project
|
||||
$process->run();
|
||||
|
||||
return new PestResult(
|
||||
array_values($arguments),
|
||||
$arguments,
|
||||
$process->getOutput().$process->getErrorOutput(),
|
||||
(int) $process->getExitCode(),
|
||||
);
|
||||
@@ -204,24 +220,50 @@ final class Project
|
||||
*/
|
||||
public function seed(string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void
|
||||
{
|
||||
$this->seedFor($this->path, $branch, $sentinel, $failing, $configuration);
|
||||
$this->seedFor($this->path, $branch, $sentinel, $failing, $configuration === null ? [] : ['--configuration', $configuration]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $failing
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void
|
||||
public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = [], array $arguments = []): void
|
||||
{
|
||||
$this->graphRoot = $root;
|
||||
|
||||
ExternalSources::flush();
|
||||
|
||||
$previous = getcwd();
|
||||
|
||||
if ($previous !== false) {
|
||||
chdir($root);
|
||||
}
|
||||
|
||||
try {
|
||||
$this->seedGraphFor($root, $branch, $sentinel, $failing, $arguments);
|
||||
} finally {
|
||||
if ($previous !== false) {
|
||||
chdir($previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $failing
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
private function seedGraphFor(string $root, string $branch, bool $sentinel, array $failing, array $arguments): void
|
||||
{
|
||||
putenv('COMPOSER');
|
||||
|
||||
$changedFiles = new ChangedFiles($root);
|
||||
$sha = new GitRepo($root)->sha();
|
||||
|
||||
$graph = new Graph($root);
|
||||
$graph->setFingerprint(Fingerprint::compute($root, $configuration === null ? null : ConfigurationFile::at($root.DIRECTORY_SEPARATOR.$configuration)));
|
||||
$graph->setFingerprint(Fingerprint::compute($root, ConfigurationFile::fromArguments($arguments), $arguments));
|
||||
$graph->setRecordedAtSha($branch, $sha);
|
||||
|
||||
$graph->setLastRunTree($branch, $changedFiles->snapshotTree($changedFiles->since($sha) ?? []));
|
||||
$graph->setLastRunTree($branch, $changedFiles->baselineTree($sha, ExternalSources::ignoredInputs($root, $arguments)));
|
||||
|
||||
$graph->markKnownTestFiles(array_keys(self::EDGES));
|
||||
|
||||
|
||||
@@ -21,3 +21,36 @@ test('compute comparable coverage', function (float $givenValue, float $expected
|
||||
[32.57777771232132, 32.5],
|
||||
[100.0, 100.0],
|
||||
]);
|
||||
|
||||
test('coverage options accept a space separated value', function (array $arguments, float $min, ?float $exactly): void {
|
||||
$plugin = new Coverage(new NullOutput);
|
||||
|
||||
$plugin->handleArguments($arguments);
|
||||
|
||||
expect($plugin->coverageMin)->toBe($min)
|
||||
->and($plugin->coverageExactly)->toBe($exactly);
|
||||
})->with([
|
||||
'min with equals sign' => [['--min=50'], 50.0, null],
|
||||
'min with space' => [['--min', '50'], 50.0, null],
|
||||
'exactly with equals sign' => [['--exactly=100'], 0.0, 100.0],
|
||||
'exactly with space' => [['--exactly', '100'], 0.0, 100.0],
|
||||
'both with space' => [['--min', '50', '--exactly', '100'], 50.0, 100.0],
|
||||
]);
|
||||
|
||||
test('coverage options do not consume arguments owned by phpunit', function (): void {
|
||||
$plugin = new Coverage(new NullOutput);
|
||||
|
||||
$arguments = $plugin->handleArguments(['--min', '50', '--filter', 'add', 'tests/Unit']);
|
||||
|
||||
expect($plugin->coverageMin)->toBe(50.0)
|
||||
->and($arguments)->toBe(['--filter', 'add', 'tests/Unit']);
|
||||
});
|
||||
|
||||
test('value less coverage options do not consume the next argument', function (): void {
|
||||
$plugin = new Coverage(new NullOutput);
|
||||
|
||||
$arguments = $plugin->handleArguments(['--only-covered', '--filter', 'add']);
|
||||
|
||||
expect($plugin->showOnlyCovered)->toBeTrue()
|
||||
->and($arguments)->toBe(['--filter', 'add']);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
use Pest\Plugins\Concerns\HandleArguments;
|
||||
|
||||
test('pushArgument inserts before the option separator when the keys have gaps', function (): void {
|
||||
$argumentHandler = new class
|
||||
{
|
||||
use HandleArguments;
|
||||
};
|
||||
|
||||
$arguments = [0 => 'bin/pest', 2 => '--', 3 => 'tests/Fixtures/ExampleTest.php'];
|
||||
|
||||
expect($argumentHandler->pushArgument('--no-output', $arguments))
|
||||
->toBe(['bin/pest', '--no-output', '--', 'tests/Fixtures/ExampleTest.php']);
|
||||
});
|
||||
@@ -2,10 +2,15 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Exceptions\GitTimedOut;
|
||||
use Pest\Plugins\Tia\ChangedFiles;
|
||||
use Pest\Plugins\Tia\ExternalSources;
|
||||
use Pest\Plugins\Tia\Fingerprint;
|
||||
use Pest\Support\Git;
|
||||
use Symfony\Component\Process\ExecutableFinder;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Tests\Fixtures\Tia\GitRepo;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
@@ -51,6 +56,8 @@ afterEach(function (): void {
|
||||
foreach (tiaMonorepoRoots() as $root) {
|
||||
new Process(['rm', '-rf', $root])->run();
|
||||
}
|
||||
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
it('resolves the project prefix inside the repository', function (): void {
|
||||
@@ -285,3 +292,315 @@ it('reads committed paths from the repository root even when git is told to be r
|
||||
expect($changedFiles->since($monorepo['sha']))->toBe(['app/Service.php'])
|
||||
->and($changedFiles->outsideProject())->toBe(['frontend/widget.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('tells a working tree change outside the project from a committed one', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
|
||||
$monorepo['repo']->commit('rework the widget');
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/other.php', "<?php\n\$other = 1;\n");
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
$changedFiles->since($monorepo['sha']);
|
||||
|
||||
expect($changedFiles->outsideProject())->toBe(['frontend/widget.php', 'frontend/other.php'])
|
||||
->and($changedFiles->outsideProjectDirty())->toBe(['frontend/other.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('keeps a changed file whose name is a number as a string', function (): void {
|
||||
$project = Project::make();
|
||||
$sha = $project->git()->sha();
|
||||
|
||||
file_put_contents($project->path('123'), "changed\n");
|
||||
$project->git()->commit('add a file with a numeric name');
|
||||
|
||||
expect(new ChangedFiles($project->path())->since($sha))->toBe(['123']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('keeps a changed file outside the project whose name is a number as a string', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/123', "outside\n");
|
||||
file_put_contents($monorepo['project'].'/123', "inside\n");
|
||||
$monorepo['repo']->commit('add files with a numeric name');
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
|
||||
expect($changedFiles->since($monorepo['sha']))->toBe(['123'])
|
||||
->and($changedFiles->outsideProject())->toBe(['123']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('matches no external root for a changed file whose name is a number', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
$previous = (string) getcwd();
|
||||
|
||||
mkdir($monorepo['root'].'/packages/shared/src', 0755, true);
|
||||
file_put_contents($monorepo['root'].'/packages/shared/src/Shared.php', "<?php\n\$shared = 1;\n");
|
||||
file_put_contents($monorepo['project'].'/composer.json', (string) json_encode([
|
||||
'autoload' => ['psr-4' => ['Shared\\' => '../packages/shared/src']],
|
||||
], JSON_PRETTY_PRINT));
|
||||
$monorepo['repo']->commit('let the project load a sibling package');
|
||||
$sha = $monorepo['repo']->sha();
|
||||
|
||||
file_put_contents($monorepo['root'].'/123', "changed\n");
|
||||
$monorepo['repo']->commit('add a file with a numeric name');
|
||||
|
||||
chdir($monorepo['project']);
|
||||
ExternalSources::flush();
|
||||
|
||||
try {
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
$changedFiles->since($sha);
|
||||
|
||||
$matched = ExternalSources::matching($monorepo['project'], $changedFiles->outsideProject());
|
||||
} finally {
|
||||
chdir($previous);
|
||||
ExternalSources::flush();
|
||||
}
|
||||
|
||||
expect($matched)->toBeEmpty();
|
||||
})->skipOnWindows();
|
||||
|
||||
it('hashes an external input without reading it into memory', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
$handle = fopen($monorepo['root'].'/frontend/database.sqlite', 'wb');
|
||||
ftruncate($handle, 64 * 1024 * 1024);
|
||||
fclose($handle);
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
|
||||
memory_reset_peak_usage();
|
||||
$before = memory_get_peak_usage();
|
||||
|
||||
$tree = $changedFiles->baselineTree($monorepo['sha'], ['frontend/database.sqlite']);
|
||||
|
||||
expect(memory_get_peak_usage() - $before)->toBeLessThan(8 * 1024 * 1024)
|
||||
->and($tree)->toHaveKey('../frontend/database.sqlite');
|
||||
})->skipOnWindows();
|
||||
|
||||
it('sees a whitespace change inside an external input', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/data.js', "export default \"a b\";\n");
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
$tree = $changedFiles->baselineTree($monorepo['sha'], ['frontend/data.js']);
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/data.js', "export default \"a b\";\n");
|
||||
|
||||
expect($changedFiles->changedSinceLastRun([], ['frontend/data.js'], $tree))->toBe([[], ['frontend/data.js']]);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reports a changed file whose name looks like a pathspec', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['project'].'/:(fixtures).php', "<?php\n");
|
||||
|
||||
expect(new ChangedFiles($monorepo['project'])->since($monorepo['sha']))->toContain(':(fixtures).php');
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reports an external input that the listing no longer names', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/generated.php', "<?php\n");
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
$before = $changedFiles->externalInputHashes(['frontend/generated.php']);
|
||||
|
||||
expect($changedFiles->changedExternalInputs($before, $changedFiles->externalInputHashes([])))->toBe(['frontend/generated.php'])
|
||||
->and($changedFiles->changedExternalInputs($before, $changedFiles->externalInputHashes(['frontend/generated.php'])))->toBeEmpty();
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reports no change for an external input it cannot read', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/secret.php', "<?php\n");
|
||||
chmod($monorepo['root'].'/frontend/secret.php', 0000);
|
||||
|
||||
try {
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
|
||||
expect($changedFiles->changedExternalInputs(
|
||||
$changedFiles->externalInputHashes(['frontend/secret.php']),
|
||||
$changedFiles->externalInputHashes(['frontend/secret.php']),
|
||||
))->toBeEmpty();
|
||||
} finally {
|
||||
chmod($monorepo['root'].'/frontend/secret.php', 0644);
|
||||
}
|
||||
})->skipOnWindows()->skip(function_exists('posix_geteuid') && posix_geteuid() === 0, 'root reads every file.');
|
||||
|
||||
it('keeps a snapshotted file whose name is a number as a string', function (): void {
|
||||
$project = Project::make();
|
||||
|
||||
file_put_contents($project->path('123'), "changed\n");
|
||||
|
||||
expect(new ChangedFiles($project->path())->filterUnchangedSinceLastRun([], ['123' => 'stale']))->toBe(['123']);
|
||||
});
|
||||
|
||||
it('keeps a branch whose name is a number as a string', function (): void {
|
||||
$project = Project::make();
|
||||
$project->git()->switchTo('123', new: true);
|
||||
|
||||
expect(new ChangedFiles($project->path())->branchNames())->toBe(['123', 'master']);
|
||||
});
|
||||
|
||||
it('reads the baseline of many changed files and keeps their order', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
$project = $monorepo['project'];
|
||||
|
||||
foreach (['a', 'b', 'c', 'd', 'e'] as $name) {
|
||||
file_put_contents($project.'/app/'.$name.'.php', "<?php\n\$".$name." = 1;\n");
|
||||
}
|
||||
|
||||
$monorepo['repo']->commit('Add the files');
|
||||
$sha = $monorepo['repo']->sha();
|
||||
|
||||
file_put_contents($project.'/app/a.php', "<?php\n\$a = 2;\n");
|
||||
file_put_contents($project.'/app/c.php', "<?php\n\$c = 2;\n");
|
||||
$monorepo['repo']->commit('Change a and c');
|
||||
|
||||
file_put_contents($project.'/app/c.php', "<?php\n\$c = 1;\n");
|
||||
file_put_contents($project.'/app/d.php', "<?php\n\$d = 2;\n");
|
||||
unlink($project.'/app/b.php');
|
||||
file_put_contents($project.'/app/new.php', "<?php\n\$new = 1;\n");
|
||||
|
||||
expect(new ChangedFiles($project)->since($sha))
|
||||
->toBe(['app/a.php', 'app/b.php', 'app/d.php', 'app/new.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
/**
|
||||
* @param list<string> $paths
|
||||
* @return array{0: bool, 1: list<string|null>}
|
||||
*/
|
||||
function tiaShowEach(Git $git, string $sha, array $paths): array
|
||||
{
|
||||
$contents = array_fill(0, count($paths), 'not received');
|
||||
$succeeded = $git->showEach($sha, $paths, function (int $position, ?string $content) use (&$contents): void {
|
||||
$contents[$position] = $content;
|
||||
});
|
||||
|
||||
return [$succeeded, $contents];
|
||||
}
|
||||
|
||||
function tiaWithFakeCatFile(string $mode, string $catFile, Closure $run): mixed
|
||||
{
|
||||
$realGit = (string) new ExecutableFinder()->find('git');
|
||||
$directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-fake-git-'.bin2hex(random_bytes(8));
|
||||
mkdir($directory);
|
||||
file_put_contents($directory.'/git', "#!/bin/sh\nif [ \"\$1\" = cat-file ] && [ \"\$2\" = ".$mode." ]; then\n read -r first\n cat > /dev/null\n ".$catFile."\nfi\nexec ".escapeshellarg($realGit)." \"\$@\"\n");
|
||||
chmod($directory.'/git', 0755);
|
||||
|
||||
$path = (string) getenv('PATH');
|
||||
$envPath = $_ENV['PATH'] ?? null;
|
||||
$serverPath = $_SERVER['PATH'] ?? null;
|
||||
|
||||
putenv('PATH='.$directory.PATH_SEPARATOR.$path);
|
||||
$_SERVER['PATH'] = $_ENV['PATH'] = $directory.PATH_SEPARATOR.$path;
|
||||
|
||||
try {
|
||||
return $run();
|
||||
} finally {
|
||||
putenv('PATH='.$path);
|
||||
$_SERVER['PATH'] = $serverPath ?? $path;
|
||||
|
||||
if ($envPath !== null) {
|
||||
$_ENV['PATH'] = $envPath;
|
||||
} else {
|
||||
unset($_ENV['PATH']);
|
||||
}
|
||||
|
||||
new Process(['rm', '-rf', $directory])->run();
|
||||
}
|
||||
}
|
||||
|
||||
it('reads many baselines with one call and gives the same content as one call per file', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
$root = $monorepo['root'];
|
||||
|
||||
file_put_contents($root.'/empty.txt', '');
|
||||
file_put_contents($root.'/binary.bin', "\x00\n\x01\n\n");
|
||||
file_put_contents($root."/new\nline.txt", "line\n");
|
||||
file_put_contents($root."/return.txt\r", "carriage\n");
|
||||
$monorepo['repo']->commit('Add the files');
|
||||
|
||||
$git = new Git($root);
|
||||
$sha = $monorepo['repo']->sha();
|
||||
$paths = ['backend/app/Service.php', 'missing.php', 'empty.txt', 'backend', "new\nline.txt", 'binary.bin', "return.txt\r", 'frontend/widget.php'];
|
||||
|
||||
[$succeeded, $contents] = tiaShowEach($git, $sha, $paths);
|
||||
|
||||
expect($succeeded)->toBeTrue()
|
||||
->and($contents)->toBe(array_map(static fn (string $path): ?string => $git->show($sha, $path), $paths))
|
||||
->and($contents[3])->toStartWith('tree ');
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reads no baseline when the commit does not exist', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
expect(tiaShowEach(new Git($monorepo['root']), str_repeat('0', 40), ['backend/app/Service.php']))->toBe([true, [null]]);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reads the baseline of each file again when the batch fails', function (string $mode, string $catFile): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
$project = $monorepo['project'];
|
||||
|
||||
file_put_contents($project.'/app/Service.php', "<?php\n\$service = 2;\n");
|
||||
$monorepo['repo']->commit('Change the service');
|
||||
|
||||
file_put_contents($project.'/app/Service.php', "<?php\n\$service = 1;\n");
|
||||
file_put_contents($project.'/app/Other.php', "<?php\n\$other = 1;\n");
|
||||
|
||||
$git = new Git($monorepo['root']);
|
||||
|
||||
expect(tiaWithFakeCatFile($mode, $catFile, fn (): bool => tiaShowEach($git, $monorepo['sha'], ['backend/app/Service.php'])[0]))->toBeFalse()
|
||||
->and(tiaWithFakeCatFile($mode, $catFile, fn (): ?array => new ChangedFiles($project)->since($monorepo['sha'])))->toBe(['app/Other.php']);
|
||||
})->with([
|
||||
'a failed check' => ['--batch-check', 'exit 1'],
|
||||
'a check line that does not parse' => ['--batch-check', 'echo "not a header"; exit 0'],
|
||||
'a check without a line' => ['--batch-check', 'exit 0'],
|
||||
'a failed read' => ['--batch', 'exit 1'],
|
||||
'a header that does not parse after one blob' => ['--batch', 'printf "%s blob 1\nx\nnot a header\n" "$first"; exit 0'],
|
||||
'a missing blob' => ['--batch', 'exit 0'],
|
||||
'bytes after the last blob' => ['--batch', 'printf "%s blob 1\nx\nextra" "$first"; exit 0'],
|
||||
'a blob without its line feed' => ['--batch', 'printf "%s blob 1\nxy" "$first"; exit 0'],
|
||||
'another blob than the one asked' => ['--batch', 'printf "0123abcd blob 1\nx\n"; exit 0'],
|
||||
])->skipOnWindows();
|
||||
|
||||
it('raises a timed out read of the baseline blobs instead of answering', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
$git = new Git($monorepo['root'], 0.5);
|
||||
|
||||
expect(fn (): mixed => tiaWithFakeCatFile('--batch', 'sleep 5; exit 0', fn (): array => tiaShowEach($git, $monorepo['sha'], ['backend/app/Service.php'])))
|
||||
->toThrow(GitTimedOut::class, 'Git did not answer within 0.5 seconds: git cat-file --batch');
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reads the baseline of many large changed files within a small memory limit', function (): void {
|
||||
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-baseline-memory-'.bin2hex(random_bytes(8));
|
||||
mkdir($root, 0755, true);
|
||||
tiaMonorepoRoots($root);
|
||||
|
||||
$repo = new GitRepo($root);
|
||||
$repo->init('master');
|
||||
|
||||
foreach (range(1, 6) as $number) {
|
||||
file_put_contents($root.'/asset'.$number.'.bin', random_bytes(8_000_000));
|
||||
}
|
||||
|
||||
$repo->commit('Add the large assets');
|
||||
$sha = $repo->sha();
|
||||
|
||||
foreach (range(1, 6) as $number) {
|
||||
file_put_contents($root.'/asset'.$number.'.bin', 'x', FILE_APPEND);
|
||||
}
|
||||
|
||||
$script = 'require '.var_export(dirname(__DIR__, 4).'/vendor/autoload.php', true).';'
|
||||
.'echo json_encode(new Pest\Plugins\Tia\ChangedFiles('.var_export($root, true).')->since('.var_export($sha, true).'));';
|
||||
|
||||
$process = new Process([PHP_BINARY, '-d', 'memory_limit=64M', '-r', $script]);
|
||||
$process->run();
|
||||
|
||||
expect($process->getErrorOutput().$process->getOutput())->not->toContain('Allowed memory size')
|
||||
->and($process->getOutput())->toBe('["asset1.bin","asset2.bin","asset3.bin","asset4.bin","asset5.bin","asset6.bin"]');
|
||||
})->skipOnWindows();
|
||||
|
||||
@@ -215,3 +215,28 @@ it('tells an include path through a symlink to a directory with a separator in i
|
||||
}
|
||||
}
|
||||
})->skipOnWindows();
|
||||
|
||||
it('builds the source scope from the coverage filter and the source of the configuration', function (): void {
|
||||
mkdir($this->projectRoot.'/vendor/acme', 0755, true);
|
||||
file_put_contents($this->projectRoot.'/phpunit.xml', "<?xml version=\"1.0\"?>\n<phpunit><source><include><directory>lib</directory></include></source></phpunit>\n");
|
||||
$realRoot = (string) realpath($this->projectRoot);
|
||||
|
||||
$withoutFilter = ConfigurationFile::fromArguments(['--configuration', $this->projectRoot.'/phpunit.xml'])
|
||||
->sourceScope($this->projectRoot)
|
||||
?->coverageExcludePaths($this->projectRoot);
|
||||
$withFilter = ConfigurationFile::fromArguments(['--configuration', $this->projectRoot.'/phpunit.xml', '--coverage-filter', $realRoot.'/vendor/acme'])
|
||||
->sourceScope($this->projectRoot)
|
||||
?->coverageExcludePaths($this->projectRoot);
|
||||
|
||||
rmdir($this->projectRoot.'/vendor/acme');
|
||||
rmdir($this->projectRoot.'/vendor');
|
||||
|
||||
expect($withoutFilter)->toBe([$realRoot.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR])
|
||||
->and($withFilter)->toBe([]);
|
||||
});
|
||||
|
||||
it('gives no source scope when the configuration cannot be read', function (): void {
|
||||
file_put_contents($this->projectRoot.'/phpunit.xml', '<phpunit');
|
||||
|
||||
expect(ConfigurationFile::at($this->projectRoot.'/phpunit.xml')->sourceScope($this->projectRoot))->toBeNull();
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,7 @@
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\ConfigurationFile;
|
||||
use Pest\Plugins\Tia\ExternalSources;
|
||||
use Pest\Plugins\Tia\Fingerprint;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
@@ -107,6 +108,7 @@ describe('compute()', function (): void {
|
||||
fingerprintRemoveDirectory($clone);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the command line bootstrap and include path out of a run that sets neither', function (): void {
|
||||
$root = fingerprintRepository();
|
||||
|
||||
@@ -133,4 +135,59 @@ describe('compute()', function (): void {
|
||||
fingerprintRemoveDirectory($root);
|
||||
}
|
||||
});
|
||||
|
||||
it('tells a relative include path from the absolute path it names', function (): void {
|
||||
$root = (string) realpath(fingerprintRepository());
|
||||
$previous = getcwd();
|
||||
chdir($root);
|
||||
|
||||
try {
|
||||
$relativeFirst = Fingerprint::compute($root, null, ['--include-path', '.'.PATH_SEPARATOR.$root]);
|
||||
$absoluteFirst = Fingerprint::compute($root, null, ['--include-path', $root.PATH_SEPARATOR.'.']);
|
||||
|
||||
expect(Fingerprint::structuralMatches($relativeFirst, $absoluteFirst))->toBeFalse();
|
||||
} finally {
|
||||
chdir((string) $previous);
|
||||
fingerprintRemoveDirectory($root);
|
||||
}
|
||||
});
|
||||
|
||||
it('stores an include path whose name is not utf-8 as text json can encode', function (): void {
|
||||
$root = (string) realpath(fingerprintRepository());
|
||||
mkdir($root.'/app');
|
||||
file_put_contents($root.'/app/composer.json', '{}');
|
||||
fingerprintGit($root, 'add', '-A');
|
||||
fingerprintGit($root, 'commit', '-q', '-m', 'init');
|
||||
$previous = getcwd();
|
||||
chdir($root.'/app');
|
||||
ExternalSources::flush();
|
||||
|
||||
try {
|
||||
$fingerprint = Fingerprint::compute($root.'/app', null, ['--include-path', "../optional-\xff"]);
|
||||
|
||||
expect($fingerprint['structural'])->toHaveKeys(['external_roots', 'include_path'])
|
||||
->and(json_encode($fingerprint))->toBeString();
|
||||
} finally {
|
||||
chdir((string) $previous);
|
||||
ExternalSources::flush();
|
||||
fingerprintRemoveDirectory($root);
|
||||
}
|
||||
});
|
||||
|
||||
it('changes when the order of the include path changes and not when its spelling does', function (): void {
|
||||
$root = (string) realpath(fingerprintRepository());
|
||||
mkdir($root.'/a');
|
||||
mkdir($root.'/b');
|
||||
|
||||
try {
|
||||
$forward = Fingerprint::compute($root, null, ['--include-path', $root.'/a'.PATH_SEPARATOR.$root.'/b']);
|
||||
$respelled = Fingerprint::compute($root, null, ['--include-path', $root.'/./a/'.PATH_SEPARATOR.$root.'/b']);
|
||||
$reversed = Fingerprint::compute($root, null, ['--include-path', $root.'/b'.PATH_SEPARATOR.$root.'/a']);
|
||||
|
||||
expect(Fingerprint::structuralMatches($forward, $respelled))->toBeTrue()
|
||||
->and(Fingerprint::structuralMatches($forward, $reversed))->toBeFalse();
|
||||
} finally {
|
||||
fingerprintRemoveDirectory($root);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -410,6 +410,32 @@ describe('branch baseline over the fallback', function (): void {
|
||||
});
|
||||
});
|
||||
|
||||
describe('pruneMissingBranches()', function (): void {
|
||||
it('keeps a branch whose name is a number', function (): void {
|
||||
$graph = new Graph(sys_get_temp_dir());
|
||||
$graph->setRecordedAtSha('123', 'abc');
|
||||
$graph->setRecordedAtSha('gone', 'def');
|
||||
|
||||
$graph->pruneMissingBranches(['123']);
|
||||
|
||||
expect($graph->recordedAtSha('123'))->toBe('abc')
|
||||
->and($graph->recordedAtSha('gone'))->toBeNull()
|
||||
->and(Graph::branchesIn($graph->encode()))->toBe(['123']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('decode()', function (): void {
|
||||
it('keeps a file of the last run tree whose name is a number', function (): void {
|
||||
$graph = new Graph(sys_get_temp_dir());
|
||||
$graph->setRecordedAtSha('master', 'abc');
|
||||
$graph->setLastRunTree('master', ['123' => 'hash']);
|
||||
|
||||
$decoded = Graph::decode($graph->encode(), sys_get_temp_dir());
|
||||
|
||||
expect($decoded?->lastRunTree('master'))->toBe([123 => 'hash']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('encode() and decode()', function (): void {
|
||||
it('round-trips paths that are not valid UTF-8', function (): void {
|
||||
$root = sys_get_temp_dir();
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\Graph;
|
||||
use Pest\Plugins\Tia\Recorder;
|
||||
use Pest\Plugins\Tia\WatchPatterns;
|
||||
use Pest\Support\Container;
|
||||
|
||||
beforeEach(function (): void {
|
||||
Container::getInstance()->add(WatchPatterns::class, new WatchPatterns);
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
Container::getInstance()->add(WatchPatterns::class, new WatchPatterns);
|
||||
});
|
||||
|
||||
it('selects the tests of a changed Inertia page whose name is a number', function (): void {
|
||||
$root = (string) realpath(sys_get_temp_dir());
|
||||
$graph = new Graph($root);
|
||||
$graph->replaceTestInertiaComponents([
|
||||
$root.'/tests/Feature/NumericPageTest.php' => ['123'],
|
||||
$root.'/tests/Feature/DashboardTest.php' => ['Dashboard'],
|
||||
]);
|
||||
|
||||
expect($graph->affected(['resources/js/Pages/123.vue']))->toBe(['tests/Feature/NumericPageTest.php']);
|
||||
});
|
||||
|
||||
it('keeps an Inertia page whose name is a number after the graph is decoded', function (): void {
|
||||
$root = (string) realpath(sys_get_temp_dir());
|
||||
$graph = new Graph($root);
|
||||
$graph->replaceTestInertiaComponents([
|
||||
$root.'/tests/Feature/NumericPageTest.php' => ['123'],
|
||||
]);
|
||||
|
||||
$decoded = Graph::decode($graph->encode(), $root);
|
||||
|
||||
expect($decoded?->affected(['resources/js/Pages/123.vue']))->toBe(['tests/Feature/NumericPageTest.php']);
|
||||
});
|
||||
|
||||
it('records an Inertia page whose name is a number as a string', function (): void {
|
||||
$recorder = new Recorder;
|
||||
$recorder->activateLinkTracking();
|
||||
|
||||
$recorder->beginTest('Some\Missing\TestClass', 'it renders', '/project/tests/Feature/NumericPageTest.php');
|
||||
$recorder->linkInertiaComponent('123');
|
||||
$recorder->endTest();
|
||||
|
||||
expect($recorder->perTestInertiaComponents())->toBe(['/project/tests/Feature/NumericPageTest.php' => ['123']]);
|
||||
});
|
||||
|
||||
it('selects the tests of a shared module of an Inertia page whose name is a number', function (): void {
|
||||
$root = (string) realpath(sys_get_temp_dir());
|
||||
$graph = new Graph($root);
|
||||
$graph->replaceTestInertiaComponents([
|
||||
$root.'/tests/Feature/NumericPageTest.php' => ['123'],
|
||||
]);
|
||||
$graph->replaceJsFileToComponents(['resources/js/Components/Chart.vue' => ['123']]);
|
||||
|
||||
expect($graph->affected(['resources/js/Components/Chart.vue']))->toBe(['tests/Feature/NumericPageTest.php']);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\Graph;
|
||||
use Pest\Plugins\Tia\WatchPatterns;
|
||||
use Pest\Support\Container;
|
||||
|
||||
beforeEach(function (): void {
|
||||
Container::getInstance()->add(WatchPatterns::class, new WatchPatterns);
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
Container::getInstance()->add(WatchPatterns::class, new WatchPatterns);
|
||||
});
|
||||
|
||||
it('selects the tests of a changed source file whose name is a number', function (): void {
|
||||
$graph = new Graph(sys_get_temp_dir());
|
||||
$graph->link('tests/Feature/NumericTest.php', '123');
|
||||
$graph->link('tests/Feature/OtherTest.php', 'app/Other.php');
|
||||
|
||||
expect($graph->affected(['123']))->toBe(['tests/Feature/NumericTest.php']);
|
||||
});
|
||||
|
||||
it('selects the tests of a numeric source file after the graph is decoded', function (): void {
|
||||
$graph = new Graph(sys_get_temp_dir());
|
||||
$graph->link('tests/Feature/NumericTest.php', '123');
|
||||
|
||||
$decoded = Graph::decode($graph->encode(), sys_get_temp_dir());
|
||||
|
||||
expect($decoded?->affected(['123']))->toBe(['tests/Feature/NumericTest.php']);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\WatchPatterns;
|
||||
|
||||
it('matches a watch pattern whose key is a number', function (): void {
|
||||
$watchPatterns = new WatchPatterns;
|
||||
$watchPatterns->add(['123' => 'tests/Feature']);
|
||||
|
||||
expect($watchPatterns->matchedDirectories(sys_get_temp_dir(), ['123']))->toBe(['tests/Feature']);
|
||||
});
|
||||
|
||||
it('selects the tests under a watch target whose name is a number', function (): void {
|
||||
$watchPatterns = new WatchPatterns;
|
||||
$watchPatterns->add(['config.txt' => '123']);
|
||||
|
||||
$directories = $watchPatterns->matchedDirectories(sys_get_temp_dir(), ['config.txt']);
|
||||
|
||||
expect($directories)->toBe(['123'])
|
||||
->and($watchPatterns->testsUnderDirectories($directories, ['123/ConfigTest.php', 'tests/OtherTest.php']))
|
||||
->toBe(['123/ConfigTest.php']);
|
||||
});
|
||||
@@ -239,6 +239,40 @@ describe('the file wrapper', function (): void {
|
||||
]);
|
||||
});
|
||||
|
||||
it('reports why an include failed as plain PHP does while a test records', function (): void {
|
||||
$missing = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-read-capture-missing-'.bin2hex(random_bytes(8)).'.php';
|
||||
$results = [];
|
||||
$errorReporting = error_reporting(E_ALL);
|
||||
|
||||
set_error_handler(function (int $level, string $message, string $file, int $line): bool {
|
||||
if ((error_reporting() & $level) === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new ErrorException($message, 0, $level, $file, $line);
|
||||
});
|
||||
|
||||
try {
|
||||
tiaReadCaptureLinks(function () use ($missing, &$results): void {
|
||||
try {
|
||||
include $missing;
|
||||
} catch (ErrorException $exception) {
|
||||
$results['include'] = str_contains($exception->getMessage(), 'No such file or directory');
|
||||
}
|
||||
|
||||
$results['silenced include'] = @include $missing;
|
||||
});
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
error_reporting($errorReporting);
|
||||
}
|
||||
|
||||
expect($results)->toBe([
|
||||
'include' => true,
|
||||
'silenced include' => false,
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps no memory for each filesystem call while a test records', function (): void {
|
||||
$growth = 0;
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\Recorder;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
describe('activateLinkTracking()', function (): void {
|
||||
it('tracks tables without a coverage driver', function (): void {
|
||||
@@ -58,3 +59,86 @@ describe('activateLinkTracking()', function (): void {
|
||||
expect($recorder->perTestTables())->toBeEmpty();
|
||||
});
|
||||
});
|
||||
|
||||
describe('activate()', function (): void {
|
||||
it('keeps xdebug from tracing the vendor directory of the project', function (): void {
|
||||
$projectRoot = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-xdebug-filter-'.bin2hex(random_bytes(4));
|
||||
mkdir($projectRoot.'/app', 0755, true);
|
||||
mkdir($projectRoot.'/vendor/acme', 0755, true);
|
||||
file_put_contents($projectRoot.'/app/Inside.php', "<?php\nfunction pest_tia_inside(): int\n{\n return 1;\n}\n");
|
||||
file_put_contents($projectRoot.'/vendor/acme/Outside.php', "<?php\nfunction pest_tia_outside(): int\n{\n return 2;\n}\n");
|
||||
file_put_contents($projectRoot.'/record.php', sprintf(<<<'PHP'
|
||||
<?php
|
||||
require %s;
|
||||
\Pest\TestSuite::getInstance(%s, 'tests');
|
||||
(new \Pest\Plugins\Tia\Recorder)->activate(\Pest\Plugins\Tia\ConfigurationFile::projectDefault());
|
||||
require %s;
|
||||
require %s;
|
||||
\xdebug_start_code_coverage();
|
||||
pest_tia_inside();
|
||||
pest_tia_outside();
|
||||
echo json_encode(array_keys(\xdebug_get_code_coverage()));
|
||||
PHP,
|
||||
var_export(dirname(__DIR__, 4).'/vendor/autoload.php', true),
|
||||
var_export($projectRoot, true),
|
||||
var_export($projectRoot.'/app/Inside.php', true),
|
||||
var_export($projectRoot.'/vendor/acme/Outside.php', true),
|
||||
));
|
||||
|
||||
$process = new Process(
|
||||
[PHP_BINARY, '-d', 'pcov.enabled=0', $projectRoot.'/record.php'],
|
||||
$projectRoot,
|
||||
['XDEBUG_MODE' => 'coverage'],
|
||||
);
|
||||
$process->run();
|
||||
|
||||
$realRoot = (string) realpath($projectRoot);
|
||||
$traced = json_decode($process->getOutput(), true);
|
||||
|
||||
foreach (['app/Inside.php', 'vendor/acme/Outside.php', 'record.php'] as $file) {
|
||||
unlink($projectRoot.'/'.$file);
|
||||
}
|
||||
|
||||
rmdir($projectRoot.'/vendor/acme');
|
||||
rmdir($projectRoot.'/vendor');
|
||||
rmdir($projectRoot.'/app');
|
||||
rmdir($projectRoot);
|
||||
|
||||
expect($traced)->toBeArray($process->getErrorOutput().$process->getOutput())
|
||||
->toContain($realRoot.'/app/Inside.php')
|
||||
->not->toContain($realRoot.'/vendor/acme/Outside.php');
|
||||
})->skip(! extension_loaded('xdebug'), 'Xdebug is not installed.')->skipOnWindows();
|
||||
});
|
||||
|
||||
describe('recordOnly()', function (): void {
|
||||
it('records only the test files it accepts', function (): void {
|
||||
$recorder = new Recorder;
|
||||
$recorder->activateLinkTracking();
|
||||
$recorder->recordOnly(fn (string $testFile): bool => $testFile === '/project/tests/Feature/NewTest.php');
|
||||
|
||||
$recorder->beginTest('Some\Missing\TestClass', 'known', '/project/tests/Feature/KnownTest.php');
|
||||
$recorder->linkSource('/project/app/Known.php');
|
||||
$recorder->linkTable('known');
|
||||
$recorder->endTest();
|
||||
|
||||
$recorder->beginTest('Some\Missing\TestClass', 'new', '/project/tests/Feature/NewTest.php');
|
||||
$recorder->linkSource('/project/app/New.php');
|
||||
$recorder->endTest();
|
||||
|
||||
expect($recorder->perTestFiles())->toBe(['/project/tests/Feature/NewTest.php' => ['/project/app/New.php']])
|
||||
->and($recorder->perTestTables())->toBeEmpty();
|
||||
});
|
||||
|
||||
it('records each test file again after a reset', function (): void {
|
||||
$recorder = new Recorder;
|
||||
$recorder->recordOnly(fn (string $testFile): bool => false);
|
||||
$recorder->reset();
|
||||
$recorder->activateLinkTracking();
|
||||
|
||||
$recorder->beginTest('Some\Missing\TestClass', 'known', '/project/tests/Feature/KnownTest.php');
|
||||
$recorder->linkSource('/project/app/Known.php');
|
||||
$recorder->endTest();
|
||||
|
||||
expect($recorder->perTestFiles())->toBe(['/project/tests/Feature/KnownTest.php' => ['/project/app/Known.php']]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,3 +35,104 @@ describe('contains()', function (): void {
|
||||
->and($scope->contains('/project/storage/framework/views/compiled.php'))->toBeFalse();
|
||||
});
|
||||
});
|
||||
|
||||
describe('coverageExcludePaths()', function (): void {
|
||||
beforeEach(function (): void {
|
||||
$this->projectRoot = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-scope-'.bin2hex(random_bytes(4));
|
||||
mkdir($this->projectRoot.'/vendor/acme', 0755, true);
|
||||
mkdir($this->projectRoot.'/storage/framework', 0755, true);
|
||||
$this->realRoot = (string) realpath($this->projectRoot);
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
if (is_link($this->projectRoot.'/storage/framework')) {
|
||||
unlink($this->projectRoot.'/storage/framework');
|
||||
}
|
||||
|
||||
foreach (['vendor/acme', 'vendor', 'storage/framework', 'storage/Framework', 'storage/generated', 'storage/Generated', 'storage'] as $directory) {
|
||||
if (is_dir($this->projectRoot.'/'.$directory)) {
|
||||
rmdir($this->projectRoot.'/'.$directory);
|
||||
}
|
||||
}
|
||||
|
||||
rmdir($this->projectRoot);
|
||||
});
|
||||
|
||||
it('excludes each noise directory of the project that the scope rejects', function (): void {
|
||||
$scope = new SourceScope(
|
||||
[$this->realRoot.'/app'],
|
||||
[['path' => $this->realRoot.'/storage/framework', 'prefix' => '', 'suffix' => '']],
|
||||
);
|
||||
|
||||
expect($scope->coverageExcludePaths($this->projectRoot))->toBe([
|
||||
$this->realRoot.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR,
|
||||
$this->realRoot.DIRECTORY_SEPARATOR.'storage/framework'.DIRECTORY_SEPARATOR,
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps a noise directory that holds an included directory', function (): void {
|
||||
$scope = new SourceScope([$this->realRoot.'/vendor/acme'], []);
|
||||
|
||||
expect($scope->coverageExcludePaths($this->projectRoot))
|
||||
->toBe([$this->realRoot.DIRECTORY_SEPARATOR.'storage/framework'.DIRECTORY_SEPARATOR]);
|
||||
});
|
||||
|
||||
it('keeps a noise directory below an included directory', function (): void {
|
||||
$scope = new SourceScope([$this->realRoot], []);
|
||||
|
||||
expect($scope->coverageExcludePaths($this->projectRoot))->toBeEmpty();
|
||||
});
|
||||
|
||||
it('keeps a noise directory whose name an included directory shares in another case', function (): void {
|
||||
$scope = new SourceScope([$this->realRoot.'/Vendor'], []);
|
||||
|
||||
expect($scope->coverageExcludePaths($this->projectRoot))
|
||||
->toBe([$this->realRoot.DIRECTORY_SEPARATOR.'storage/framework'.DIRECTORY_SEPARATOR]);
|
||||
});
|
||||
|
||||
it('keeps a noise directory that has a sibling with the same name in another case', function (): void {
|
||||
rmdir($this->projectRoot.'/storage/framework');
|
||||
mkdir($this->projectRoot.'/storage/Framework');
|
||||
|
||||
if (! is_dir($this->projectRoot.'/storage/framework')) {
|
||||
mkdir($this->projectRoot.'/storage/framework');
|
||||
}
|
||||
|
||||
$scope = new SourceScope(
|
||||
[$this->realRoot.'/storage'],
|
||||
[['path' => $this->realRoot.'/storage/framework', 'prefix' => '', 'suffix' => '']],
|
||||
);
|
||||
|
||||
expect($scope->coverageExcludePaths($this->projectRoot))
|
||||
->toBe([$this->realRoot.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR]);
|
||||
});
|
||||
|
||||
it('keeps each noise directory when an included directory is the project root in another case', function (): void {
|
||||
$twinRoot = dirname($this->realRoot).DIRECTORY_SEPARATOR.strtoupper(basename($this->realRoot));
|
||||
$scope = new SourceScope(
|
||||
[$this->realRoot.'/app', $twinRoot],
|
||||
[['path' => $this->realRoot.'/storage/framework', 'prefix' => '', 'suffix' => '']],
|
||||
);
|
||||
|
||||
expect($scope->coverageExcludePaths($this->projectRoot))->toBeEmpty();
|
||||
});
|
||||
|
||||
it('keeps a linked noise directory whose target has a sibling with the same name in another case', function (): void {
|
||||
rmdir($this->projectRoot.'/storage/framework');
|
||||
mkdir($this->projectRoot.'/storage/Generated');
|
||||
|
||||
if (! is_dir($this->projectRoot.'/storage/generated')) {
|
||||
mkdir($this->projectRoot.'/storage/generated');
|
||||
}
|
||||
|
||||
symlink('generated', $this->projectRoot.'/storage/framework');
|
||||
|
||||
$scope = new SourceScope(
|
||||
[$this->realRoot.'/storage'],
|
||||
[['path' => $this->realRoot.'/storage/generated', 'prefix' => '', 'suffix' => '']],
|
||||
);
|
||||
|
||||
expect($scope->coverageExcludePaths($this->projectRoot))
|
||||
->toBe([$this->realRoot.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR]);
|
||||
})->skipOnWindows();
|
||||
});
|
||||
|
||||
@@ -49,3 +49,9 @@ describe('last', function (): void {
|
||||
->and(current($array))->toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stringKeys', function (): void {
|
||||
it('returns every key as a string', function (): void {
|
||||
expect(Arr::stringKeys(['123' => true, 'app/Service.php' => true]))->toBe(['123', 'app/Service.php']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Support\ComposerProject;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
it('reads the project root that composer recorded', function (): void {
|
||||
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-composer-project-'.bin2hex(random_bytes(8));
|
||||
mkdir($root.'/app/lib/deps/composer', 0755, true);
|
||||
file_put_contents($root.'/app/lib/deps/composer/installed.php', "<?php\n\nreturn ['root' => ['install_path' => ".var_export($root.'/app', true)."]];\n");
|
||||
|
||||
try {
|
||||
expect(ComposerProject::rootPath($root.'/app/lib/deps/autoload.php'))->toBe(realpath($root.'/app'));
|
||||
} finally {
|
||||
new Process(['rm', '-rf', $root])->run();
|
||||
}
|
||||
})->skipOnWindows();
|
||||
|
||||
it('falls back to the parent of the vendor directory when composer recorded no install path', function (): void {
|
||||
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-composer-project-'.bin2hex(random_bytes(8));
|
||||
mkdir($root.'/vendor/composer', 0755, true);
|
||||
file_put_contents($root.'/vendor/composer/installed.php', "<?php\n\nreturn ['root' => ['name' => '__root__'], 'versions' => []];\n");
|
||||
|
||||
try {
|
||||
expect(ComposerProject::rootPath($root.'/vendor/autoload.php'))->toBe(realpath($root));
|
||||
} finally {
|
||||
new Process(['rm', '-rf', $root])->run();
|
||||
}
|
||||
})->skipOnWindows();
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Exceptions\GitTimedOut;
|
||||
use Pest\Support\Git;
|
||||
|
||||
it('raises a timed out command instead of answering', function (string $method): void {
|
||||
$git = new Git(timeout: 0.2);
|
||||
|
||||
expect(fn (): mixed => $git->{$method}(['-c', 'alias.slow=!sleep 5', 'slow']))
|
||||
->toThrow(GitTimedOut::class, 'Git did not answer within 0.2 seconds: git -c alias.slow=!sleep 5 slow');
|
||||
})->with(['result', 'raw', 'output', 'succeeds'])->skipOnWindows();
|
||||
@@ -21,7 +21,7 @@ test('parallel', function () use ($run): void {
|
||||
$output = implode("\n", array_slice(explode("\n", (string) $output), -10));
|
||||
$profileOutput = $run('tests/Fixtures/Suites/SuccessOnly.php', '--profile');
|
||||
|
||||
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 31 skipped, 1872 passed (3978 assertions)';
|
||||
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 37 skipped, 2019 passed (4196 assertions)';
|
||||
|
||||
expect($output)
|
||||
->toContain("Tests: {$expected}")
|
||||
@@ -59,6 +59,31 @@ test('parallel lets extensions register event subscribers', function (): void {
|
||||
->toContain('Parallel: 2 processes');
|
||||
})->skipOnWindows();
|
||||
|
||||
test('sets Laravel parallel flags', function (array $options, array $databaseFlags): void {
|
||||
$process = new Process(
|
||||
[PHP_BINARY, '-d', 'auto_prepend_file=', 'tests/Fixtures/Suites/ParallelLaravelFlags.php', '--parallel', ...$options],
|
||||
dirname(__DIR__, 2),
|
||||
[
|
||||
'LARAVEL_PARALLEL_TESTING' => false,
|
||||
'LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES' => false,
|
||||
'LARAVEL_PARALLEL_TESTING_DROP_DATABASES' => false,
|
||||
],
|
||||
);
|
||||
|
||||
$process->mustRun();
|
||||
|
||||
$expectedFlags = ['LARAVEL_PARALLEL_TESTING', ...$databaseFlags];
|
||||
|
||||
expect(json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR))->toBe([
|
||||
'server' => $expectedFlags,
|
||||
'env' => $expectedFlags,
|
||||
]);
|
||||
})->with([
|
||||
'without database options' => [[], []],
|
||||
'recreate databases' => [['--recreate-databases'], ['LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES']],
|
||||
'drop databases' => [['--drop-databases'], ['LARAVEL_PARALLEL_TESTING_DROP_DATABASES']],
|
||||
]);
|
||||
|
||||
test('parallel can have multiple exclude-groups', function () use ($run): void {
|
||||
$singleExclude = $run('--exclude-group=integration');
|
||||
$doubleExclude = $run('--exclude-group=integration', '--exclude-group=container');
|
||||
@@ -137,3 +162,9 @@ test('parallel group-filtered run still fails when the selection matches no test
|
||||
expect(removeAnsiEscapeSequences($process->getOutput()))->toContain('No tests found.')
|
||||
->and($process->getExitCode())->toBe(1);
|
||||
})->skipOnWindows();
|
||||
|
||||
test('parallel accepts a path after the option separator', function () use ($run): void {
|
||||
expect($run('--', 'tests/Fixtures/ExampleTest.php'))
|
||||
->toContain('Tests: 1 passed (1 assertions)')
|
||||
->toContain('Parallel: 3 processes');
|
||||
})->skipOnWindows();
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
$run = function (array $arguments): Process {
|
||||
$process = new Process(
|
||||
['php', 'bin/pest', '--parallel', '--processes=2', ...$arguments, 'tests/Fixtures/ParallelIncludePath'],
|
||||
dirname(__DIR__, 2),
|
||||
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1'],
|
||||
);
|
||||
|
||||
$process->run();
|
||||
|
||||
return $process;
|
||||
};
|
||||
|
||||
test('parallel resolves requires through the include path', function (array $arguments) use ($run): void {
|
||||
$process = $run($arguments);
|
||||
$output = (string) removeAnsiEscapeSequences($process->getOutput());
|
||||
|
||||
expect($process->getExitCode())->toBe(0, $process->getErrorOutput().$output)
|
||||
->and($output)->toContain('Tests: 2 passed');
|
||||
})->with([
|
||||
'value in the same argument' => [['--include-path=tests/Fixtures/ParallelIncludePath/lib']],
|
||||
'value as a separate argument' => [['--include-path', 'tests/Fixtures/ParallelIncludePath/lib']],
|
||||
'absolute path' => [['--include-path='.__DIR__.'/../Fixtures/ParallelIncludePath/lib']],
|
||||
'several paths' => [['--include-path=tests/Fixtures/Inheritance'.PATH_SEPARATOR.'tests/Fixtures/ParallelIncludePath/lib']],
|
||||
'directory name with an equals sign' => [['--include-path', 'tests/Fixtures/ParallelIncludePath/include=path']],
|
||||
'absolute directory name with an equals sign' => [['--include-path', __DIR__.'/../Fixtures/ParallelIncludePath/include=path']],
|
||||
'require in the bootstrap file' => [['--bootstrap=tests/Fixtures/ParallelIncludePath/bootstrap.inc', '--include-path=tests/Fixtures/ParallelIncludePath/lib']],
|
||||
'command line before the XML include path' => [['--configuration=tests/Fixtures/ParallelIncludePath.xml', '--include-path=tests/Fixtures/ParallelIncludePath/lib']],
|
||||
'command line before the XML include path in the bootstrap file' => [['--configuration=tests/Fixtures/ParallelIncludePath.xml', '--bootstrap=tests/Fixtures/ParallelIncludePath/bootstrap.inc', '--include-path=tests/Fixtures/ParallelIncludePath/lib']],
|
||||
])->skipOnWindows();
|
||||
|
||||
test('parallel places the include path before the argument separator', function (): void {
|
||||
$process = new Process(
|
||||
['php', '-r', 'require "vendor/autoload.php"; echo json_encode((new Pest\\Plugins\\Parallel\\Handlers\\IncludePath)->handleArguments(["--include-path", "lib", "--", "tests/Foo"]));'],
|
||||
dirname(__DIR__, 2),
|
||||
);
|
||||
|
||||
$process->run();
|
||||
|
||||
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
|
||||
->and(json_decode($process->getOutput(), true))->toBe(['--include-path=lib', '--', 'tests/Foo']);
|
||||
});
|
||||
|
||||
test('parallel fails to resolve requires without the include path', function () use ($run): void {
|
||||
$process = $run([]);
|
||||
$output = (string) removeAnsiEscapeSequences($process->getOutput().$process->getErrorOutput());
|
||||
|
||||
expect($process->getExitCode())->not->toBe(0)
|
||||
->and($output)->toContain("Failed opening required 'parallel-include-path.inc'");
|
||||
})->skipOnWindows();
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
test('parallel keeps the leading space of an include path in the same argument as serial phpunit does', function (): void {
|
||||
$script = <<<'PHP_WRAP'
|
||||
require "vendor/autoload.php";
|
||||
$serial = (new PHPUnit\TextUI\CliArguments\Builder(PHPUnit\Event\Facade::emitter()))->fromParameters(["--include-path= lib"])->includePath();
|
||||
$handler = new Pest\Plugins\Parallel\Handlers\IncludePath;
|
||||
$forwarded = $handler->handleArguments(["--include-path= lib"]);
|
||||
echo json_encode(["serial" => $serial, "forwarded" => $forwarded, "first" => explode(PATH_SEPARATOR, get_include_path())[0], "worker" => $handler->handleWorkerArguments([])]);
|
||||
PHP_WRAP;
|
||||
|
||||
$process = new Process(['php', '-r', $script], dirname(__DIR__, 2));
|
||||
|
||||
$process->run();
|
||||
|
||||
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
|
||||
->and(json_decode($process->getOutput(), true))->toBe([
|
||||
'serial' => ' lib',
|
||||
'forwarded' => ['--include-path= lib'],
|
||||
'first' => ' lib',
|
||||
'worker' => ['--include-path= lib'],
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
test('parallel reads an include path option with a leading space as serial phpunit does', function (): void {
|
||||
$script = <<<'PHP_WRAP'
|
||||
require "vendor/autoload.php";
|
||||
$arguments = ["--include-path=first", " --include-path=lib"];
|
||||
$serial = (new PHPUnit\TextUI\CliArguments\Builder(PHPUnit\Event\Facade::emitter()))->fromParameters(["phpunit", ...$arguments])->includePath();
|
||||
$handler = new Pest\Plugins\Parallel\Handlers\IncludePath;
|
||||
$forwarded = $handler->handleArguments($arguments);
|
||||
echo json_encode(["serial" => $serial, "forwarded" => $forwarded, "worker" => $handler->handleWorkerArguments([])]);
|
||||
PHP_WRAP;
|
||||
|
||||
$process = new Process(['php', '-r', $script], dirname(__DIR__, 2));
|
||||
|
||||
$process->run();
|
||||
|
||||
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
|
||||
->and(json_decode($process->getOutput(), true))->toBe([
|
||||
'serial' => 'lib',
|
||||
'forwarded' => ['--include-path=lib'],
|
||||
'worker' => ['--include-path=lib'],
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
test('parallel workers keep the trailing space of an include path as serial phpunit does', function (): void {
|
||||
$script = <<<'PHP_WRAP'
|
||||
require "vendor/autoload.php";
|
||||
$read = fn (array $arguments): string => (new PHPUnit\TextUI\CliArguments\Builder(PHPUnit\Event\Facade::emitter()))->fromParameters(["phpunit", ...$arguments])->includePath();
|
||||
$arguments = ["--include-path=lib =extra"];
|
||||
$handler = new Pest\Plugins\Parallel\Handlers\IncludePath;
|
||||
$forwarded = $handler->handleArguments($arguments);
|
||||
echo json_encode(["serial" => $read($arguments), "forwarded" => $read($forwarded), "worker" => $read($handler->handleWorkerArguments([]))]);
|
||||
PHP_WRAP;
|
||||
|
||||
$process = new Process(['php', '-r', $script], dirname(__DIR__, 2));
|
||||
|
||||
$process->run();
|
||||
|
||||
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
|
||||
->and(json_decode($process->getOutput(), true))->toBe([
|
||||
'serial' => 'lib ',
|
||||
'forwarded' => 'lib ',
|
||||
'worker' => 'lib ',
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
test('parallel accepts an include path of whitespace as serial phpunit does', function (): void {
|
||||
$process = new Process(
|
||||
['php', 'bin/pest', '--parallel', '--processes=2', '--configuration=tests/Fixtures/ParallelIncludePath.xml', '--include-path', ' '],
|
||||
dirname(__DIR__, 2),
|
||||
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1'],
|
||||
);
|
||||
|
||||
$process->run();
|
||||
|
||||
$output = (string) removeAnsiEscapeSequences($process->getOutput().$process->getErrorOutput());
|
||||
|
||||
expect($output)->not->toContain('Required argument for option "--include-path" is missing')
|
||||
->and($process->getExitCode())->toBe(0, $output);
|
||||
})->skipOnWindows();
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
test('parallel keeps the pest runner when the include path option has no value', function (): void {
|
||||
$script = <<<'PHP_WRAP'
|
||||
require "vendor/autoload.php";
|
||||
$handlers = array_values(array_intersect(
|
||||
(new ReflectionClassConstant(Pest\Plugins\Parallel::class, "HANDLERS"))->getValue(),
|
||||
[Pest\Plugins\Parallel\Handlers\Parallel::class, Pest\Plugins\Parallel\Handlers\IncludePath::class],
|
||||
));
|
||||
$forwarded = array_reduce($handlers, fn (array $arguments, string $handler): array => (new $handler)->handleArguments($arguments), ["--parallel", "--include-path="]);
|
||||
echo json_encode(["runner" => in_array("--runner=".Pest\Plugins\Parallel\Paratest\WrapperRunner::class, $forwarded, true)]);
|
||||
PHP_WRAP;
|
||||
|
||||
$process = new Process(['php', '-r', $script], dirname(__DIR__, 2));
|
||||
|
||||
$process->run();
|
||||
|
||||
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
|
||||
->and(json_decode($process->getOutput(), true))->toBe(['runner' => true]);
|
||||
});
|
||||
@@ -47,3 +47,15 @@ test('a non-empty shard runs its assigned test', function (): void {
|
||||
expect($process->getExitCode())->toBe(0)
|
||||
->and($process->getOutput())->toContain('1 passed', '1 of 2 — 1 file ran, out of 1.');
|
||||
});
|
||||
|
||||
test('shard accepts a path after the option separator', function (): void {
|
||||
$process = new Process(
|
||||
['php', 'bin/pest', '--shard=1/2', '--', 'tests/Fixtures/ExampleTest.php'],
|
||||
dirname(__DIR__, 2),
|
||||
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1'],
|
||||
);
|
||||
|
||||
$process->run();
|
||||
|
||||
expect(removeAnsiEscapeSequences($process->getOutput()))->toContain('Tests: 1 passed (1 assertions)');
|
||||
})->skipOnWindows();
|
||||
|
||||
@@ -79,3 +79,15 @@ it('disable decorating printer when colors is set to never', function () use ($s
|
||||
$output = $process->getOutput();
|
||||
expect($output)->toContain($snapshot('disable-decorating-printer'));
|
||||
})->skipOnWindows();
|
||||
|
||||
test('allows to run a single test after the option separator', function (): void {
|
||||
$process = new Process(
|
||||
['php', 'bin/pest', '--', 'tests/Fixtures/ExampleTest.php'],
|
||||
dirname(__DIR__, 2),
|
||||
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1'],
|
||||
);
|
||||
|
||||
$process->run();
|
||||
|
||||
expect(removeAnsiEscapeSequences($process->getOutput()))->toContain('Tests: 1 passed (1 assertions)');
|
||||
})->skipOnWindows();
|
||||
|
||||
Reference in New Issue
Block a user