mirror of
https://github.com/pestphp/pest.git
synced 2026-12-03 22:45:06 +01:00
Compare commits
35 Commits
fabc818ba9
...
5.x
| Author | SHA1 | Date | |
|---|---|---|---|
| 12bddc0137 | |||
| f5874c12ca | |||
| 557aca75a0 | |||
| 5b534641e4 | |||
| edb56ae412 | |||
| 8c635c5ba0 | |||
| b5851d67ff | |||
| d314fc0540 | |||
| 093ca57693 | |||
| cf21b7cd64 | |||
| a6a919c32c | |||
| fa6e96486e | |||
| 249a120d89 | |||
| 8d004b80d7 | |||
| 12f3cd80de | |||
| dc73ec009e | |||
| 5bb349dcf2 | |||
| 1f60dc8f9a | |||
| b75cf904b7 | |||
| 0fe7c2440c | |||
| 4c886b16d1 | |||
| 8c87eefebf | |||
| 4cfeb458fe | |||
| 5cb7a1c043 | |||
| a2d3e6badd | |||
| 66e585081a | |||
| 9a6ceb0699 | |||
| 996b5ee8f5 | |||
| 776a44a391 | |||
| 89999bdaed | |||
| f5c3687a68 | |||
| 41af35a3f2 | |||
| fdc57f77b7 | |||
| 67d3733eb2 | |||
| f80b3a89a0 |
@@ -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
|
||||
|
||||
@@ -32,16 +32,14 @@ We cannot thank our sponsors enough for their incredible support in funding Pest
|
||||
- **[PhpStorm](https://jb.gg/nuno)**
|
||||
- **[CodeRabbit](https://coderabbit.link/nunomaduro)**
|
||||
- **[SerpApi](https://serpapi.com/?ref=nunomaduro)**
|
||||
- **[Bento](https://bentonow.com/?ref=nunomaduro)**
|
||||
- **[CMS Max](https://cmsmax.com/?ref=nunomaduro)**
|
||||
- **[Redberry](https://redberry.international/laravel-development/?utm_source=pest&utm_medium=banner&utm_campaign=pest_sponsorship)**
|
||||
- **[Typesense](https://typesense.org/?ref=nunomaduro)**
|
||||
- **[Pixel](https://wearepixel.com.au/?ref=nunomaduro)**
|
||||
- **[NativePHP](https://nativephp.com/?ref=nunomaduro)**
|
||||
- [TestMu AI](https://www.testmuai.com/?utm_medium=sponsor&utm_source=pest)
|
||||
- [Zapiet](https://zapiet.com/?ref=nunomaduro)
|
||||
- [LoadForge](https://loadforge.com/?ref=nunomaduro)
|
||||
- [Route4Me](https://route4me.com/?ref=nunomaduro)
|
||||
- [Nerdify](https://getnerdify.com/?ref=nunomaduro)
|
||||
- [Pushery](https://www.pushery.com/?ref=nunomaduro)
|
||||
- [LFCarry](https://lfcarry.com/?ref=nunomaduro)
|
||||
|
||||
Pest is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
|
||||
|
||||
@@ -129,6 +129,60 @@ use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
}
|
||||
}
|
||||
|
||||
$optionsWithSeparateValue = [
|
||||
'-c', '-d', '--atleast-version', '--bootstrap', '--cache-directory', '--columns', '--configuration',
|
||||
'--coverage-filter', '--coverage-clover', '--coverage-cobertura', '--coverage-crap4j', '--coverage-html',
|
||||
'--coverage-jsonl', '--coverage-openclover', '--coverage-php', '--coverage-xml', '--default-time-limit',
|
||||
'--diff-context', '--exclude-group', '--filter', '--exclude-filter', '--generate-baseline', '--use-baseline',
|
||||
'--group', '--covers', '--uses', '--requires-php-extension', '--include-path', '--list-tests-xml',
|
||||
'--log-junit', '--log-otr', '--log-teamcity', '--order-by', '--random-order-seed', '--repeat',
|
||||
'--timeout', '--testdox-html', '--testdox-text', '--test-suffix', '--testsuite', '--exclude-testsuite',
|
||||
'--test-files-file', '--test-id-filter-file', '--run-test-id', '--log-events-text',
|
||||
'--log-events-verbose-text', '--extension',
|
||||
];
|
||||
|
||||
$isOptionValue = false;
|
||||
|
||||
// Convert namespace-style arguments (e.g. Tests\Unit\TestName) to file paths.
|
||||
foreach ($arguments as $key => $value) {
|
||||
if ($isOptionValue) {
|
||||
$isOptionValue = false;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_starts_with($value, '-')) {
|
||||
$isOptionValue = in_array($value, $optionsWithSeparateValue, true);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! str_contains($value, '\\')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$path = str_replace('\\', DIRECTORY_SEPARATOR, $value);
|
||||
|
||||
if (! str_ends_with($path, '.php')) {
|
||||
$path .= '.php';
|
||||
}
|
||||
|
||||
if (file_exists($path)) {
|
||||
$arguments[$key] = $path;
|
||||
|
||||
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);
|
||||
|
||||
if (file_exists($lowercasedPath)) {
|
||||
$arguments[$key] = $lowercasedPath;
|
||||
}
|
||||
}
|
||||
|
||||
// Used when Pest is required using composer.
|
||||
$autoloadPath = $GLOBALS['_composer_autoload_path'] ?? dirname(__DIR__, 3).'/autoload.php';
|
||||
|
||||
@@ -138,6 +192,7 @@ use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
|
||||
include_once $autoloadPath;
|
||||
|
||||
$GLOBALS['_composer_autoload_path'] = $autoloadPath;
|
||||
$GLOBALS['_composer_bin_dir'] ??= dirname($autoloadPath).'/bin';
|
||||
$rootPath = ComposerProject::rootPath($autoloadPath);
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ const PAGE_EXTENSIONS = new Set([
|
||||
'.mts', '.cts', '.mjs', '.cjs',
|
||||
])
|
||||
const SFC_RE = /\.(vue|svelte)$/i
|
||||
const SCRIPT_BLOCK_RE = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi
|
||||
const SCRIPT_BLOCK_RE = /<script\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/script>/gi
|
||||
const ASSET_EXT_RE = /\.(css|scss|sass|less|styl|stylus|svg|png|jpe?g|gif|webp|avif|ico|bmp|woff2?|ttf|eot|otf|md|mdx|txt|html|mp4|webm|mp3|wav|ogg|m4a|pdf|wasm|glsl|frag|vert)$/i
|
||||
const PROJECT_ROOT = resolve(process.argv[2] ?? process.cwd())
|
||||
const PAGE_DIR_CANDIDATES = [
|
||||
@@ -25,8 +25,8 @@ const PAGE_DIR_CANDIDATES = [
|
||||
'assets/pages',
|
||||
]
|
||||
|
||||
async function loadRolldown() {
|
||||
const projectRequire = createRequire(join(PROJECT_ROOT, 'package.json'))
|
||||
export async function loadRolldown(projectRoot = PROJECT_ROOT) {
|
||||
const projectRequire = createRequire(join(projectRoot, 'package.json'))
|
||||
let path = null
|
||||
|
||||
try { path = projectRequire.resolve('rolldown') } catch {}
|
||||
@@ -40,6 +40,10 @@ async function loadRolldown() {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (path === null) {
|
||||
try { path = projectRequire.resolve('vite/rolldown') } catch {}
|
||||
}
|
||||
|
||||
if (path === null) return null
|
||||
|
||||
return await import(pathToFileURL(path).href)
|
||||
|
||||
@@ -43,9 +43,11 @@ $bootPest = (static function (string $rootPath): void {
|
||||
'testdox-columns:',
|
||||
'testdox-summary',
|
||||
'phpunit-argv:',
|
||||
'composer-autoload:',
|
||||
]);
|
||||
|
||||
$composerAutoloadFiles = [
|
||||
...(isset($getopt['composer-autoload']) && is_string($getopt['composer-autoload']) ? [$getopt['composer-autoload']] : []),
|
||||
dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'autoload.php',
|
||||
dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php',
|
||||
dirname(__DIR__).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php',
|
||||
|
||||
+3
-3
@@ -26,7 +26,7 @@
|
||||
"pestphp/pest-plugin-mutate": "^5.0.2",
|
||||
"pestphp/pest-plugin-profanity": "^5.0.1",
|
||||
"phpunit/phpunit": "^13.4.7",
|
||||
"symfony/process": "^8.1.10"
|
||||
"symfony/process": "^8.1.12"
|
||||
},
|
||||
"conflict": {
|
||||
"filp/whoops": "<2.18.3",
|
||||
@@ -63,8 +63,8 @@
|
||||
"pestphp/pest-dev-tools": "^5.0.0",
|
||||
"pestphp/pest-plugin-browser": "^5.2.0",
|
||||
"pestphp/pest-plugin-phpstan": "^5.3.1",
|
||||
"pestphp/pest-plugin-rector": "^5.0.6",
|
||||
"pestphp/pest-plugin-type-coverage": "^5.1.0",
|
||||
"pestphp/pest-plugin-rector": "^5.0.7",
|
||||
"pestphp/pest-plugin-type-coverage": "^5.1.1",
|
||||
"phpstan/phpstan": "^2.3.5 <2.3.6",
|
||||
"psy/psysh": "^0.12.24"
|
||||
},
|
||||
|
||||
@@ -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>
|
||||
|
||||
+1
-4
@@ -7,9 +7,7 @@ use Pest\Rector\Set\PestSetList;
|
||||
use Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector;
|
||||
use Rector\CodingStyle\Rector\ArrowFunction\ArrowFunctionDelegatingCallToFirstClassCallableRector;
|
||||
use Rector\Config\RectorConfig;
|
||||
use Rector\DeadCode\Rector\ClassMethod\RemoveDuplicatedReturnSelfDocblockRector;
|
||||
use Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector;
|
||||
use Rector\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector;
|
||||
use Rector\DeadCode\Rector\ClassMethod\RemoveReturnTagIncompatibleWithNativeTypeRector;
|
||||
use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedConstructorParamRector;
|
||||
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessUnionReturnDocblockRector;
|
||||
@@ -30,11 +28,10 @@ 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,
|
||||
RemoveParentDelegatingConstructorRector::class,
|
||||
RemoveDuplicatedReturnSelfDocblockRector::class,
|
||||
RemoveUselessUnionReturnDocblockRector::class,
|
||||
RemoveReturnTagIncompatibleWithNativeTypeRector::class => [
|
||||
__DIR__.'/src/Expectations/HigherOrderExpectation.php',
|
||||
|
||||
@@ -36,7 +36,7 @@ final class BootFiles implements Bootstrapper
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
if ($this->runningInit()) {
|
||||
if ($this->hasCliOption('--init')) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -44,6 +44,10 @@ final class BootFiles implements Bootstrapper
|
||||
$testsPath = $rootPath.DIRECTORY_SEPARATOR.testDirectory();
|
||||
|
||||
if (! is_dir($testsPath)) {
|
||||
if ($this->hasCliOption('--help', '--version')) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new FatalException(sprintf('The test directory [%s] does not exist.', $testsPath));
|
||||
}
|
||||
|
||||
@@ -69,7 +73,7 @@ final class BootFiles implements Bootstrapper
|
||||
$this->bootDatasets($testsPath);
|
||||
}
|
||||
|
||||
private function runningInit(): bool
|
||||
private function hasCliOption(string ...$options): bool
|
||||
{
|
||||
$arguments = $_SERVER['argv'] ?? null;
|
||||
|
||||
@@ -78,7 +82,7 @@ final class BootFiles implements Bootstrapper
|
||||
}
|
||||
|
||||
/** @var array<int, string> $arguments */
|
||||
return $this->hasArgument('--init', $arguments);
|
||||
return array_any($options, fn (string $option): bool => $this->hasArgument($option, $arguments));
|
||||
}
|
||||
|
||||
private function load(string $filename): void
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Contracts\Plugins;
|
||||
|
||||
interface ObservesExitCode
|
||||
{
|
||||
public function observeExitCode(int $exitCode): void;
|
||||
}
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Exceptions;
|
||||
|
||||
use NunoMaduro\Collision\Contracts\RenderlessEditor;
|
||||
use NunoMaduro\Collision\Contracts\RenderlessTrace;
|
||||
use Pest\Contracts\Panicable;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Exception\ExceptionInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class TiaRequiresRepositoryRoot extends RuntimeException implements ExceptionInterface, Panicable, RenderlessEditor, RenderlessTrace
|
||||
{
|
||||
public function __construct(private readonly string $subdirectoryPrefix)
|
||||
{
|
||||
parent::__construct(sprintf(
|
||||
'Tia mode requires the project root to be the git repository root, but this project sits in the subdirectory [%s] of a larger repository. Please give it its own repository to use Tia.',
|
||||
$this->subdirectoryPrefix,
|
||||
));
|
||||
}
|
||||
|
||||
public function render(OutputInterface $output): void
|
||||
{
|
||||
$output->writeln([
|
||||
'',
|
||||
' <fg=white;options=bold;bg=red> ERROR </> Tia mode requires the git repository root.',
|
||||
'',
|
||||
sprintf(' This project sits in a subdirectory of a larger repo <fg=yellow>%s</>.', $this->subdirectoryPrefix),
|
||||
'',
|
||||
' Give the project its own git repository to use Tia.',
|
||||
'',
|
||||
]);
|
||||
}
|
||||
|
||||
public function exitCode(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ namespace Pest\PendingCalls;
|
||||
|
||||
use Closure;
|
||||
use Pest\PendingCalls\Concerns\Describable;
|
||||
use Pest\Support\Arr;
|
||||
use Pest\Support\Backtrace;
|
||||
use Pest\Support\ChainableClosure;
|
||||
use Pest\Support\HigherOrderMessageCollection;
|
||||
@@ -43,7 +42,7 @@ final class AfterEachCall
|
||||
$proxies = $this->proxies;
|
||||
|
||||
$afterEachTestCase = ChainableClosure::boundWhen(
|
||||
fn (): bool => $describing === [] || in_array(Arr::last($describing), $this->__describing, true),
|
||||
fn (): bool => $describing === [] || (count($describing) <= count($this->__describing) && array_slice($this->__describing, 0, count($describing)) === $describing),
|
||||
ChainableClosure::bound(fn () => $proxies->chain($this), $this->closure)->bindTo($this, self::class),
|
||||
)->bindTo($this, self::class);
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ namespace Pest\PendingCalls;
|
||||
use Closure;
|
||||
use Pest\Exceptions\AfterBeforeTestFunction;
|
||||
use Pest\PendingCalls\Concerns\Describable;
|
||||
use Pest\Support\Arr;
|
||||
use Pest\Support\Backtrace;
|
||||
use Pest\Support\ChainableClosure;
|
||||
use Pest\Support\HigherOrderMessageCollection;
|
||||
@@ -50,11 +49,9 @@ final class BeforeEachCall
|
||||
$beforeEachTestCall = function (TestCall $testCall) use ($describing): void {
|
||||
|
||||
if ($this->describing !== []) {
|
||||
if (Arr::last($describing) !== Arr::last($this->describing)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! in_array(Arr::last($describing), $testCall->describing, true)) {
|
||||
$testCallDescribing = $testCall->describing;
|
||||
if (count($describing) > count($testCallDescribing) ||
|
||||
array_slice($testCallDescribing, 0, count($describing)) !== $describing) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -63,7 +60,7 @@ final class BeforeEachCall
|
||||
};
|
||||
|
||||
$beforeEachTestCase = ChainableClosure::boundWhen(
|
||||
fn (): bool => $describing === [] || in_array(Arr::last($describing), $this->__describing, true),
|
||||
fn (): bool => $describing === [] || (count($describing) <= count($this->__describing) && array_slice($this->__describing, 0, count($describing)) === $describing),
|
||||
ChainableClosure::bound(fn () => $testCaseProxies->chain($this), $this->closure)->bindTo($this, self::class),
|
||||
)->bindTo($this, self::class);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\PendingCalls;
|
||||
|
||||
use AllowDynamicProperties;
|
||||
use Closure;
|
||||
use Pest\Concerns\Testable;
|
||||
use Pest\Exceptions\InvalidArgumentException;
|
||||
@@ -34,7 +35,8 @@ use PHPUnit\Framework\TestCase;
|
||||
*
|
||||
* @mixin HigherOrderCallables|TestCase|Testable
|
||||
*/
|
||||
final class TestCall // @phpstan-ignore-line
|
||||
#[AllowDynamicProperties] // @phpstan-ignore-line
|
||||
final class TestCall
|
||||
{
|
||||
use Describable;
|
||||
|
||||
|
||||
@@ -7,20 +7,24 @@ namespace Pest\Plugins\Actions;
|
||||
use Pest\Contracts\Plugins;
|
||||
use Pest\Plugin\Loader;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class CallsAddsOutput
|
||||
{
|
||||
public static function execute(int $exitCode): int
|
||||
{
|
||||
$plugins = Loader::getPlugins(Plugins\AddsOutput::class);
|
||||
|
||||
/** @var Plugins\AddsOutput $plugin */
|
||||
foreach ($plugins as $plugin) {
|
||||
assert($plugin instanceof Plugins\AddsOutput);
|
||||
|
||||
$exitCode = $plugin->addOutput($exitCode);
|
||||
}
|
||||
|
||||
foreach (Loader::getPlugins(Plugins\ObservesExitCode::class) as $plugin) {
|
||||
assert($plugin instanceof Plugins\ObservesExitCode);
|
||||
|
||||
$plugin->observeExitCode($exitCode);
|
||||
}
|
||||
|
||||
return $exitCode;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,11 @@ final class Configuration implements HandlesArguments, Terminable
|
||||
return $this->pushArgument((string) realpath($this->fromGeneratedConfigurationFile()), $arguments);
|
||||
}
|
||||
|
||||
public function generatedConfigurationPath(): ?string
|
||||
{
|
||||
return $this->generatedConfiguration['path'] ?? null;
|
||||
}
|
||||
|
||||
private function fromGeneratedConfigurationFile(): string
|
||||
{
|
||||
$directory = getcwd();
|
||||
|
||||
+54
-17
@@ -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;
|
||||
@@ -47,23 +57,7 @@ final class Coverage implements AddsOutput, HandlesArguments
|
||||
*/
|
||||
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);
|
||||
@@ -121,6 +115,49 @@ final class Coverage implements AddsOutput, HandlesArguments
|
||||
return $originals;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
|
||||
@@ -146,7 +146,7 @@ final readonly class Help implements HandlesArguments
|
||||
],
|
||||
[
|
||||
'arg' => '--update-shards',
|
||||
'desc' => 'Update shards.json with test timing data for time-balanced sharding',
|
||||
'desc' => 'Update the shards file with timing data for time-balanced sharding',
|
||||
],
|
||||
], ...$content['Execution']];
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins;
|
||||
|
||||
use Composer\InstalledVersions;
|
||||
use Pest\Console\Thanks;
|
||||
use Pest\Contracts\Plugins\HandlesArguments;
|
||||
use Pest\Support\InstalledPackages;
|
||||
use Pest\Support\View;
|
||||
use Pest\TestSuite;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
@@ -96,11 +96,11 @@ final readonly class Init implements HandlesArguments
|
||||
|
||||
View::render('components.new-line');
|
||||
|
||||
(new Thanks($this->input, $this->output))();
|
||||
new Thanks($this->input, $this->output)();
|
||||
}
|
||||
|
||||
private function isLaravelInstalled(): bool
|
||||
{
|
||||
return InstalledVersions::isInstalled('laravel/framework');
|
||||
return InstalledPackages::has('laravel/framework');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -150,6 +151,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;
|
||||
}
|
||||
|
||||
@@ -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, '=');
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ declare(strict_types=1);
|
||||
namespace Pest\Plugins\Parallel\Handlers;
|
||||
|
||||
use Closure;
|
||||
use Composer\InstalledVersions;
|
||||
use Illuminate\Testing\ParallelRunner;
|
||||
use Orchestra\Testbench\TestCase;
|
||||
use ParaTest\Options;
|
||||
@@ -13,6 +12,7 @@ use ParaTest\RunnerInterface;
|
||||
use Pest\Contracts\Plugins\HandlesArguments;
|
||||
use Pest\Plugins\Concerns\HandleArguments;
|
||||
use Pest\Plugins\Parallel\Paratest\WrapperRunner;
|
||||
use Pest\Support\InstalledPackages;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
@@ -43,7 +43,7 @@ final class Laravel implements HandlesArguments
|
||||
*/
|
||||
private function whenUsingLaravel(array $arguments, Closure $closure): array
|
||||
{
|
||||
$isLaravelApplication = InstalledVersions::isInstalled('laravel/framework', false);
|
||||
$isLaravelApplication = InstalledPackages::has('laravel/framework', false);
|
||||
$isLaravelPackage = class_exists(TestCase::class);
|
||||
|
||||
if ($isLaravelApplication && ! $isLaravelPackage) {
|
||||
@@ -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);
|
||||
|
||||
@@ -156,6 +156,10 @@ final class WrapperRunner implements RunnerInterface
|
||||
$parameters[] = $wrapper;
|
||||
$parameters[] = '--test-directory='.TestSuite::getInstance()->testPath;
|
||||
|
||||
if (is_string($GLOBALS['_composer_autoload_path'] ?? null)) {
|
||||
$parameters[] = '--composer-autoload='.$GLOBALS['_composer_autoload_path'];
|
||||
}
|
||||
|
||||
$this->parameters = $parameters;
|
||||
$this->codeCoverageFilterRegistry = new CodeCoverageFilterRegistry;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ final class Retry implements HandlesArguments
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
if ($this->hasArgument('--parallel', $arguments)) {
|
||||
if ($this->hasArgument('--parallel', $arguments) || in_array('-p', $arguments, true)) {
|
||||
throw new InvalidOption('The [--retry] option is not supported when running in parallel.');
|
||||
}
|
||||
|
||||
|
||||
+301
-65
@@ -31,6 +31,26 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
|
||||
private const string CLASS_END = "\0";
|
||||
|
||||
/**
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
private const array PARATEST_ONLY_OPTIONS = [
|
||||
'--processes' => true,
|
||||
'--runner' => true,
|
||||
'--max-batch-size' => true,
|
||||
'-m' => true,
|
||||
'--max-processes' => true,
|
||||
'--passthru-php' => true,
|
||||
'--tmp-dir' => true,
|
||||
'--functional' => false,
|
||||
'--no-test-tokens' => false,
|
||||
];
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
private const array PARATEST_ONLY_SHORT_OPTIONS_WITH_VALUE = ['-m'];
|
||||
|
||||
/**
|
||||
* @var array{
|
||||
* index: int,
|
||||
@@ -43,6 +63,23 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
|
||||
private static bool $updateShards = false;
|
||||
|
||||
private static ?string $timingsFilename = null;
|
||||
|
||||
/**
|
||||
* @var array<string, float|array{time: float, tests: list<string>}>|null
|
||||
*/
|
||||
private static ?array $externalTimings = null;
|
||||
|
||||
/**
|
||||
* @var array<string, bool>|null
|
||||
*/
|
||||
private static ?array $ownership = null;
|
||||
|
||||
/**
|
||||
* @var array<string, scalar>
|
||||
*/
|
||||
private static array $metadata = [];
|
||||
|
||||
private static bool $timeBalanced = false;
|
||||
|
||||
private static bool $shardsOutdated = false;
|
||||
@@ -50,7 +87,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
private static bool $passed = false;
|
||||
|
||||
/**
|
||||
* @var array<string, float>|null
|
||||
* @var array<string, float|array{time: float, tests: list<string>}>|null
|
||||
*/
|
||||
private static ?array $collectedTimings = null;
|
||||
|
||||
@@ -65,6 +102,48 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
//
|
||||
}
|
||||
|
||||
public static function useTimingsFile(string $filename): void
|
||||
{
|
||||
self::$timingsFilename = $filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, float|array{time: float, tests: list<string>}> $units
|
||||
* @param array<string, scalar> $metadata Stored alongside the units, and read back
|
||||
* by {@see self::metadata()} on sharded runs.
|
||||
*/
|
||||
public static function useTimings(array $units, array $metadata = []): void
|
||||
{
|
||||
self::$externalTimings = $units;
|
||||
|
||||
if ($metadata !== []) {
|
||||
self::$metadata = $metadata;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, scalar>
|
||||
*/
|
||||
public static function metadata(): array
|
||||
{
|
||||
return self::$metadata;
|
||||
}
|
||||
|
||||
public static function owns(string $unit): bool
|
||||
{
|
||||
if (self::$ownership === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! isset(self::$ownership[$unit])) {
|
||||
self::$shardsOutdated = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return self::$ownership[$unit];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@@ -98,20 +177,33 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
|
||||
$tests = $this->allTests($arguments);
|
||||
|
||||
$timings = $this->loadShardsFile();
|
||||
if ($timings !== null) {
|
||||
$knownTests = array_values(array_filter($tests, fn (string $test): bool => isset($timings[$test])));
|
||||
$newTests = array_values(array_diff($tests, $knownTests));
|
||||
$units = $this->loadShardsFile();
|
||||
if ($units !== null) {
|
||||
$hasRemovedTests = array_diff($this->testsOf($units), $tests) !== [];
|
||||
|
||||
$partitions = $this->partitionByTime($knownTests, $timings, $total);
|
||||
$units = $this->withoutRemovedTests($units, $tests);
|
||||
|
||||
$newTests = array_values(array_diff($tests, $this->testsOf($units)));
|
||||
|
||||
$partitions = $this->partitionByTime($units, $total);
|
||||
|
||||
$median = $this->medianTime($units);
|
||||
|
||||
foreach ($newTests as $i => $test) {
|
||||
$partitions[$i % $total][] = $test;
|
||||
$partitions[$i % $total][$test] = ['time' => $median, 'tests' => [$test]];
|
||||
}
|
||||
|
||||
$testsToRun = $partitions[$index - 1] ?? [];
|
||||
$selected = $partitions[$index - 1] ?? [];
|
||||
|
||||
self::$ownership = [];
|
||||
|
||||
foreach ($partitions as $i => $partition) {
|
||||
self::$ownership += array_fill_keys(array_keys($partition), $i === $index - 1);
|
||||
}
|
||||
self::$timeBalanced = true;
|
||||
self::$shardsOutdated = $newTests !== [];
|
||||
self::$shardsOutdated = $newTests !== [] || $hasRemovedTests;
|
||||
|
||||
$testsToRun = array_values(array_intersect($tests, $this->testsOf($selected)));
|
||||
} else {
|
||||
$isInCurrentShard = fn (int $key): bool => $key % $total === ($index - 1);
|
||||
$testsToRun = array_values(array_filter($tests, $isInCurrentShard, ARRAY_FILTER_USE_KEY));
|
||||
@@ -198,31 +290,65 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
}
|
||||
}
|
||||
|
||||
if ($argument === '--runner') {
|
||||
$skipNext = true;
|
||||
if (in_array($argument, ['--parallel', '-p'], strict: true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->isAttachedParatestShortOption($argument)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$option] = explode('=', $argument, 2);
|
||||
|
||||
if (! array_key_exists($option, self::PARATEST_ONLY_OPTIONS)) {
|
||||
$filtered[] = $argument;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($argument, ['--parallel', '-p'], strict: true)
|
||||
|| str_starts_with($argument, '--processes')
|
||||
|| str_starts_with($argument, '--runner=')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$filtered[] = $argument;
|
||||
$skipNext = self::PARATEST_ONLY_OPTIONS[$option] && ! str_contains($argument, '=');
|
||||
}
|
||||
|
||||
return $filtered;
|
||||
}
|
||||
|
||||
private function isAttachedParatestShortOption(string $argument): bool
|
||||
{
|
||||
if (strlen($argument) <= 2 || str_starts_with($argument, '--')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return in_array(substr($argument, 0, 2), self::PARATEST_ONLY_SHORT_OPTIONS_WITH_VALUE, strict: true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $arguments
|
||||
* @return list<string>
|
||||
*/
|
||||
private function buildListTestsCommand(array $arguments, string $testPath): array
|
||||
{
|
||||
$filtered = $this->removeParallelArguments($arguments);
|
||||
$filtered = [];
|
||||
$skipNext = false;
|
||||
|
||||
foreach ($this->removeParallelArguments($arguments) as $argument) {
|
||||
if ($skipNext) {
|
||||
$skipNext = false;
|
||||
|
||||
if (! str_starts_with($argument, '-')) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (preg_match('/^--(?:coverage-(?:php|html|clover|xml|cobertura|crap4j|openclover|jsonl|filter)|min|exactly)$/', $argument) === 1) {
|
||||
$skipNext = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! str_starts_with($argument, '--coverage')) {
|
||||
$filtered[] = $argument;
|
||||
}
|
||||
}
|
||||
|
||||
return [PHP_BINARY, ...$filtered, '--test-directory='.$testPath, '--list-tests'];
|
||||
}
|
||||
@@ -314,15 +440,16 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
{
|
||||
self::$passed = $exitCode === 0;
|
||||
|
||||
if (self::$updateShards && self::$passed && ! Parallel::isWorker()) {
|
||||
if (self::$updateShards && (self::$passed || self::$externalTimings !== null) && ! Parallel::isWorker()) {
|
||||
self::$collectedTimings = $this->collectTimings();
|
||||
}
|
||||
|
||||
$count = self::$knownTests !== null
|
||||
? count(array_intersect_key(self::$collectedTimings, array_flip(self::$knownTests)))
|
||||
: count(self::$collectedTimings);
|
||||
if (self::$collectedTimings !== null && self::$collectedTimings !== []) {
|
||||
$count = count($this->unitsToWrite(self::$collectedTimings));
|
||||
|
||||
$this->output->writeln(sprintf(
|
||||
' <fg=gray>Shards:</> <fg=default>shards.json updated with timings for %d test class%s.</>',
|
||||
' <fg=gray>Shards:</> <fg=default>%s updated with timings for %d test class%s.</>',
|
||||
$this->timingsFilename(),
|
||||
$count,
|
||||
$count === 1 ? '' : 'es',
|
||||
));
|
||||
@@ -350,7 +477,10 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
));
|
||||
|
||||
if (self::$shardsOutdated) {
|
||||
$this->output->writeln(' <fg=yellow;options=bold>WARN</> <fg=default>The [tests/.pest/shards.json] file is out of date. Run [--update-shards] to update it.</>');
|
||||
$this->output->writeln(sprintf(
|
||||
' <fg=yellow;options=bold>WARN</> <fg=default>The [%s] file is out of date. Run [--update-shards] to update it.</>',
|
||||
$this->relativeTimingsPath(),
|
||||
));
|
||||
}
|
||||
|
||||
return $exitCode;
|
||||
@@ -368,7 +498,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
return;
|
||||
}
|
||||
|
||||
if (! self::$passed) {
|
||||
if (! self::$passed && self::$externalTimings === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -382,17 +512,17 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, float>
|
||||
* @return array<string, float|array{time: float, tests: list<string>}>
|
||||
*/
|
||||
private function collectTimings(): array
|
||||
{
|
||||
$runId = Parallel::getGlobal('SHARD_RUN_ID');
|
||||
|
||||
if (is_string($runId)) {
|
||||
return $this->readWorkerTimings($runId);
|
||||
}
|
||||
$collected = is_string($runId)
|
||||
? $this->readWorkerTimings($runId)
|
||||
: EnsureShardTimingsAreCollected::timings();
|
||||
|
||||
return EnsureShardTimingsAreCollected::timings();
|
||||
return self::$externalTimings ?? $collected;
|
||||
}
|
||||
|
||||
private function writeWorkerTimings(): void
|
||||
@@ -447,15 +577,46 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
return $merged;
|
||||
}
|
||||
|
||||
private function timingsFilename(): string
|
||||
{
|
||||
return self::$timingsFilename ?? 'shards.json';
|
||||
}
|
||||
|
||||
private function relativeTimingsPath(): string
|
||||
{
|
||||
return implode(DIRECTORY_SEPARATOR, [TestSuite::getInstance()->testPath, '.pest', $this->timingsFilename()]);
|
||||
}
|
||||
|
||||
private function shardsPath(): string
|
||||
{
|
||||
$testSuite = TestSuite::getInstance();
|
||||
|
||||
return implode(DIRECTORY_SEPARATOR, [$testSuite->rootPath, $testSuite->testPath, '.pest', 'shards.json']);
|
||||
return TestSuite::getInstance()->rootPath.DIRECTORY_SEPARATOR.$this->relativeTimingsPath();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, float>|null
|
||||
* @param array<string, mixed> $units
|
||||
* @return array<string, array{time: float, tests: list<string>}>
|
||||
*/
|
||||
private function normaliseUnits(array $units): array
|
||||
{
|
||||
$normalised = [];
|
||||
|
||||
foreach ($units as $key => $unit) {
|
||||
if (is_array($unit) && isset($unit['time']) && isset($unit['tests']) && is_array($unit['tests'])) {
|
||||
$normalised[$key] = ['time' => (float) $unit['time'], 'tests' => array_values(array_map(strval(...), $unit['tests']))];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_float($unit) || is_int($unit)) {
|
||||
$normalised[$key] = ['time' => (float) $unit, 'tests' => [$key]];
|
||||
}
|
||||
}
|
||||
|
||||
return $normalised;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{time: float, tests: list<string>}>|null
|
||||
*/
|
||||
private function loadShardsFile(): ?array
|
||||
{
|
||||
@@ -468,50 +629,95 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
$contents = file_get_contents($path);
|
||||
|
||||
if ($contents === false) {
|
||||
throw new InvalidOption('The [tests/.pest/shards.json] file could not be read. Delete it or run [--update-shards] to regenerate.');
|
||||
throw new InvalidOption(sprintf('The [%s] file could not be read. Delete it or run [--update-shards] to regenerate.', $this->relativeTimingsPath()));
|
||||
}
|
||||
|
||||
$data = json_decode($contents, true);
|
||||
|
||||
if (! is_array($data) || ! isset($data['timings']) || ! is_array($data['timings'])) {
|
||||
throw new InvalidOption('The [tests/.pest/shards.json] file is corrupted. Delete it or run [--update-shards] to regenerate.');
|
||||
$units = null;
|
||||
|
||||
if (is_array($data)) {
|
||||
$units = $data['units'] ?? $data['timings'] ?? null;
|
||||
}
|
||||
|
||||
return $data['timings'];
|
||||
if (! is_array($units)) {
|
||||
throw new InvalidOption(sprintf('The [%s] file is corrupted. Delete it or run [--update-shards] to regenerate.', $this->relativeTimingsPath()));
|
||||
}
|
||||
|
||||
if (isset($data['metadata']) && is_array($data['metadata'])) {
|
||||
self::$metadata = array_filter($data['metadata'], is_scalar(...));
|
||||
}
|
||||
|
||||
return $this->normaliseUnits($units);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array{time: float, tests: list<string>}> $units
|
||||
* @param list<string> $tests
|
||||
* @param array<string, float> $timings
|
||||
* @return list<list<string>>
|
||||
* @return array<string, array{time: float, tests: list<string>}>
|
||||
*/
|
||||
private function partitionByTime(array $tests, array $timings, int $total): array
|
||||
private function withoutRemovedTests(array $units, array $tests): array
|
||||
{
|
||||
$knownTimings = array_filter(
|
||||
array_map(fn (string $test): ?float => $timings[$test] ?? null, $tests),
|
||||
fn (?float $t): bool => $t !== null,
|
||||
);
|
||||
$live = [];
|
||||
|
||||
$median = $knownTimings !== [] ? $this->median(array_values($knownTimings)) : 1.0;
|
||||
foreach ($units as $key => $unit) {
|
||||
$declared = $unit['tests'];
|
||||
$unit['tests'] = array_values(array_intersect($declared, $tests));
|
||||
|
||||
$testsWithTimings = array_map(
|
||||
fn (string $test): array => ['test' => $test, 'time' => $timings[$test] ?? $median],
|
||||
$tests,
|
||||
);
|
||||
if ($declared === [] || $unit['tests'] !== []) {
|
||||
$live[$key] = $unit;
|
||||
}
|
||||
}
|
||||
|
||||
usort($testsWithTimings, fn (array $a, array $b): int => $b['time'] <=> $a['time']);
|
||||
return $live;
|
||||
}
|
||||
|
||||
/** @var list<list<string>> */
|
||||
/**
|
||||
* @param array<string, array{time: float, tests: list<string>}> $units
|
||||
* @return list<string>
|
||||
*/
|
||||
private function testsOf(array $units): array
|
||||
{
|
||||
$tests = [];
|
||||
|
||||
foreach ($units as $unit) {
|
||||
foreach ($unit['tests'] as $test) {
|
||||
$tests[$test] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return array_keys($tests);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array{time: float, tests: list<string>}> $units
|
||||
*/
|
||||
private function medianTime(array $units): float
|
||||
{
|
||||
$times = array_column($units, 'time');
|
||||
|
||||
return $times === [] ? 1.0 : $this->median($times);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array{time: float, tests: list<string>}> $units
|
||||
* @return list<array<string, array{time: float, tests: list<string>}>>
|
||||
*/
|
||||
private function partitionByTime(array $units, int $total): array
|
||||
{
|
||||
uasort($units, fn (array $a, array $b): int => $b['time'] <=> $a['time']);
|
||||
|
||||
/** @var list<array<string, array{time: float, tests: list<string>}>> */
|
||||
$bins = array_fill(0, $total, []);
|
||||
/** @var non-empty-list<float> */
|
||||
$binTimes = array_fill(0, $total, 0.0);
|
||||
|
||||
foreach ($testsWithTimings as $item) {
|
||||
foreach ($units as $key => $unit) {
|
||||
$minIndex = array_search(min($binTimes), $binTimes, strict: true);
|
||||
assert(is_int($minIndex));
|
||||
|
||||
$bins[$minIndex][] = $item['test'];
|
||||
$binTimes[$minIndex] += $item['time'];
|
||||
$bins[$minIndex][$key] = $unit;
|
||||
$binTimes[$minIndex] += $unit['time'];
|
||||
}
|
||||
|
||||
return $bins;
|
||||
@@ -535,9 +741,32 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, float> $timings
|
||||
* @param array<string, float|array{time: float, tests: list<string>}> $units
|
||||
* @return array<string, array{time: float, tests: list<string>}>
|
||||
*/
|
||||
private function writeTimings(array $timings): void
|
||||
private function unitsToWrite(array $units): array
|
||||
{
|
||||
$units = $this->normaliseUnits($units);
|
||||
|
||||
if (self::$knownTests === null) {
|
||||
return $units;
|
||||
}
|
||||
|
||||
$known = self::$knownTests;
|
||||
|
||||
$units = array_filter($units, fn (array $unit): bool => $unit['tests'] === [] || array_intersect($unit['tests'], $known) !== []);
|
||||
|
||||
foreach (array_diff($known, $this->testsOf($units)) as $test) {
|
||||
$units[$test] = ['time' => 0.0, 'tests' => [$test]];
|
||||
}
|
||||
|
||||
return $units;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, float|array{time: float, tests: list<string>}> $units
|
||||
*/
|
||||
private function writeTimings(array $units): void
|
||||
{
|
||||
$path = $this->shardsPath();
|
||||
|
||||
@@ -546,18 +775,25 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
mkdir($directory, 0755, true);
|
||||
}
|
||||
|
||||
if (self::$knownTests !== null) {
|
||||
$knownSet = array_flip(self::$knownTests);
|
||||
$timings = array_intersect_key($timings, $knownSet);
|
||||
}
|
||||
$bundled = self::$externalTimings !== null && array_filter($units, is_array(...)) !== [];
|
||||
|
||||
ksort($timings);
|
||||
$units = $this->unitsToWrite($units);
|
||||
|
||||
$canonical = self::$knownTests ?? array_keys($timings);
|
||||
ksort($units);
|
||||
|
||||
$canonical = self::$knownTests ?? $this->testsOf($units);
|
||||
sort($canonical);
|
||||
|
||||
$payload = $bundled
|
||||
? ['units' => $units]
|
||||
: ['timings' => array_map(fn (array $unit): float => $unit['time'], $units)];
|
||||
|
||||
if (self::$metadata !== []) {
|
||||
$payload['metadata'] = self::$metadata;
|
||||
}
|
||||
|
||||
file_put_contents($path, json_encode([
|
||||
'timings' => $timings,
|
||||
...$payload,
|
||||
'checksum' => md5(implode("\n", $canonical)),
|
||||
'updated_at' => date('c'),
|
||||
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");
|
||||
|
||||
+446
-66
@@ -4,11 +4,13 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins;
|
||||
|
||||
use JsonException;
|
||||
use NunoMaduro\Collision\Adapters\Phpunit\Printers\DefaultPrinter;
|
||||
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;
|
||||
@@ -17,15 +19,16 @@ use Pest\Exceptions\TiaGitFailed;
|
||||
use Pest\Exceptions\TiaRequiresCommit;
|
||||
use Pest\Exceptions\TiaRequiresDefaultBranch;
|
||||
use Pest\Exceptions\TiaRequiresRemote;
|
||||
use Pest\Exceptions\TiaRequiresRepositoryRoot;
|
||||
use Pest\Panic;
|
||||
use Pest\Plugins\Concerns\HandleArguments;
|
||||
use Pest\Plugins\Tia\BaselineSync;
|
||||
use Pest\Plugins\Tia\ByteSafeJson;
|
||||
use Pest\Plugins\Tia\ChangedFiles;
|
||||
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;
|
||||
@@ -35,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;
|
||||
@@ -190,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;
|
||||
@@ -202,6 +216,11 @@ 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 $flushesWorkerResults = false;
|
||||
@@ -223,6 +242,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
private ?string $freshGraphReason = null;
|
||||
|
||||
private ?string $graphEncodeError = null;
|
||||
|
||||
public function __construct(
|
||||
private readonly OutputInterface $output,
|
||||
private readonly Recorder $recorder,
|
||||
@@ -311,15 +332,26 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
private function saveGraph(Graph $graph): bool
|
||||
{
|
||||
$json = $graph->encode();
|
||||
try {
|
||||
$json = $graph->encode();
|
||||
} catch (JsonException $exception) {
|
||||
$this->graphEncodeError = $exception->getMessage();
|
||||
|
||||
if ($json === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->graphEncodeError = null;
|
||||
|
||||
return $this->state->write(self::KEY_GRAPH, $json);
|
||||
}
|
||||
|
||||
private function renderGraphWriteFailure(): void
|
||||
{
|
||||
$this->renderBadge('ERROR', $this->graphEncodeError === null
|
||||
? 'Could not write the dependency graph.'
|
||||
: sprintf('Could not write the dependency graph: %s.', $this->graphEncodeError));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
@@ -382,8 +414,6 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors {@see HandleArguments::hasArgument()} for
|
||||
*
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
private static function argumentPresent(string $argument, array $arguments): bool
|
||||
@@ -465,17 +495,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $this->cachedAssertionsByTestId[$testId] ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function handleOriginalArguments(array $arguments): void
|
||||
{
|
||||
$this->originalArguments = $arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function handleArguments(array $arguments): array
|
||||
{
|
||||
if ($this->hasArgument(self::BASELINE_PATH_OPTION, $arguments)) {
|
||||
@@ -484,7 +508,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
exit(0);
|
||||
}
|
||||
|
||||
$this->configuration = ConfigurationFile::fromArguments($arguments);
|
||||
$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';
|
||||
@@ -644,7 +671,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.');
|
||||
@@ -663,12 +690,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);
|
||||
@@ -678,7 +713,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$this->seedResultsInto($graph);
|
||||
|
||||
if (! $this->saveGraph($graph)) {
|
||||
$this->renderBadge('ERROR', 'Could not write the dependency graph.');
|
||||
$this->renderGraphWriteFailure();
|
||||
$recorder->reset();
|
||||
|
||||
return;
|
||||
@@ -738,7 +773,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.');
|
||||
@@ -761,12 +796,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);
|
||||
@@ -790,7 +835,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$graph->replaceJsFileToComponents(JsModuleGraph::build($projectRoot));
|
||||
|
||||
if (! $this->saveGraph($graph)) {
|
||||
$this->renderBadge('ERROR', 'Could not write the dependency graph.');
|
||||
$this->renderGraphWriteFailure();
|
||||
|
||||
return $exitCode;
|
||||
}
|
||||
@@ -865,12 +910,6 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
{
|
||||
$this->watchPatterns->useDefaults($projectRoot);
|
||||
|
||||
$subdirectoryPrefix = $this->gitSubdirectoryPrefix($projectRoot);
|
||||
|
||||
if ($subdirectoryPrefix !== null) {
|
||||
Panic::with(new TiaRequiresRepositoryRoot($subdirectoryPrefix));
|
||||
}
|
||||
|
||||
try {
|
||||
$this->resolveBranch($projectRoot);
|
||||
} catch (MissingDependency|TiaGitFailed $missingGit) {
|
||||
@@ -889,9 +928,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
: 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();
|
||||
@@ -927,6 +967,18 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->holdsDirtyExternalSources($projectRoot) || $this->holdsUnverifiableExternalSources($projectRoot)) {
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$uncommittedPhpChanges = $this->uncommittedPhpChangesOutsideProject($projectRoot);
|
||||
|
||||
if ($uncommittedPhpChanges !== []) {
|
||||
$this->recordNothingForUncommittedPhpChangesOutsideProject($uncommittedPhpChanges);
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$coverageCacheOwned = $this->piggybackCoverage && $this->pestCoverageActive();
|
||||
|
||||
if ($coverageCacheOwned) {
|
||||
@@ -954,6 +1006,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('Running the full suite, 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('Running the full suite, 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('Running the full suite, 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 ([
|
||||
@@ -1037,7 +1217,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return;
|
||||
}
|
||||
|
||||
$decoded = json_decode($raw, true);
|
||||
$decoded = ByteSafeJson::decode($raw);
|
||||
|
||||
if (! is_array($decoded)) {
|
||||
return;
|
||||
@@ -1106,16 +1286,68 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
Panic::with(new TiaBaselineCommitMissing((string) $branchSha));
|
||||
}
|
||||
|
||||
$changed = $changedFiles->filterUnchangedSinceLastRun(
|
||||
$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();
|
||||
|
||||
$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);
|
||||
}
|
||||
|
||||
$hasProjectPhpSourceChanges = $this->hasProjectPhpSourceChanges($changed);
|
||||
$coverageAvailable = $this->piggybackCoverage || $this->recorder->driverAvailable();
|
||||
|
||||
if ($hasProjectPhpSourceChanges && ! $coverageAvailable) {
|
||||
$this->fullSuiteFallbackRan = true;
|
||||
$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.');
|
||||
@@ -1143,7 +1375,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
...$rerunFromCache,
|
||||
]));
|
||||
|
||||
$this->reportAffectedSummary($changed, $affectedFromChanges, $rerunFromCache, $affected);
|
||||
$this->reportAffectedSummary($changed, $affectedFromChanges, $rerunFromCache, $affected, $outsideProject);
|
||||
|
||||
$affectedSet = array_fill_keys($affected, true);
|
||||
$canRefreshReplayEdges = $affected !== [] && $coverageAvailable;
|
||||
@@ -1208,13 +1440,15 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
* @param array<int, string> $affectedFromChanges
|
||||
* @param array<int, string> $rerunFromCache
|
||||
* @param array<int, string> $affected
|
||||
* @param array<int, string> $outsideProject
|
||||
*/
|
||||
private function reportAffectedSummary(array $changedFiles, array $affectedFromChanges, array $rerunFromCache, array $affected): void
|
||||
private function reportAffectedSummary(array $changedFiles, array $affectedFromChanges, array $rerunFromCache, array $affected, array $outsideProject = []): void
|
||||
{
|
||||
$this->output->writeln('');
|
||||
|
||||
if ($affected === []) {
|
||||
$this->renderChild('Experimental TIA mode enabled.');
|
||||
$this->reportChangesOutsideProject($outsideProject);
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -1277,6 +1511,124 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
if ($remainder > 0) {
|
||||
$this->output->writeln(sprintf(' <fg=gray>… +%d more</>', $remainder));
|
||||
}
|
||||
|
||||
$this->reportChangesOutsideProject($outsideProject);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function uncommittedPhpChangesOutsideProject(string $projectRoot): array
|
||||
{
|
||||
$changedFiles = new ChangedFiles($projectRoot);
|
||||
|
||||
if ($changedFiles->gitPrefix() === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
$changedFiles->since(null);
|
||||
} catch (MissingDependency|TiaGitFailed) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->phpFiles($changedFiles->outsideProjectDirty());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $uncommittedPhpChanges
|
||||
*/
|
||||
private function recordNothingForUncommittedPhpChangesOutsideProject(array $uncommittedPhpChanges): void
|
||||
{
|
||||
$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('Commit what you changed there to let a run leave a baseline behind.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $phpChanges
|
||||
* @param array<int, string> $arguments
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function runFullSuiteForPhpChangesOutsideProject(array $phpChanges, array $arguments): array
|
||||
{
|
||||
$this->renderPhpChangesOutsideProject($phpChanges);
|
||||
|
||||
if ($this->canRebuildGraph()) {
|
||||
$this->deleteState(self::KEY_GRAPH);
|
||||
$this->deleteState(self::KEY_COVERAGE_CACHE);
|
||||
|
||||
$this->freshGraphReason = 'a PHP file outside the project changed';
|
||||
|
||||
return $this->enterRecordMode($arguments);
|
||||
}
|
||||
|
||||
$this->requestWorkerResults();
|
||||
|
||||
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.');
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$this->fullSuiteFallbackRan = true;
|
||||
|
||||
$this->renderChild('Running the full suite — the project may load that code, and the dependency graph only reaches files under the project root.');
|
||||
$this->renderChild('Install / enable pcov or xdebug (mode: coverage) so edges can be safely refreshed after changes outside the project root.');
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $files
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function phpFiles(array $files): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
$files,
|
||||
static fn (string $file): bool => str_ends_with($file, '.php'),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $phpChanges
|
||||
*/
|
||||
private function renderPhpChangesOutsideProject(array $phpChanges): void
|
||||
{
|
||||
$count = count($phpChanges);
|
||||
|
||||
$this->renderBadge('WARN', sprintf(
|
||||
'Detected %d changed PHP file%s outside this project.',
|
||||
$count,
|
||||
$count === 1 ? '' : 's',
|
||||
));
|
||||
|
||||
foreach (array_slice($phpChanges, 0, $this->output->isVerbose() ? $count : 5) as $file) {
|
||||
$this->output->writeln(sprintf(' <fg=gray>%s</>', $file));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $outsideProject Repository-relative paths.
|
||||
*/
|
||||
private function reportChangesOutsideProject(array $outsideProject): void
|
||||
{
|
||||
if ($outsideProject === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$count = count($outsideProject);
|
||||
|
||||
$this->renderChild(sprintf(
|
||||
'%d changed file%s outside this project %s ignored — TIA only tracks files under the project root.',
|
||||
$count,
|
||||
$count === 1 ? '' : 's',
|
||||
$count === 1 ? 'was' : 'were',
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1284,9 +1636,9 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
*/
|
||||
private function persistAffectedSet(array $affected): bool
|
||||
{
|
||||
$json = json_encode(array_values($affected), JSON_UNESCAPED_SLASHES);
|
||||
|
||||
if ($json === false) {
|
||||
try {
|
||||
$json = ByteSafeJson::encode(array_values($affected));
|
||||
} catch (JsonException) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1410,13 +1762,13 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
*/
|
||||
private function flushWorkerPartial(array $perTestFiles, array $perTestTables, array $perTestInertiaComponents): void
|
||||
{
|
||||
$json = json_encode([
|
||||
'files' => $perTestFiles,
|
||||
'tables' => $perTestTables,
|
||||
'inertia' => $perTestInertiaComponents,
|
||||
], JSON_UNESCAPED_SLASHES);
|
||||
|
||||
if ($json === false) {
|
||||
try {
|
||||
$json = ByteSafeJson::encode([
|
||||
'files' => $perTestFiles,
|
||||
'tables' => $perTestTables,
|
||||
'inertia' => $perTestInertiaComponents,
|
||||
]);
|
||||
} catch (JsonException) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1490,15 +1842,15 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$results[$testId] = $this->replayedAsRecorded($testId, $result);
|
||||
}
|
||||
|
||||
$json = json_encode([
|
||||
'results' => $results,
|
||||
'replayed' => $this->replayedCount,
|
||||
'affected' => $this->affectedCount,
|
||||
'executed' => $this->executedCount,
|
||||
'truncated' => $this->stoppedEarly() || $collector->hasUnfinishedTest(),
|
||||
], JSON_UNESCAPED_SLASHES);
|
||||
|
||||
if ($json === false) {
|
||||
try {
|
||||
$json = ByteSafeJson::encode([
|
||||
'results' => $results,
|
||||
'replayed' => $this->replayedCount,
|
||||
'affected' => $this->affectedCount,
|
||||
'executed' => $this->executedCount,
|
||||
'truncated' => $this->stoppedEarly() || $collector->hasUnfinishedTest(),
|
||||
]);
|
||||
} catch (JsonException) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1526,7 +1878,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
continue;
|
||||
}
|
||||
|
||||
$decoded = json_decode($raw, true);
|
||||
$decoded = ByteSafeJson::decode($raw);
|
||||
|
||||
if (! is_array($decoded)) {
|
||||
continue;
|
||||
@@ -1626,7 +1978,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']),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1641,7 +1993,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = json_decode($raw, true);
|
||||
$data = ByteSafeJson::decode($raw);
|
||||
|
||||
if (! is_array($data)) {
|
||||
return null;
|
||||
@@ -1734,12 +2086,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);
|
||||
}
|
||||
@@ -1831,7 +2191,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;
|
||||
@@ -1863,9 +2227,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);
|
||||
@@ -2026,8 +2399,6 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return;
|
||||
}
|
||||
|
||||
$this->branchResolved = true;
|
||||
|
||||
$changedFiles = new ChangedFiles($projectRoot);
|
||||
|
||||
$resolved = $this->resolveFallbackBranch($changedFiles);
|
||||
@@ -2035,11 +2406,13 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$this->fallbackBranchResolved = $resolved !== null;
|
||||
$this->fallbackBranch = $resolved ?? self::DEFAULT_BRANCH;
|
||||
|
||||
Parallel::setGlobal(self::FALLBACK_BRANCH_GLOBAL, $this->fallbackBranch);
|
||||
Parallel::setGlobal(self::FALLBACK_BRANCH_GLOBAL, ByteSafeJson::encode($this->fallbackBranch));
|
||||
|
||||
$this->branch = $changedFiles->currentBranch()
|
||||
?? CiBranch::detectCurrent()
|
||||
?? $this->workspaceBranch($projectRoot);
|
||||
|
||||
$this->branchResolved = true;
|
||||
}
|
||||
|
||||
private function workspaceBranch(string $projectRoot): string
|
||||
@@ -2053,9 +2426,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
private function resolveFallbackBranch(ChangedFiles $changedFiles): ?string
|
||||
{
|
||||
$inherited = Parallel::getGlobal(self::FALLBACK_BRANCH_GLOBAL);
|
||||
$inheritedBranch = is_string($inherited) ? ByteSafeJson::decode($inherited) : null;
|
||||
|
||||
if (is_string($inherited) && $inherited !== '') {
|
||||
return $inherited;
|
||||
if (is_string($inheritedBranch) && $inheritedBranch !== '') {
|
||||
return $inheritedBranch;
|
||||
}
|
||||
|
||||
return $this->watchPatterns->defaultBranch()
|
||||
@@ -2244,8 +2618,13 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
'package_json' => 'package.json',
|
||||
'package_lock' => 'Node lockfile',
|
||||
'js_config' => 'JS/TS config',
|
||||
'phpunit_bootstrap' => '--bootstrap',
|
||||
'phpunit_include_path' => '--include-path',
|
||||
'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 = [];
|
||||
@@ -2260,11 +2639,6 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return implode(', ', array_keys($seen));
|
||||
}
|
||||
|
||||
private function gitSubdirectoryPrefix(string $projectRoot): ?string
|
||||
{
|
||||
return new Git($projectRoot)->subdirectoryPrefix();
|
||||
}
|
||||
|
||||
private function composerLockDelta(string $projectRoot, string $sha): string
|
||||
{
|
||||
$current = @file_get_contents($projectRoot.'/composer.lock');
|
||||
@@ -2272,7 +2646,13 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return '';
|
||||
}
|
||||
|
||||
$baseline = new Git($projectRoot)->show($sha, 'composer.lock');
|
||||
$git = new Git($projectRoot);
|
||||
|
||||
try {
|
||||
$baseline = $git->show($sha, $git->pathPrefix().'composer.lock');
|
||||
} catch (GitTimedOut) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($baseline === null) {
|
||||
return '';
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Pest\Plugins\Tia\Baselines;
|
||||
|
||||
use Pest\Plugins\Tia\WatchPatterns;
|
||||
use Pest\Support\Git;
|
||||
use Symfony\Component\Process\ExecutableFinder;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
@@ -73,23 +74,7 @@ abstract readonly class BaseRemote // @pest-arch-ignore-line
|
||||
|
||||
protected function readOriginUrl(string $projectRoot): ?string // @pest-arch-ignore-line
|
||||
{
|
||||
$gitConfig = $projectRoot.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config';
|
||||
|
||||
if (! is_file($gitConfig)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$content = @file_get_contents($gitConfig);
|
||||
|
||||
if ($content === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match('/\[remote "origin"\][^\[]*?url\s*=\s*(\S+)/s', $content, $match) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $match[1];
|
||||
return new Git($projectRoot)->originUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -120,13 +105,9 @@ abstract readonly class BaseRemote // @pest-arch-ignore-line
|
||||
return $configured;
|
||||
}
|
||||
|
||||
$process = new Process(['git', 'symbolic-ref', 'refs/remotes/origin/HEAD']);
|
||||
$process->setTimeout(5.0);
|
||||
$process->run();
|
||||
|
||||
if ($process->isSuccessful()) {
|
||||
$ref = trim($process->getOutput());
|
||||
$ref = new Git()->output(['symbolic-ref', 'refs/remotes/origin/HEAD']);
|
||||
|
||||
if ($ref !== null) {
|
||||
$branch = str_replace('refs/remotes/origin/', '', $ref);
|
||||
|
||||
if ($branch !== '') {
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use JsonException;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class ByteSafeJson
|
||||
{
|
||||
private const string ESCAPE_PREFIX = "\0base64:";
|
||||
|
||||
private const string ENCODED_ESCAPE_PREFIX = '\u0000base64:';
|
||||
|
||||
/**
|
||||
* @throws JsonException
|
||||
*/
|
||||
public static function encode(mixed $value): string
|
||||
{
|
||||
$plain = json_encode($value, JSON_UNESCAPED_SLASHES);
|
||||
|
||||
if ($plain !== false && ! self::holdsEscapes($plain)) {
|
||||
return $plain;
|
||||
}
|
||||
|
||||
return json_encode(self::escape($value), JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
public static function decode(string $json): mixed
|
||||
{
|
||||
return self::restore(json_decode($json, true), $json);
|
||||
}
|
||||
|
||||
public static function restore(mixed $decoded, string $json): mixed
|
||||
{
|
||||
return self::holdsEscapes($json) ? self::unescape($decoded) : $decoded;
|
||||
}
|
||||
|
||||
private static function holdsEscapes(string $json): bool
|
||||
{
|
||||
return str_contains($json, self::ENCODED_ESCAPE_PREFIX);
|
||||
}
|
||||
|
||||
private static function escape(mixed $value): mixed
|
||||
{
|
||||
if (is_string($value)) {
|
||||
return self::escapeString($value);
|
||||
}
|
||||
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$escaped = [];
|
||||
|
||||
foreach ($value as $key => $item) {
|
||||
$escaped[is_string($key) ? self::escapeString($key) : $key] = self::escape($item);
|
||||
}
|
||||
|
||||
return $escaped;
|
||||
}
|
||||
|
||||
private static function unescape(mixed $value): mixed
|
||||
{
|
||||
if (is_string($value)) {
|
||||
return self::unescapeString($value);
|
||||
}
|
||||
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$unescaped = [];
|
||||
|
||||
foreach ($value as $key => $item) {
|
||||
$unescaped[is_string($key) ? self::unescapeString($key) : $key] = self::unescape($item);
|
||||
}
|
||||
|
||||
return $unescaped;
|
||||
}
|
||||
|
||||
private static function escapeString(string $value): string
|
||||
{
|
||||
if (preg_match('//u', $value) === 1 && ! str_starts_with($value, self::ESCAPE_PREFIX)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return self::ESCAPE_PREFIX.base64_encode($value);
|
||||
}
|
||||
|
||||
private static function unescapeString(string $value): string
|
||||
{
|
||||
if (! str_starts_with($value, self::ESCAPE_PREFIX)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$raw = base64_decode(substr($value, strlen(self::ESCAPE_PREFIX)), true);
|
||||
|
||||
return $raw === false ? $value : $raw;
|
||||
}
|
||||
}
|
||||
@@ -6,21 +6,90 @@ 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;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final readonly class ChangedFiles
|
||||
final class ChangedFiles
|
||||
{
|
||||
private Git $git;
|
||||
private readonly Git $git;
|
||||
|
||||
public function __construct(private string $projectRoot)
|
||||
private ?string $gitPrefix = null;
|
||||
|
||||
/**
|
||||
* @var array<string, true>
|
||||
*/
|
||||
private array $outsideProject = [];
|
||||
|
||||
/**
|
||||
* @var array<string, true>
|
||||
*/
|
||||
private array $outsideProjectDirty = [];
|
||||
|
||||
public function __construct(private readonly string $projectRoot)
|
||||
{
|
||||
$this->git = new Git($projectRoot);
|
||||
}
|
||||
|
||||
public function gitPrefix(): string
|
||||
{
|
||||
return $this->gitPrefix ??= $this->git->pathPrefix();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $files repository-relative paths, as printed by git.
|
||||
* @return array<int, string> project-relative paths; paths outside the project are dropped.
|
||||
*/
|
||||
private function toProjectRelative(array $files, bool $fromWorkingTree = false): array
|
||||
{
|
||||
$prefix = $this->gitPrefix();
|
||||
|
||||
if ($prefix === '') {
|
||||
return $files;
|
||||
}
|
||||
|
||||
$projectFiles = [];
|
||||
|
||||
foreach ($files as $file) {
|
||||
if (str_starts_with($file, $prefix)) {
|
||||
$projectFiles[] = substr($file, strlen($prefix));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($file === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->outsideProject[$file] = true;
|
||||
|
||||
if ($fromWorkingTree) {
|
||||
$this->outsideProjectDirty[$file] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $projectFiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function outsideProjectDirty(): array
|
||||
{
|
||||
return Arr::stringKeys($this->outsideProjectDirty);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function outsideProject(): array
|
||||
{
|
||||
return Arr::stringKeys($this->outsideProject);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $files project-relative paths.
|
||||
* @param array<string, string> $lastRunTree path → content hash from last run.
|
||||
@@ -34,13 +103,13 @@ final readonly 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);
|
||||
|
||||
@@ -52,6 +121,100 @@ final readonly 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;
|
||||
@@ -60,11 +223,22 @@ final readonly 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
|
||||
@@ -82,7 +256,7 @@ final readonly class ChangedFiles
|
||||
continue;
|
||||
}
|
||||
|
||||
$hash = ContentHash::of($absolute);
|
||||
$hash = $this->hashOf($file, $absolute);
|
||||
|
||||
if ($hash !== false) {
|
||||
$out[$file] = $hash;
|
||||
@@ -97,6 +271,9 @@ final readonly class ChangedFiles
|
||||
*/
|
||||
public function since(?string $sha): ?array
|
||||
{
|
||||
$this->outsideProject = [];
|
||||
$this->outsideProjectDirty = [];
|
||||
|
||||
$files = [];
|
||||
|
||||
if ($sha !== null && $sha !== '') {
|
||||
@@ -118,7 +295,9 @@ final readonly class ChangedFiles
|
||||
$unique[$file] = true;
|
||||
}
|
||||
|
||||
$candidates = array_keys($this->filterIgnored($unique));
|
||||
$candidates = Arr::stringKeys($this->filterIgnored($unique));
|
||||
|
||||
$this->filterIgnoredOutsideProject();
|
||||
|
||||
if ($sha !== null && $sha !== '') {
|
||||
return $this->filterBehaviourallyUnchanged($candidates, $sha);
|
||||
@@ -162,7 +341,25 @@ final readonly class ChangedFiles
|
||||
|
||||
private function contentAtSha(string $sha, string $path): ?string
|
||||
{
|
||||
return $this->git->show($sha, $path);
|
||||
return $this->git->show($sha, $this->gitPrefix().$path);
|
||||
}
|
||||
|
||||
private function filterIgnoredOutsideProject(): void
|
||||
{
|
||||
if ($this->outsideProject === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$repositoryRoot = $this->git->repositoryRoot();
|
||||
|
||||
if ($repositoryRoot === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$git = new Git($repositoryRoot);
|
||||
|
||||
$this->outsideProject = $this->filterIgnoredWith($git, $this->outsideProject);
|
||||
$this->outsideProjectDirty = array_intersect_key($this->outsideProjectDirty, $this->outsideProject);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -170,30 +367,28 @@ final readonly class ChangedFiles
|
||||
* @return array<string, true>
|
||||
*/
|
||||
private function filterIgnored(array $candidates): array
|
||||
{
|
||||
return $this->filterIgnoredWith($this->git, $candidates);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, true> $candidates
|
||||
* @return array<string, true>
|
||||
*/
|
||||
private function filterIgnoredWith(Git $git, array $candidates): array
|
||||
{
|
||||
if ($candidates === []) {
|
||||
return $candidates;
|
||||
}
|
||||
|
||||
$result = $this->git->result(
|
||||
['check-ignore', '--no-index', '-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;
|
||||
@@ -274,7 +469,7 @@ final readonly class ChangedFiles
|
||||
}
|
||||
}
|
||||
|
||||
return array_keys($names);
|
||||
return Arr::stringKeys($names);
|
||||
}
|
||||
|
||||
public function hasRemote(): bool
|
||||
@@ -323,13 +518,13 @@ final readonly class ChangedFiles
|
||||
*/
|
||||
private function diffSinceSha(string $sha): array
|
||||
{
|
||||
$result = $this->scan()->result(['diff', '--name-only', '--no-renames', $sha.'..HEAD']);
|
||||
$result = $this->scan()->result(['diff', '--name-only', '--no-renames', '--no-relative', '-z', $sha.'..HEAD']);
|
||||
|
||||
if ($result['exitCode'] !== 0) {
|
||||
throw $this->gitFailure($result);
|
||||
}
|
||||
|
||||
return $this->splitLines($result['output']);
|
||||
return $this->toProjectRelative($this->splitRecords($result['output']));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -377,7 +572,7 @@ final readonly class ChangedFiles
|
||||
$files[] = $path;
|
||||
}
|
||||
|
||||
return $files;
|
||||
return $this->toProjectRelative($files, fromWorkingTree: true);
|
||||
}
|
||||
|
||||
public function currentSha(): ?string
|
||||
@@ -407,6 +602,21 @@ final readonly class ChangedFiles
|
||||
return new TiaGitFailed($error !== '' ? $error : sprintf('Git exited with code %d.', $result['exitCode']));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function splitRecords(string $output): array
|
||||
{
|
||||
if ($output === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_filter(
|
||||
explode("\x00", rtrim($output, "\x00")),
|
||||
static fn (string $record): bool => $record !== '',
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
|
||||
@@ -115,4 +115,17 @@ final class Configuration
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string>|null $patterns Project-relative globs to exclude, or null to disable read capture. Use watch() for excluded files that an existing watch pattern does not cover.
|
||||
* @return $this
|
||||
*/
|
||||
public function withoutReadCapture(?array $patterns = null): self
|
||||
{
|
||||
/** @var WatchPatterns $watchPatterns */
|
||||
$watchPatterns = Container::getInstance()->get(WatchPatterns::class);
|
||||
$watchPatterns->excludeReads($patterns);
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,15 +18,22 @@ 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'];
|
||||
|
||||
/**
|
||||
* @param list<string>|null $includePaths
|
||||
*/
|
||||
private function __construct(
|
||||
private ?string $path,
|
||||
private bool $suppressed,
|
||||
private ?string $bootstrap = null,
|
||||
private ?array $includePaths = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
public static function fromArguments(array $arguments): self
|
||||
public static function fromArguments(array $arguments, ?string $generatedPath = null): self
|
||||
{
|
||||
try {
|
||||
$configuration = new Builder(EventFacade::emitter())->fromParameters(self::configurationParameters($arguments));
|
||||
@@ -34,14 +41,23 @@ final readonly class ConfigurationFile
|
||||
return self::projectDefault();
|
||||
}
|
||||
|
||||
$bootstrap = $configuration->hasBootstrap() ? self::resolved($configuration->bootstrap()) : null;
|
||||
$includePaths = $configuration->hasIncludePath()
|
||||
? array_map(self::resolved(...), explode(PATH_SEPARATOR, $configuration->includePath()))
|
||||
: null;
|
||||
|
||||
if (! $configuration->hasConfigurationFile() && ! $configuration->useDefaultConfiguration()) {
|
||||
return new self(null, true);
|
||||
return new self(null, true, $bootstrap, $includePaths);
|
||||
}
|
||||
|
||||
$file = new XmlConfigurationFileFinder()->find($configuration);
|
||||
$path = $file === false ? false : realpath($file);
|
||||
|
||||
return new self($path === false ? null : $path, false);
|
||||
if ($path !== false && $generatedPath !== null && $path === realpath($generatedPath)) {
|
||||
return new self(null, false, $bootstrap, $includePaths);
|
||||
}
|
||||
|
||||
return new self($path === false ? null : $path, false, $bootstrap, $includePaths);
|
||||
}
|
||||
|
||||
public static function at(string $path): self
|
||||
@@ -54,6 +70,25 @@ final readonly class ConfigurationFile
|
||||
return new self(null, false);
|
||||
}
|
||||
|
||||
public function bootstrapFingerprint(string $projectRoot): ?string
|
||||
{
|
||||
return $this->bootstrap === null ? null : $this->relativeTo($projectRoot, $this->bootstrap);
|
||||
}
|
||||
|
||||
public function includePathFingerprint(string $projectRoot): ?string
|
||||
{
|
||||
if ($this->includePaths === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$paths = array_map(
|
||||
fn (string $path): string => $this->relativeTo($projectRoot, $path),
|
||||
$this->includePaths,
|
||||
);
|
||||
|
||||
return implode("\0", $paths);
|
||||
}
|
||||
|
||||
public function fingerprint(string $projectRoot): ?string
|
||||
{
|
||||
if ($this->suppressed) {
|
||||
@@ -84,10 +119,14 @@ final readonly class ConfigurationFile
|
||||
|
||||
private function relativeTo(string $projectRoot, string $path): string
|
||||
{
|
||||
$root = rtrim(str_replace('\\', '/', realpath($projectRoot) ?: $projectRoot), '/').'/';
|
||||
$file = str_replace('\\', '/', realpath($path) ?: $path);
|
||||
$root = rtrim($this->withForwardSlashes(realpath($projectRoot) ?: $projectRoot), '/').'/';
|
||||
$resolvedPath = $this->withForwardSlashes(self::resolved($path));
|
||||
|
||||
return str_starts_with($file, $root) ? substr($file, strlen($root)) : $file;
|
||||
if ($resolvedPath.'/' === $root) {
|
||||
return '.';
|
||||
}
|
||||
|
||||
return str_starts_with($resolvedPath, $root) ? substr($resolvedPath, strlen($root)) : $resolvedPath;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,20 +141,48 @@ final readonly class ConfigurationFile
|
||||
foreach ($arguments as $index => $argument) {
|
||||
if ($argument === '--no-configuration') {
|
||||
$parameters[] = $argument;
|
||||
} elseif ($argument === '--configuration' || $argument === '-c') {
|
||||
if (isset($arguments[$index + 1])) {
|
||||
$parameters[] = '--configuration';
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$option = self::withLongConfigurationOption($argument);
|
||||
|
||||
foreach (self::VALUE_OPTIONS as $name) {
|
||||
if ($option === $name && isset($arguments[$index + 1])) {
|
||||
$parameters[] = $name;
|
||||
$parameters[] = $arguments[$index + 1];
|
||||
} elseif (str_starts_with($option, $name.'=')) {
|
||||
$parameters[] = $name;
|
||||
$parameters[] = substr($option, strlen($name.'='));
|
||||
}
|
||||
} elseif (str_starts_with($argument, '--configuration=')) {
|
||||
$parameters[] = '--configuration';
|
||||
$parameters[] = substr($argument, strlen('--configuration='));
|
||||
} elseif (str_starts_with($argument, '-c') && ! str_starts_with($argument, '--')) {
|
||||
$parameters[] = '--configuration';
|
||||
$parameters[] = substr($argument, 2);
|
||||
}
|
||||
}
|
||||
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
private static function withLongConfigurationOption(string $argument): string
|
||||
{
|
||||
if ($argument === '-c') {
|
||||
return '--configuration';
|
||||
}
|
||||
|
||||
if (str_starts_with($argument, '-c')) {
|
||||
return '--configuration='.substr($argument, 2);
|
||||
}
|
||||
|
||||
return $argument;
|
||||
}
|
||||
|
||||
private function withForwardSlashes(string $path): string
|
||||
{
|
||||
return DIRECTORY_SEPARATOR === '\\' ? str_replace('\\', '/', $path) : $path;
|
||||
}
|
||||
|
||||
private static function resolved(string $path): string
|
||||
{
|
||||
$real = $path === '' ? false : realpath($path);
|
||||
|
||||
return $real === false ? $path : $real;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,9 +4,10 @@ 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;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
@@ -23,22 +24,46 @@ 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();
|
||||
|
||||
$structural = [
|
||||
'schema' => self::SCHEMA_VERSION,
|
||||
'composer_lock' => self::composerLockHash($projectRoot),
|
||||
'phpunit_configuration' => $configuration->fingerprint($projectRoot),
|
||||
'vite_config' => self::viteConfigHash($projectRoot),
|
||||
'package_lock' => self::packageLockHash($projectRoot),
|
||||
'js_config' => self::jsConfigHash($projectRoot),
|
||||
...self::commandLineOverrides($projectRoot, $configuration),
|
||||
];
|
||||
|
||||
$prefix = self::projectPrefix($projectRoot);
|
||||
|
||||
if ($prefix !== '') {
|
||||
$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' => [
|
||||
'schema' => self::SCHEMA_VERSION,
|
||||
'composer_lock' => self::composerLockHash($projectRoot),
|
||||
'phpunit_configuration' => ($configuration ?? ConfigurationFile::projectDefault())->fingerprint($projectRoot),
|
||||
'vite_config' => self::viteConfigHash($projectRoot),
|
||||
'package_lock' => self::packageLockHash($projectRoot),
|
||||
'js_config' => self::jsConfigHash($projectRoot),
|
||||
],
|
||||
'structural' => $structural,
|
||||
'environmental' => [
|
||||
'php_minor' => PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION,
|
||||
|
||||
@@ -46,6 +71,17 @@ final readonly class Fingerprint
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private static function commandLineOverrides(string $projectRoot, ConfigurationFile $configuration): array
|
||||
{
|
||||
return array_filter([
|
||||
'phpunit_bootstrap' => $configuration->bootstrapFingerprint($projectRoot),
|
||||
'phpunit_include_path' => $configuration->includePathFingerprint($projectRoot),
|
||||
], fn (?string $value): bool => $value !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $a
|
||||
* @param array<string, mixed> $b
|
||||
@@ -275,20 +311,31 @@ final readonly class Fingerprint
|
||||
return $cache[$key];
|
||||
}
|
||||
|
||||
if (! is_dir($projectRoot.'/.git') && ! is_file($projectRoot.'/.git')) {
|
||||
if (! self::isGitRepository($projectRoot)) {
|
||||
return $cache[$key] = true;
|
||||
}
|
||||
|
||||
$process = new Process(['git', 'check-ignore', '-q', '--', $relativePath], $projectRoot);
|
||||
$process->setTimeout(5.0);
|
||||
|
||||
try {
|
||||
$process->run();
|
||||
} catch (ProcessException) {
|
||||
$result = new Git($projectRoot)->checkIgnore([$relativePath]);
|
||||
} catch (ProcessException|GitTimedOut) {
|
||||
return $cache[$key] = true;
|
||||
}
|
||||
|
||||
return $cache[$key] = $process->getExitCode() !== 0;
|
||||
return $cache[$key] = $result['exitCode'] !== 0;
|
||||
}
|
||||
|
||||
private static function projectPrefix(string $projectRoot): string
|
||||
{
|
||||
static $cache = [];
|
||||
|
||||
return $cache[$projectRoot] ??= new Git($projectRoot)->pathPrefix();
|
||||
}
|
||||
|
||||
private static function isGitRepository(string $projectRoot): bool
|
||||
{
|
||||
static $cache = [];
|
||||
|
||||
return $cache[$projectRoot] ??= new Git($projectRoot)->isRepository();
|
||||
}
|
||||
|
||||
private static function contentHashOrNull(string $path): ?string
|
||||
|
||||
+47
-16
@@ -4,8 +4,10 @@ declare(strict_types=1);
|
||||
|
||||
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;
|
||||
@@ -20,6 +22,10 @@ final class Graph
|
||||
{
|
||||
public const string WORKSPACE_BRANCH_PREFIX = '@workspace:';
|
||||
|
||||
private const int LEGACY_SCHEMA = 1;
|
||||
|
||||
private const int SCHEMA = 2;
|
||||
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
@@ -589,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) {
|
||||
@@ -1126,7 +1132,7 @@ final class Graph
|
||||
}
|
||||
}
|
||||
|
||||
$names = array_keys($normalised);
|
||||
$names = Arr::stringKeys($normalised);
|
||||
sort($names);
|
||||
|
||||
$this->testInertiaComponents[$testRel] = $names;
|
||||
@@ -1156,7 +1162,7 @@ final class Graph
|
||||
continue;
|
||||
}
|
||||
|
||||
$keys = array_keys($names);
|
||||
$keys = Arr::stringKeys($names);
|
||||
sort($keys);
|
||||
$out[$path] = $keys;
|
||||
}
|
||||
@@ -1640,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;
|
||||
}
|
||||
@@ -1698,7 +1704,7 @@ final class Graph
|
||||
*/
|
||||
public static function branchesIn(string $json): array
|
||||
{
|
||||
$data = json_decode($json, true);
|
||||
$data = ByteSafeJson::decode($json);
|
||||
|
||||
if (! is_array($data) || ! is_array($data['baselines'] ?? null)) {
|
||||
return [];
|
||||
@@ -1706,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;
|
||||
}
|
||||
}
|
||||
@@ -1715,11 +1721,35 @@ final class Graph
|
||||
return $branches;
|
||||
}
|
||||
|
||||
public static function decode(string $json, string $projectRoot): ?self
|
||||
/**
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
private static function payload(string $json): ?array
|
||||
{
|
||||
$data = json_decode($json, true);
|
||||
|
||||
if (! is_array($data) || ($data['schema'] ?? null) !== 1) {
|
||||
if (! is_array($data)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (($data['schema'] ?? null) === self::LEGACY_SCHEMA) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
if (($data['schema'] ?? null) !== self::SCHEMA) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$restored = ByteSafeJson::restore($data, $json);
|
||||
|
||||
return is_array($restored) ? $restored : null;
|
||||
}
|
||||
|
||||
public static function decode(string $json, string $projectRoot): ?self
|
||||
{
|
||||
$data = self::payload($json);
|
||||
|
||||
if ($data === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1818,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1922,10 +1952,13 @@ final class Graph
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function encode(): ?string
|
||||
/**
|
||||
* @throws JsonException
|
||||
*/
|
||||
public function encode(): string
|
||||
{
|
||||
$payload = [
|
||||
'schema' => 1,
|
||||
'schema' => self::SCHEMA,
|
||||
'fingerprint' => $this->fingerprint,
|
||||
'files' => $this->files,
|
||||
'edges' => $this->edges,
|
||||
@@ -1935,9 +1968,7 @@ final class Graph
|
||||
'js_file_to_components' => $this->jsFileToComponents,
|
||||
];
|
||||
|
||||
$json = json_encode($payload, JSON_UNESCAPED_SLASHES);
|
||||
|
||||
return $json === false ? null : $json;
|
||||
return ByteSafeJson::encode($payload);
|
||||
}
|
||||
|
||||
private function relative(string $path): ?string
|
||||
|
||||
@@ -89,13 +89,16 @@ final class ReadCapture
|
||||
|
||||
private static function disable(): void
|
||||
{
|
||||
if (in_array(self::PROTOCOL, stream_get_wrappers(), true)) {
|
||||
stream_wrapper_unregister(self::PROTOCOL);
|
||||
}
|
||||
|
||||
if (self::$previousWrapper === null) {
|
||||
stream_wrapper_restore(self::PROTOCOL);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
stream_wrapper_unregister(self::PROTOCOL);
|
||||
stream_wrapper_register(self::PROTOCOL, self::$previousWrapper);
|
||||
}
|
||||
|
||||
@@ -124,16 +127,22 @@ final class ReadCapture
|
||||
|
||||
public function dir_closedir(): bool
|
||||
{
|
||||
closedir($this->resource());
|
||||
$this->forward('dir_closedir', function (mixed $resource): bool {
|
||||
closedir($resource);
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function dir_opendir(string $path): bool
|
||||
public function dir_opendir(string $path, int $options): bool
|
||||
{
|
||||
$handle = $this->withOriginalWrapper(fn () => opendir($path, $this->context));
|
||||
$handle = $this->withOriginalWrapper(fn (): mixed => self::$previousWrapper === null
|
||||
? opendir($path, $this->context)
|
||||
: $this->openDirectoryThroughPreviousWrapper(self::$previousWrapper, $path, $options));
|
||||
|
||||
if (! is_resource($handle)) {
|
||||
if ($handle === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -144,14 +153,18 @@ final class ReadCapture
|
||||
|
||||
public function dir_readdir(): string|false
|
||||
{
|
||||
return readdir($this->resource());
|
||||
$entry = $this->forward('dir_readdir', fn (mixed $resource): string|false => readdir($resource));
|
||||
|
||||
return is_string($entry) ? $entry : false;
|
||||
}
|
||||
|
||||
public function dir_rewinddir(): bool
|
||||
{
|
||||
rewinddir($this->resource());
|
||||
return $this->forward('dir_rewinddir', function (mixed $resource): bool {
|
||||
rewinddir($resource);
|
||||
|
||||
return true;
|
||||
return true;
|
||||
}) === true;
|
||||
}
|
||||
|
||||
public function mkdir(string $path, int $mode, int $options): bool
|
||||
@@ -286,21 +299,13 @@ final class ReadCapture
|
||||
public function url_stat(string $path, int $flags): array|false
|
||||
{
|
||||
return $this->withOriginalWrapper(function () use ($path, $flags): array|false {
|
||||
$isQuiet = ($flags & STREAM_URL_STAT_QUIET) !== 0;
|
||||
set_error_handler(static fn (): bool => true);
|
||||
|
||||
if (($flags & STREAM_URL_STAT_LINK) !== 0) {
|
||||
if ($isQuiet && ! is_link($path) && ! file_exists($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return @lstat($path);
|
||||
try {
|
||||
return ($flags & STREAM_URL_STAT_LINK) !== 0 ? lstat($path) : stat($path);
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
|
||||
if ($isQuiet && ! file_exists($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return @stat($path);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -309,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);
|
||||
}
|
||||
@@ -325,7 +330,25 @@ final class ReadCapture
|
||||
$wrapper->context = $this->context;
|
||||
}
|
||||
|
||||
if (! method_exists($wrapper, 'stream_open') || $wrapper->stream_open($path, $mode, $options, $openedPath) !== true) {
|
||||
if (! is_callable([$wrapper, 'stream_open']) || $wrapper->stream_open($path, $mode, $options, $openedPath) !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param class-string $wrapperClass
|
||||
*/
|
||||
private function openDirectoryThroughPreviousWrapper(string $wrapperClass, string $path, int $options): object|false
|
||||
{
|
||||
$wrapper = new $wrapperClass;
|
||||
|
||||
if (property_exists($wrapper, 'context')) {
|
||||
$wrapper->context = $this->context;
|
||||
}
|
||||
|
||||
if (! is_callable([$wrapper, 'dir_opendir']) || $wrapper->dir_opendir($path, $options) !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -341,16 +364,6 @@ final class ReadCapture
|
||||
return str_contains($mode, 'r') || str_contains($mode, '+');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return resource
|
||||
*/
|
||||
private function resource(): mixed
|
||||
{
|
||||
assert(is_resource($this->handle));
|
||||
|
||||
return $this->handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Closure(resource): mixed $native
|
||||
*/
|
||||
@@ -360,7 +373,7 @@ final class ReadCapture
|
||||
return $native($this->handle);
|
||||
}
|
||||
|
||||
if (! method_exists($this->handle, $method)) {
|
||||
if (! is_callable([$this->handle, $method])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use Pest\Support\Arr;
|
||||
use Pest\Support\Container;
|
||||
use Pest\TestSuite;
|
||||
use ReflectionClass;
|
||||
|
||||
@@ -103,7 +105,9 @@ final class Recorder
|
||||
|
||||
$this->currentTestFile = $file;
|
||||
|
||||
ReadCapture::start($this);
|
||||
if ($this->watchPatterns()->isReadCaptureEnabled()) {
|
||||
ReadCapture::start($this);
|
||||
}
|
||||
|
||||
if ($this->classUsesDatabase($className)) {
|
||||
$this->perTestUsesDatabase[$file] = true;
|
||||
@@ -201,9 +205,34 @@ final class Recorder
|
||||
return;
|
||||
}
|
||||
|
||||
$relative = $this->projectRelative($real);
|
||||
|
||||
if ($relative !== null && $this->watchPatterns()->excludesRead($relative)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->linkSource($real);
|
||||
}
|
||||
|
||||
private function projectRelative(string $realPath): ?string
|
||||
{
|
||||
$root = rtrim(TestSuite::getInstance()->rootPath, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
|
||||
|
||||
if (! str_starts_with($realPath, $root)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return str_replace(DIRECTORY_SEPARATOR, '/', substr($realPath, strlen($root)));
|
||||
}
|
||||
|
||||
private function watchPatterns(): WatchPatterns
|
||||
{
|
||||
$watchPatterns = Container::getInstance()->get(WatchPatterns::class);
|
||||
assert($watchPatterns instanceof WatchPatterns);
|
||||
|
||||
return $watchPatterns;
|
||||
}
|
||||
|
||||
private function classUsesDatabase(string $className): bool
|
||||
{
|
||||
if (array_key_exists($className, $this->classUsesDatabaseCache)) {
|
||||
@@ -301,7 +330,7 @@ final class Recorder
|
||||
$out = [];
|
||||
|
||||
foreach ($this->perTestInertiaComponents as $testFile => $components) {
|
||||
$names = array_keys($components);
|
||||
$names = Arr::stringKeys($components);
|
||||
sort($names);
|
||||
$out[$testFile] = $names;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,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.
|
||||
|
||||
+13
-21
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use Pest\Support\Git;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@@ -92,9 +94,6 @@ final class Storage
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `git@github.com:foo/bar.git`, `ssh://git@github.com/foo/bar`
|
||||
*/
|
||||
private static function projectKey(string $projectRoot): string
|
||||
{
|
||||
$origin = self::originIdentity($projectRoot);
|
||||
@@ -102,6 +101,12 @@ final class Storage
|
||||
$realpath = @realpath($projectRoot);
|
||||
$input = $origin ?? ($realpath === false ? $projectRoot : $realpath);
|
||||
|
||||
$prefix = $origin === null ? '' : self::gitPrefix($projectRoot);
|
||||
|
||||
if ($prefix !== '') {
|
||||
$input .= '/'.$prefix;
|
||||
}
|
||||
|
||||
$hash = substr(hash('sha256', $input), 0, 16);
|
||||
$slug = self::slug(basename($projectRoot));
|
||||
|
||||
@@ -116,12 +121,10 @@ final class Storage
|
||||
return null;
|
||||
}
|
||||
|
||||
// git@host:org/repo(.git)
|
||||
if (preg_match('#^[\w.-]+@([\w.-]+):([\w./-]+?)(?:\.git)?/?$#', $url, $m) === 1) {
|
||||
return strtolower($m[1].'/'.$m[2]);
|
||||
}
|
||||
|
||||
// scheme://[user@]host[:port]/org/repo(.git) — https, ssh, git, file
|
||||
if (preg_match('#^[a-z]+://(?:[^@/]+@)?([^/:]+)(?::\d+)?/([\w./-]+?)(?:\.git)?/?$#i', $url, $m) === 1) {
|
||||
return strtolower($m[1].'/'.$m[2]);
|
||||
}
|
||||
@@ -131,23 +134,12 @@ final class Storage
|
||||
|
||||
private static function rawOriginUrl(string $projectRoot): ?string
|
||||
{
|
||||
$config = $projectRoot.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config';
|
||||
return new Git($projectRoot)->originUrl();
|
||||
}
|
||||
|
||||
if (! is_file($config)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$raw = @file_get_contents($config);
|
||||
|
||||
if ($raw === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match('/\[remote "origin"\][^\[]*?url\s*=\s*(\S+)/s', $raw, $match) === 1) {
|
||||
return trim($match[1]);
|
||||
}
|
||||
|
||||
return null;
|
||||
private static function gitPrefix(string $projectRoot): string
|
||||
{
|
||||
return new Git($projectRoot)->pathPrefix();
|
||||
}
|
||||
|
||||
private static function slug(string $name): string
|
||||
|
||||
@@ -4,10 +4,10 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia\WatchDefaults;
|
||||
|
||||
use Composer\InstalledVersions;
|
||||
use Pest\Browser\Support\BrowserTestIdentifier;
|
||||
use Pest\Factories\TestCaseFactory;
|
||||
use Pest\Plugins\Tia\Contracts\WatchDefault;
|
||||
use Pest\Support\InstalledPackages;
|
||||
use Pest\TestSuite;
|
||||
|
||||
/**
|
||||
@@ -17,8 +17,7 @@ final readonly class Browser implements WatchDefault
|
||||
{
|
||||
public function applicable(): bool
|
||||
{
|
||||
return class_exists(InstalledVersions::class)
|
||||
&& InstalledVersions::isInstalled('pestphp/pest-plugin-browser');
|
||||
return InstalledPackages::has('pestphp/pest-plugin-browser');
|
||||
}
|
||||
|
||||
public function defaults(string $projectRoot, string $testPath): array
|
||||
|
||||
@@ -4,8 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia\WatchDefaults;
|
||||
|
||||
use Composer\InstalledVersions;
|
||||
use Pest\Plugins\Tia\Contracts\WatchDefault;
|
||||
use Pest\Support\InstalledPackages;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
@@ -14,9 +14,8 @@ final readonly class Inertia implements WatchDefault
|
||||
{
|
||||
public function applicable(): bool
|
||||
{
|
||||
return class_exists(InstalledVersions::class)
|
||||
&& (InstalledVersions::isInstalled('inertiajs/inertia-laravel')
|
||||
|| InstalledVersions::isInstalled('rompetomp/inertia-bundle'));
|
||||
return InstalledPackages::has('inertiajs/inertia-laravel')
|
||||
|| InstalledPackages::has('rompetomp/inertia-bundle');
|
||||
}
|
||||
|
||||
public function defaults(string $projectRoot, string $testPath): array
|
||||
|
||||
@@ -4,8 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia\WatchDefaults;
|
||||
|
||||
use Composer\InstalledVersions;
|
||||
use Pest\Plugins\Tia\Contracts\WatchDefault;
|
||||
use Pest\Support\InstalledPackages;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
@@ -14,8 +14,7 @@ final readonly class Laravel implements WatchDefault
|
||||
{
|
||||
public function applicable(): bool
|
||||
{
|
||||
return class_exists(InstalledVersions::class)
|
||||
&& InstalledVersions::isInstalled('laravel/framework');
|
||||
return InstalledPackages::has('laravel/framework');
|
||||
}
|
||||
|
||||
public function defaults(string $projectRoot, string $testPath): array
|
||||
|
||||
@@ -4,8 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia\WatchDefaults;
|
||||
|
||||
use Composer\InstalledVersions;
|
||||
use Pest\Plugins\Tia\Contracts\WatchDefault;
|
||||
use Pest\Support\InstalledPackages;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
@@ -14,8 +14,7 @@ final readonly class Livewire implements WatchDefault
|
||||
{
|
||||
public function applicable(): bool
|
||||
{
|
||||
return class_exists(InstalledVersions::class)
|
||||
&& InstalledVersions::isInstalled('livewire/livewire');
|
||||
return InstalledPackages::has('livewire/livewire');
|
||||
}
|
||||
|
||||
public function defaults(string $projectRoot, string $testPath): array
|
||||
|
||||
@@ -4,8 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia\WatchDefaults;
|
||||
|
||||
use Composer\InstalledVersions;
|
||||
use Pest\Plugins\Tia\Contracts\WatchDefault;
|
||||
use Pest\Support\InstalledPackages;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
@@ -14,8 +14,7 @@ final readonly class Symfony implements WatchDefault
|
||||
{
|
||||
public function applicable(): bool
|
||||
{
|
||||
return class_exists(InstalledVersions::class)
|
||||
&& InstalledVersions::isInstalled('symfony/framework-bundle');
|
||||
return InstalledPackages::has('symfony/framework-bundle');
|
||||
}
|
||||
|
||||
public function defaults(string $projectRoot, string $testPath): array
|
||||
|
||||
@@ -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;
|
||||
|
||||
/**
|
||||
@@ -43,6 +44,13 @@ final class WatchPatterns
|
||||
|
||||
private bool $defaultsEnabled = true;
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
private array $excludedReadPatterns = [];
|
||||
|
||||
private bool $readCaptureEnabled = true;
|
||||
|
||||
/**
|
||||
* @var array<string, array{include: string, excludes: array<int, string>, allowDotfiles: bool}>
|
||||
*/
|
||||
@@ -110,6 +118,39 @@ final class WatchPatterns
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string>|null $patterns
|
||||
*/
|
||||
public function excludeReads(?array $patterns = null): void
|
||||
{
|
||||
if ($patterns === null) {
|
||||
$this->readCaptureEnabled = false;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->excludedReadPatterns = array_values(array_unique([
|
||||
...$this->excludedReadPatterns,
|
||||
...$patterns,
|
||||
]));
|
||||
}
|
||||
|
||||
public function isReadCaptureEnabled(): bool
|
||||
{
|
||||
return $this->readCaptureEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $file Project-relative path.
|
||||
*/
|
||||
public function excludesRead(string $file): bool
|
||||
{
|
||||
return array_any(
|
||||
$this->excludedReadPatterns,
|
||||
fn (string $pattern): bool => $this->keyMatches($pattern, $file),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $projectRoot Absolute path.
|
||||
* @param array<int, string> $changedFiles Project-relative paths.
|
||||
@@ -133,7 +174,7 @@ final class WatchPatterns
|
||||
}
|
||||
}
|
||||
|
||||
return array_keys($matched);
|
||||
return Arr::stringKeys($matched);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -144,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
|
||||
@@ -279,6 +320,8 @@ final class WatchPatterns
|
||||
$this->defaultPatterns = [];
|
||||
$this->excludedDefaultPatterns = [];
|
||||
$this->defaultsEnabled = true;
|
||||
$this->excludedReadPatterns = [];
|
||||
$this->readCaptureEnabled = true;
|
||||
$this->parsed = [];
|
||||
$this->enabled = false;
|
||||
$this->locally = false;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+64
-6
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Support;
|
||||
|
||||
use Pest\Exceptions\GitTimedOut;
|
||||
use Symfony\Component\Process\Exception\ProcessTimedOutException;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
/**
|
||||
@@ -49,6 +51,22 @@ final readonly class Git
|
||||
return $output === '' ? null : $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
private function outputLine(array $arguments): ?string
|
||||
{
|
||||
$output = $this->raw($arguments);
|
||||
|
||||
if ($output === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$line = str_ends_with($output, "\n") ? substr($output, 0, -1) : $output;
|
||||
|
||||
return $line === '' ? null : $line;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
@@ -57,20 +75,46 @@ 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);
|
||||
$process = new Process(['git', ...$arguments], $this->directory, ['GIT_LITERAL_PATHSPECS' => '0', 'LC_ALL' => 'C', 'LANGUAGE' => '']);
|
||||
$process->setTimeout($this->timeout);
|
||||
|
||||
if ($input !== null) {
|
||||
$process->setInput($input);
|
||||
}
|
||||
|
||||
$process->run();
|
||||
try {
|
||||
$process->run();
|
||||
} catch (ProcessTimedOutException) {
|
||||
throw new GitTimedOut($arguments, $this->timeout);
|
||||
}
|
||||
|
||||
return [
|
||||
'exitCode' => $process->getExitCode() ?? 1,
|
||||
@@ -104,14 +148,28 @@ final readonly class Git
|
||||
return $this->raw(['show', $sha.':'.$path]);
|
||||
}
|
||||
|
||||
public function subdirectoryPrefix(): ?string
|
||||
public function repositoryRoot(): ?string
|
||||
{
|
||||
$prefix = $this->output(['rev-parse', '--show-prefix']);
|
||||
$root = $this->outputLine(['rev-parse', '--show-toplevel']);
|
||||
|
||||
return $root === null ? null : rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $root), '/');
|
||||
}
|
||||
|
||||
public function pathPrefix(): string
|
||||
{
|
||||
$prefix = $this->outputLine(['rev-parse', '--show-prefix']);
|
||||
|
||||
if ($prefix === null) {
|
||||
return null;
|
||||
return '';
|
||||
}
|
||||
|
||||
return rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $prefix), '/');
|
||||
$prefix = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $prefix), '/');
|
||||
|
||||
return $prefix === '' ? '' : $prefix.'/';
|
||||
}
|
||||
|
||||
public function originUrl(): ?string
|
||||
{
|
||||
return $this->output(['config', '--get', 'remote.origin.url']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Support;
|
||||
|
||||
use Composer\InstalledVersions;
|
||||
|
||||
final readonly class InstalledPackages
|
||||
{
|
||||
/**
|
||||
* @param array<int, array{root: array{install_path?: string}, versions: array<string, array{dev_requirement?: bool}>}> $installedSets
|
||||
*/
|
||||
public function __construct(private array $installedSets) {}
|
||||
|
||||
public static function fromComposer(): self
|
||||
{
|
||||
if (! class_exists(InstalledVersions::class)) {
|
||||
return new self([]);
|
||||
}
|
||||
|
||||
/** @var array<int, array{root: array{install_path?: string}, versions: array<string, array{dev_requirement?: bool}>}> $installedSets */
|
||||
$installedSets = InstalledVersions::getAllRawData();
|
||||
|
||||
return new self($installedSets);
|
||||
}
|
||||
|
||||
public static function has(string $package, bool $includeDevRequirements = true): bool
|
||||
{
|
||||
return self::fromComposer()->contains($package, $includeDevRequirements);
|
||||
}
|
||||
|
||||
public function contains(string $package, bool $includeDevRequirements = true): bool
|
||||
{
|
||||
foreach ($this->installedSets as $installedSet) {
|
||||
if ($this->isBundledInPhar($installedSet)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($installedSet['versions'][$package])) {
|
||||
return $includeDevRequirements || ($installedSet['versions'][$package]['dev_requirement'] ?? false) === false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{root: array{install_path?: string}} $installedSet
|
||||
*/
|
||||
private function isBundledInPhar(array $installedSet): bool
|
||||
{
|
||||
return str_starts_with($installedSet['root']['install_path'] ?? '', 'phar://');
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@
|
||||
EXECUTION OPTIONS:
|
||||
--parallel ........................................... Run tests in parallel
|
||||
--update-snapshots Update snapshots for tests using the "toMatchSnapshot" expectation
|
||||
--update-shards Update shards.json with test timing data for time-balanced sharding
|
||||
--update-shards Update the shards file with timing data for time-balanced sharding
|
||||
--globals-backup ................. Backup and restore $GLOBALS for each test
|
||||
--static-backup ......... Backup and restore static properties for each test
|
||||
--strict-coverage ................... Be strict about code coverage metadata
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
✓ matching describe block names → outer → middle → it should not call afterEach functions for sibling describe blocks with the same name
|
||||
✓ matching describe block names → outer → inner → it does not get executed before the test
|
||||
✓ matching describe block names → outer → inner → it should not call afterEach functions for descendent of sibling describe blocks with the same name
|
||||
✓ hierarchical test naming → block one → the same name → it does not call afterEach from sibling describe with same name
|
||||
✓ hierarchical test naming → block two → the same name → it correctly calls afterEach from own describe hierarchy
|
||||
|
||||
PASS Tests\Features\Assignee
|
||||
✓ it may be associated with an assignee [@nunomaduro, @taylorotwell]
|
||||
@@ -56,6 +58,8 @@
|
||||
✓ matching name → it should not call the before each on the describe block with the same name
|
||||
✓ called on all tests → beforeEach should be called
|
||||
✓ called on all tests → beforeEach should be called for all tests
|
||||
✓ hierarchical test naming → block one → the same name → it does not call beforeEach from sibling describe with same name
|
||||
✓ hierarchical test naming → block two → the same name → it correctly calls beforeEach from own describe hierarchy
|
||||
|
||||
PASS Tests\Features\BeforeEachProxiesToTestCallWithExpectations
|
||||
✓ runs 1
|
||||
@@ -335,6 +339,8 @@
|
||||
✓ depends on describe using with → foo with (3)
|
||||
✓ depends on describe using with → bar with (3)
|
||||
✓ with test after describe → it should run the before each
|
||||
✓ sibling describes may share the same it() description → block one → it can be created
|
||||
✓ sibling describes may share the same it() description → block two → it can be created
|
||||
|
||||
PASS Tests\Features\DescriptionLess
|
||||
✓ get 'foo'
|
||||
@@ -1015,6 +1021,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')
|
||||
@@ -1320,6 +1328,7 @@
|
||||
✓ init creates a suite when --init is not the first argument
|
||||
✓ init creates a suite when --init is passed with a value
|
||||
✓ a missing tests directory does not crash while resolving tia state
|
||||
✓ init writes the plain stubs when only a tool bundled in a PHAR installs Laravel
|
||||
|
||||
PASS Tests\Features\Issue
|
||||
✓ it may be associated with an issue #1, #2
|
||||
@@ -1820,6 +1829,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
|
||||
@@ -1854,6 +1870,15 @@
|
||||
PASS Tests\Unit\Overrides\ThrowableBuilder
|
||||
✓ collision editor can be added to the stack trace
|
||||
|
||||
PASS Tests\Unit\Plugins\Actions\CallsAddsOutput
|
||||
✓ exit code observers run after every output plugin
|
||||
✓ exit code observers receive unchanged codes when there are no output plugins with (0)
|
||||
✓ exit code observers receive unchanged codes when there are no output plugins with (1)
|
||||
✓ exit code observers receive unchanged codes when there are no output plugins with (2)
|
||||
✓ exit code observers receive unchanged codes when there are no output plugins with (42)
|
||||
✓ output plugins work without exit code observers
|
||||
✓ exit code observers are not called when an output plugin throws
|
||||
|
||||
PASS Tests\Unit\Plugins\Concerns\HandleArguments
|
||||
✓ method hasArgument with ('--long-argument', true)
|
||||
✓ method hasArgument with ('-a', true)
|
||||
@@ -1870,6 +1895,8 @@
|
||||
|
||||
PASS Tests\Unit\Plugins\Retry
|
||||
✓ it orders by defects and stop on defects if when --retry is used
|
||||
✓ it rejects retry with a parallel flag with ('--parallel')
|
||||
✓ it rejects retry with a parallel flag with ('-p')
|
||||
|
||||
PASS Tests\Unit\Plugins\Shard
|
||||
✓ getShard → it parses valid shard format with ('1/2', 1, 2)
|
||||
@@ -1921,15 +1948,102 @@
|
||||
✓ buildListTestsCommand → it strips --processes N (space-separated) when building the list-tests command
|
||||
✓ buildListTestsCommand → it strips --runner when building the list-tests command
|
||||
✓ buildListTestsCommand → it strips a space-separated --runner and its value when building the list-tests command
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--max-batch-size=N"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--max-batch-size N"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "-m N"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "-mN"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "-m=N"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--processes N"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--max-processes=N"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--passthru-php"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--tmp-dir"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--functional"
|
||||
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--no-test-tokens"
|
||||
✓ addOutput → it displays shard information after test execution
|
||||
✓ addOutput → it uses singular form for single test file
|
||||
✓ addOutput → it returns original exit code when shard is not set
|
||||
✓ timings file → it reads and writes shards.json until a plugin overrides the filename
|
||||
✓ timings file → it prefers timings supplied by a plugin over the ones collected from the test run
|
||||
✓ timings file → it records known tests without supplied timings as zero
|
||||
✓ timings file → it keeps timings supplied by a plugin even when the test suite did not pass
|
||||
✓ timings file → it strips coverage arguments when building the list-tests command
|
||||
✓ timings file → it strips the separate path of a coverage argument when building the list-tests command
|
||||
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--coverage-jsonl')
|
||||
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--coverage-filter')
|
||||
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--min')
|
||||
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--exactly')
|
||||
✓ timings file → it strips the separate value of the parallel processes option when building the list-tests command
|
||||
✓ timings file → it keeps a unit saved with no test classes, but drops one emptied by removed classes
|
||||
✓ timings file → it drops test classes that no longer exist from the stored units
|
||||
✓ units → it treats a bare timing as a unit bundling only its own test class
|
||||
✓ units → it keeps the test classes a unit bundles together in one shard
|
||||
✓ units → it owns every unit when the run is not time-balanced
|
||||
✓ units → it owns only the units allocated to the current shard
|
||||
✓ units → it owns a unit the timings file does not know in every shard, and reports the file as out of date
|
||||
✓ units → it keeps a unit that bundles no test class when writing
|
||||
✓ units → it collects every test class the given units bundle
|
||||
✓ units → it writes bundled units, and reads back both shapes
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\ByteSafeJson
|
||||
✓ it round-trips keys and values that are not valid UTF-8
|
||||
✓ it keeps valid UTF-8 as plain JSON
|
||||
✓ it does not confuse a real string with an escaped one
|
||||
✓ it leaves a malformed escape untouched
|
||||
✓ it returns null for invalid JSON
|
||||
✓ it throws with the reason when a value cannot be encoded
|
||||
✓ it carries a string that is not valid UTF-8 through a parallel global
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\ChangedFiles
|
||||
✓ it resolves the project prefix inside the repository
|
||||
✓ it keeps a space that begins the name of the project directory
|
||||
✓ it keeps the character that ends the name of the repository root with dataset "a space"
|
||||
✓ it keeps the character that ends the name of the repository root with dataset "a carriage return"
|
||||
✓ it reports working tree changes relative to the project, dropping siblings
|
||||
✓ it reports committed changes relative to the project, dropping siblings
|
||||
✓ it drops a file whose content came back to its baseline across the prefix boundary
|
||||
✓ it honours a gitignore inside the project
|
||||
✓ it leaves a project at the repository root untouched
|
||||
✓ it reports the changes it left outside the project
|
||||
✓ it reports nothing outside the project for a project at the repository root
|
||||
✓ it ties a fingerprint to the project location inside the repository
|
||||
✓ it sees a committed non-ascii path that git would otherwise quote
|
||||
✓ it sees a committed non-ascii path at the repository root too
|
||||
✓ 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
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\ConfigurationFile
|
||||
✓ it fingerprints the path and the content of the configuration file
|
||||
✓ it tells an identical copy under another name apart from the original
|
||||
✓ it resolves a configuration directory the way PHPUnit does
|
||||
✓ it gives a run with --no-configuration its own fingerprint
|
||||
✓ it fingerprints the configuration Pest generates the way the Xdebug restarter does with dataset "first name"
|
||||
✓ it fingerprints the configuration Pest generates the way the Xdebug restarter does with dataset "fallback name"
|
||||
✓ it fingerprints the configuration Pest generates the way the Xdebug restarter does with dataset "random name"
|
||||
✓ it fingerprints an explicit configuration apart from the one Pest generates
|
||||
✓ it keeps the bootstrap and the include path the command line sets with the configuration Pest generates
|
||||
✓ it keeps the fingerprint of a run that sets no bootstrap and no include path
|
||||
✓ it fingerprints the bootstrap the command line sets relative to the project with dataset "separate value"
|
||||
✓ it fingerprints the bootstrap the command line sets relative to the project with dataset "equals form"
|
||||
✓ it tells two bootstraps apart
|
||||
✓ it tells a bootstrap with a backslash in its name apart from a bootstrap in a directory
|
||||
✓ it fingerprints each include path the command line sets relative to the project
|
||||
✓ it fingerprints the bootstrap of a run with --no-configuration
|
||||
✓ it fingerprints an include path equal to the project root as the project root
|
||||
✓ 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
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\ContentHash
|
||||
✓ of() → it returns false when file does not exist
|
||||
@@ -1975,6 +2089,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
|
||||
@@ -1983,6 +2180,11 @@
|
||||
✓ compute() → it fingerprints tracked structural files in a regular clone
|
||||
✓ compute() → it fingerprints tracked structural files inside a linked git worktree
|
||||
✓ 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
|
||||
@@ -2015,6 +2217,12 @@
|
||||
✓ 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
|
||||
✓ legacy schema → it rebuilds a graph of an unknown schema but still lists its branches
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\IsEnabledForRun
|
||||
✓ does not throw when an integer --random-order-seed is passed as a separate argv element
|
||||
@@ -2042,12 +2250,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"
|
||||
@@ -2062,11 +2284,25 @@
|
||||
✓ the file wrapper → it is restored when the recorder resets
|
||||
✓ 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
|
||||
✓ the file wrapper → it is restored quietly when the test unregistered it
|
||||
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a link to an existing file"
|
||||
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a dangling link"
|
||||
✓ a wrapper already registered for file:// → it opens reads through it and still links them
|
||||
✓ a wrapper already registered for file:// → it keeps the include flag for the files a test includes
|
||||
✓ a wrapper already registered for file:// → it is registered again after the test
|
||||
✓ a __call wrapper already registered for file:// → it passes reads, includes and directory listings through it
|
||||
✓ withoutReadCapture() → it does not link a file matching an excluded glob
|
||||
✓ withoutReadCapture() → it still links a file outside the excluded globs
|
||||
✓ withoutReadCapture() → it keeps the file wrapper registered while globs are excluded
|
||||
✓ withoutReadCapture() → it links every read when the list of globs is empty
|
||||
✓ withoutReadCapture() → it registers no wrapper and links no read when called without globs
|
||||
✓ 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
|
||||
✓ activateLinkTracking() → it tracks tables without a coverage driver
|
||||
@@ -2090,6 +2326,7 @@
|
||||
PASS Tests\Unit\Plugins\Tia\Storage
|
||||
✓ it uses a project-relative configured directory
|
||||
✓ it uses an absolute configured directory
|
||||
✓ it keeps the state directory of a project at the repository root
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\TableExtractor
|
||||
✓ fromSql() → it extracts tables from plain DML
|
||||
@@ -2202,6 +2439,9 @@
|
||||
✓ it keeps every import a single file component declares with ('default-export-in-line-comment')
|
||||
✓ it keeps every import a single file component declares with ('default-export-in-block-comment')
|
||||
✓ it keeps every import a single file component declares with ('default-export-in-string')
|
||||
✓ it keeps every import a single file component declares with ('generic-attribute')
|
||||
✓ it keeps every import a single file component declares with ('generic-attribute-single-quoted')
|
||||
✓ it keeps every import a single file component declares with ('generic-attribute-before-lang')
|
||||
✓ it reports the script block language so the parser matches it with ('script-setup')
|
||||
✓ it reports the script block language so the parser matches it with ('plain-script-with-default')
|
||||
✓ it reports the script block language so the parser matches it with ('typescript-lang')
|
||||
@@ -2216,6 +2456,9 @@
|
||||
✓ it reports the script block language so the parser matches it with ('default-export-in-line-comment')
|
||||
✓ it reports the script block language so the parser matches it with ('default-export-in-block-comment')
|
||||
✓ it reports the script block language so the parser matches it with ('default-export-in-string')
|
||||
✓ it reports the script block language so the parser matches it with ('generic-attribute')
|
||||
✓ it reports the script block language so the parser matches it with ('generic-attribute-single-quoted')
|
||||
✓ it reports the script block language so the parser matches it with ('generic-attribute-before-lang')
|
||||
✓ it always leaves a default export for importers to resolve against with ('script-setup')
|
||||
✓ it always leaves a default export for importers to resolve against with ('plain-script-with-default')
|
||||
✓ it always leaves a default export for importers to resolve against with ('typescript-lang')
|
||||
@@ -2230,6 +2473,12 @@
|
||||
✓ it always leaves a default export for importers to resolve against with ('default-export-in-line-comment')
|
||||
✓ it always leaves a default export for importers to resolve against with ('default-export-in-block-comment')
|
||||
✓ it always leaves a default export for importers to resolve against with ('default-export-in-string')
|
||||
✓ it always leaves a default export for importers to resolve against with ('generic-attribute')
|
||||
✓ it always leaves a default export for importers to resolve against with ('generic-attribute-single-quoted')
|
||||
✓ it always leaves a default export for importers to resolve against with ('generic-attribute-before-lang')
|
||||
✓ it ends the opening script tag after a quoted attribute that holds a closing angle bracket with ('generic-attribute')
|
||||
✓ it ends the opening script tag after a quoted attribute that holds a closing angle bracket with ('generic-attribute-single-quoted')
|
||||
✓ it ends the opening script tag after a quoted attribute that holds a closing angle bracket with ('generic-attribute-before-lang')
|
||||
✓ it does not add a second default export when the block already has one
|
||||
✓ it drops template and style markup that the parser would reject
|
||||
✓ it stubs assets as JS modules so rolldown does not reject them as CSS with ('/app/resources/css/app.css')
|
||||
@@ -2240,7 +2489,10 @@
|
||||
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-line-comment')
|
||||
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-block-comment')
|
||||
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-string')
|
||||
✓ it loads the rolldown that Vite+ exposes as vite/rolldown
|
||||
✓ it finds no rolldown when neither rolldown nor vite/rolldown resolves
|
||||
- it bundles a script setup component that mentions export default in a comment → rolldown is not resolvable.
|
||||
- it bundles a generic component whose script tag holds a closing angle bracket → rolldown is not resolvable.
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\WatchPatterns
|
||||
✓ it keeps the built-in fallbacks enabled by default
|
||||
@@ -2257,6 +2509,16 @@
|
||||
✓ it retains recorded Inertia dependencies when default watches are disabled
|
||||
✓ it retains recorded migration tables when default watches are disabled
|
||||
✓ it uses custom mappings for an unknown Vue page with defaults disabled
|
||||
✓ it captures every read by default
|
||||
✓ it excludes reads of files matching a glob
|
||||
✓ it matches read globs like watch patterns
|
||||
✓ it does not exclude a dotfile unless the glob names it
|
||||
✓ it accumulates read exclusions from repeated calls
|
||||
✓ it does not turn read capture off for an empty exclusion list
|
||||
✓ it turns read capture off without a list of globs
|
||||
✓ it keeps read capture off when globs are added afterwards
|
||||
✓ it captures reads again on reset
|
||||
✓ it does not change the default watch fallbacks of an excluded read
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\WorkerToken
|
||||
✓ prefers the per-process UNIQUE_TEST_TOKEN over the per-slot TEST_TOKEN, so two workers recycled into the same slot get different tokens
|
||||
@@ -2276,10 +2538,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
|
||||
@@ -2324,9 +2591,23 @@
|
||||
✓ 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
|
||||
|
||||
PASS Tests\Unit\Support\InstalledPackages
|
||||
✓ it finds a package that the project installs
|
||||
✓ it ignores a package that only a tool bundled in a PHAR installs
|
||||
✓ it leaves out a development requirement when asked
|
||||
✓ it reads an installed set that has no install path
|
||||
✓ it reads the packages that Composer loaded
|
||||
✓ it is the only class of src that reads Composer packages
|
||||
|
||||
PASS Tests\Unit\Support\Reflection
|
||||
✓ it gets file name from closure
|
||||
✓ it gets property values
|
||||
@@ -2441,6 +2722,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')
|
||||
@@ -2452,6 +2736,34 @@
|
||||
✓ 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
|
||||
|
||||
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
|
||||
|
||||
@@ -2523,6 +2835,9 @@
|
||||
✓ parallel counts a shared issue only once across recycled workers with ('notice', 'shares notice', 'notice')
|
||||
✓ parallel combines stop-on counts from different workers and cleans up their files
|
||||
|
||||
PASS Tests\Visual\ParallelWorkerAutoload
|
||||
✓ loads the autoloader of the parent process in a parallel worker
|
||||
|
||||
PASS Tests\Visual\Shard
|
||||
✓ an empty shard runs no tests with dataset "sequential"
|
||||
✓ an empty shard runs no tests with dataset "parallel"
|
||||
@@ -2534,6 +2849,9 @@
|
||||
PASS Tests\Visual\SingleTestOrDirectory
|
||||
✓ allows to run a single test
|
||||
✓ allows to run a directory
|
||||
✓ allows to run a single test using its namespace
|
||||
✓ keeps namespace filters unchanged
|
||||
✓ converts a namespace after the retry flag
|
||||
✓ it disable decorating printer when colors is set to never
|
||||
|
||||
WARN Tests\Visual\Success
|
||||
@@ -2557,9 +2875,11 @@
|
||||
|
||||
WARN Tests\Visual\Version
|
||||
- visual snapshot of help command output
|
||||
✓ prints information when the tests directory is missing with dataset "help"
|
||||
✓ prints information when the tests directory is missing with dataset "version"
|
||||
|
||||
PASS Testsexternal\Features\Expect\toMatchSnapshot
|
||||
✓ 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, 38 skipped, 1856 passed (4269 assertions)
|
||||
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 44 skipped, 2136 passed (4703 assertions)
|
||||
@@ -100,3 +100,29 @@ describe('matching describe block names', function (): void {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('hierarchical test naming', function (): void {
|
||||
describe('block one', function (): void {
|
||||
describe('the same name', function (): void {
|
||||
it('does not call afterEach from sibling describe with same name', function (): void {
|
||||
expect($this)->not->toHaveProperty('example');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('block two', function (): void {
|
||||
describe('the same name', function (): void {
|
||||
beforeEach(function (): void {
|
||||
$this->example = false;
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
expect($this->example)->toBeFalse();
|
||||
});
|
||||
|
||||
it('correctly calls afterEach from own describe hierarchy', function (): void {
|
||||
expect($this->example)->toBeFalse();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -126,3 +126,29 @@ describe('called on all tests', function (): void {
|
||||
expect($this->baz)->toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hierarchical test naming', function (): void {
|
||||
describe('block one', function (): void {
|
||||
describe('the same name', function (): void {
|
||||
it('does not call beforeEach from sibling describe with same name', function (): void {
|
||||
expect($this)->not->toHaveProperty('example');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('block two', function (): void {
|
||||
beforeEach(function (): void {
|
||||
$this->example = false;
|
||||
});
|
||||
|
||||
describe('the same name', function (): void {
|
||||
beforeEach(function (): void {
|
||||
$this->result = $this->example;
|
||||
});
|
||||
|
||||
it('correctly calls beforeEach from own describe hierarchy', function (): void {
|
||||
expect($this->result)->toBeFalse();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -108,3 +108,17 @@ describe('with test after describe', function (): void {
|
||||
expect($this->count)->toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sibling describes may share the same it() description', function (): void {
|
||||
describe('block one', function (): void {
|
||||
it('can be created', function (): void {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
});
|
||||
|
||||
describe('block two', function (): void {
|
||||
it('can be created', function (): void {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
+64
-6
@@ -63,7 +63,7 @@ test('a missing tests directory does not crash while resolving tia state', funct
|
||||
$root = makeInitProject();
|
||||
|
||||
try {
|
||||
$process = runInitProject($root, '--version');
|
||||
$process = runInitProject($root);
|
||||
|
||||
expect($process->getExitCode())->not->toBe(0)
|
||||
->and($process->getOutput())->toContain('does not exist')
|
||||
@@ -74,6 +74,23 @@ test('a missing tests directory does not crash while resolving tia state', funct
|
||||
}
|
||||
});
|
||||
|
||||
test('init writes the plain stubs when only a tool bundled in a PHAR installs Laravel', function (): void {
|
||||
$root = makeInitProject();
|
||||
|
||||
try {
|
||||
$toolLoader = makeLaravelToolPhar($root);
|
||||
|
||||
$process = runInitProjectWithPhpOptions(['-d', 'auto_prepend_file='.$toolLoader], $root, '--init');
|
||||
|
||||
expect($process->getExitCode())->toBe(0)
|
||||
->and(file_get_contents($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Pest.php'))
|
||||
->toContain("require_once __DIR__.'/TestCase.php';")
|
||||
->not->toContain('RefreshDatabase');
|
||||
} finally {
|
||||
removeInitProject($root);
|
||||
}
|
||||
})->skipOnWindows();
|
||||
|
||||
function makeInitProject(): string
|
||||
{
|
||||
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-init-'.bin2hex(random_bytes(4));
|
||||
@@ -110,10 +127,6 @@ require {$autoload};
|
||||
|
||||
\$arguments = array_slice(\$argv, 1);
|
||||
|
||||
if (\$arguments === []) {
|
||||
\$arguments = ['--version'];
|
||||
}
|
||||
|
||||
\$GLOBALS['_composer_bin_dir'] = getcwd().'/vendor/bin';
|
||||
|
||||
\$_SERVER['argv'] = ['pest', ...\$arguments];
|
||||
@@ -138,10 +151,55 @@ PHP);
|
||||
return $root;
|
||||
}
|
||||
|
||||
function makeLaravelToolPhar(string $root): string
|
||||
{
|
||||
$phar = $root.DIRECTORY_SEPARATOR.'tool.phar';
|
||||
|
||||
$build = new Process([
|
||||
PHP_BINARY,
|
||||
'-d',
|
||||
'phar.readonly=0',
|
||||
'-r',
|
||||
<<<'PHP'
|
||||
$phar = new Phar($argv[1]);
|
||||
$phar->addFromString('vendor/composer/installed.php', <<<'INSTALLED'
|
||||
<?php
|
||||
|
||||
return [
|
||||
'root' => ['name' => 'tool/dumper', 'install_path' => __DIR__.'/../../'],
|
||||
'versions' => ['laravel/framework' => ['pretty_version' => 'v12.0.0', 'version' => '12.0.0.0', 'dev_requirement' => false]],
|
||||
];
|
||||
INSTALLED);
|
||||
$phar->setStub('<?php __HALT_COMPILER();');
|
||||
PHP,
|
||||
$phar,
|
||||
]);
|
||||
|
||||
$build->mustRun();
|
||||
|
||||
$loader = $root.DIRECTORY_SEPARATOR.'tool-loader.php';
|
||||
|
||||
file_put_contents($loader, sprintf(
|
||||
"<?php\n\nrequire_once %s;\n\n(new Composer\\Autoload\\ClassLoader(%s))->register();\n",
|
||||
var_export(dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'composer'.DIRECTORY_SEPARATOR.'ClassLoader.php', true),
|
||||
var_export('phar://'.$phar.'/vendor', true),
|
||||
));
|
||||
|
||||
return $loader;
|
||||
}
|
||||
|
||||
function runInitProject(string $root, string ...$command): Process
|
||||
{
|
||||
return runInitProjectWithPhpOptions([], $root, ...$command);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $phpOptions
|
||||
*/
|
||||
function runInitProjectWithPhpOptions(array $phpOptions, string $root, string ...$command): Process
|
||||
{
|
||||
$process = new Process(
|
||||
[PHP_BINARY, 'run.php', ...$command],
|
||||
[PHP_BINARY, ...$phpOptions, 'run.php', ...$command],
|
||||
$root,
|
||||
[
|
||||
'PEST_NO_SUPPORT' => 'true',
|
||||
|
||||
@@ -34,10 +34,6 @@ it('does not run user hooks when replaying cached skipped and incomplete results
|
||||
$graph->setResult($branch, $id('replayed skip'), 1, 'cached skip', 0.01, 0, $fixture);
|
||||
$graph->setResult($branch, $id('replayed incomplete'), 2, 'cached incomplete', 0.01, 0, $fixture);
|
||||
|
||||
$json = $graph->encode();
|
||||
|
||||
expect($json)->not->toBeNull();
|
||||
|
||||
$originalHome = getenv('HOME');
|
||||
putenv('HOME='.$home);
|
||||
|
||||
@@ -47,7 +43,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
|
||||
putenv($originalHome === false ? 'HOME' : 'HOME='.$originalHome);
|
||||
}
|
||||
|
||||
expect($storage->write(Tia::KEY_GRAPH, (string) $json))->toBeTrue();
|
||||
expect($storage->write(Tia::KEY_GRAPH, $graph->encode()))->toBeTrue();
|
||||
|
||||
$process = new Process(
|
||||
['php', 'bin/pest', '--configuration', $configuration, '--tia'],
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Support\Coverage;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
@@ -100,3 +101,102 @@ test('an identical copy of the configuration file under another name does not re
|
||||
->and($result->replayed())->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
function removeConfiguration(Project $project): void
|
||||
{
|
||||
$project->git()->run(['rm', '--quiet', 'phpunit.xml']);
|
||||
$project->write('.gitignore', file_get_contents($project->path('.gitignore'))."/.pest*.xml\n");
|
||||
$project->git()->commit('use the configuration Pest generates');
|
||||
$project->write('vendor/pestphp/pest/.temp/.gitkeep', '');
|
||||
}
|
||||
|
||||
test('a project without a configuration file replays the graph', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
removeConfiguration($project);
|
||||
$project->seed('master');
|
||||
|
||||
$result = $project->pest('--tia', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a leftover generated configuration file does not discard the graph', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
removeConfiguration($project);
|
||||
$project->seed('master');
|
||||
$project->write('.pest.xml', (string) file_get_contents($project->path('vendor/pestphp/pest/resources/base-phpunit.xml')));
|
||||
|
||||
$replayed = $project->pest('--tia', ...$arguments);
|
||||
|
||||
expect($replayed->exitCode)->toBe(0, $replayed->describe())
|
||||
->and($replayed->replayed())->toBe(Project::TOTAL_TESTS, $replayed->describe());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a graph recorded under one bootstrap is not replayed under the bootstrap the command line sets', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->write('tests/AlternateBootstrap.php', "<?php\n\nrequire __DIR__.'/../vendor/autoload.php';\n");
|
||||
$project->git()->commit('add an alternate bootstrap');
|
||||
$project->seed('master');
|
||||
|
||||
$result = $project->pest('--tia', '--bootstrap', 'tests/AlternateBootstrap.php', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->replayed())->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a graph recorded under the bootstrap the command line sets is replayed under the same bootstrap', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->write('tests/AlternateBootstrap.php', "<?php\n\nrequire __DIR__.'/../vendor/autoload.php';\n");
|
||||
$project->git()->commit('add an alternate bootstrap');
|
||||
|
||||
$project->pest('--tia', '--bootstrap', 'tests/AlternateBootstrap.php', ...$arguments);
|
||||
|
||||
$result = $project->pest('--tia', '--bootstrap', 'tests/AlternateBootstrap.php', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a graph recorded under a bootstrap whose name looks like an include path is not replayed under that bootstrap and include path', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$bootstrap = "<?php\n\nrequire __DIR__.'/../vendor/autoload.php';\n";
|
||||
$project->write('tests/Boot.php', $bootstrap);
|
||||
$project->write('tests/Boot.php;include-path=app', $bootstrap);
|
||||
$project->git()->commit('add two bootstraps');
|
||||
|
||||
$project->pest('--tia', '--bootstrap', 'tests/Boot.php;include-path=app', ...$arguments);
|
||||
|
||||
$result = $project->pest('--tia', '--bootstrap', 'tests/Boot.php', '--include-path', 'app');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->replayed())->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a graph recorded under a bootstrap with a backslash in its name is not replayed under the bootstrap in a directory', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->write('tests/Boot.php', "<?php\n\nrequire __DIR__.'/../vendor/autoload.php';\n");
|
||||
$project->write('tests\\Boot.php', "<?php\n\nrequire __DIR__.'/vendor/autoload.php';\n");
|
||||
$project->git()->commit('add two bootstraps');
|
||||
|
||||
$project->pest('--tia', '--bootstrap', 'tests\\Boot.php', ...$arguments);
|
||||
|
||||
$result = $project->pest('--tia', '--bootstrap', 'tests/Boot.php', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->replayed())->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a graph recorded without an include path is not replayed under the include path the command line sets', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$result = $project->pest('--tia', '--include-path', 'app');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->replayed())->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
|
||||
})->skipOnWindows();
|
||||
|
||||
@@ -158,18 +158,6 @@ test('the default branch baseline survives every branch that comes and goes', fu
|
||||
->and($project->graph()['baselines']['master']['results'])->toHaveCount(Project::TOTAL_TESTS);
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a project below the git repository root refuses to run and writes nothing', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$nested = $project->nested();
|
||||
|
||||
$result = $project->pestIn($nested, '--tia', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(1, $result->describe())
|
||||
->and($result->output)->toContain('Tia mode requires the git repository root')
|
||||
->and($project->path('.home/.pest'))->not->toBeDirectory()
|
||||
->and($nested.DIRECTORY_SEPARATOR.'.pest')->not->toBeDirectory();
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a repository with no commits says so, and leaves plain runs alone', function (): void {
|
||||
$project = Project::withoutGit();
|
||||
$project->git()->run(['init', '--quiet']);
|
||||
|
||||
@@ -179,6 +179,19 @@ test('tia still requires git', function (): void {
|
||||
->and($result->exitCode)->not->toBe(0);
|
||||
})->skipOnWindows();
|
||||
|
||||
test('tia still requires git when git speaks another language', function (): void {
|
||||
$project = Project::withoutGit();
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), [
|
||||
'LC_ALL' => 'es_ES.UTF-8',
|
||||
'LANG' => 'es_ES.UTF-8',
|
||||
'LANGUAGE' => 'es',
|
||||
], '--tia');
|
||||
|
||||
expect($result->output)->toContain('The [Tia mode] feature requires [git].')
|
||||
->and($result->exitCode)->toBe(1, $result->describe());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a failing git shows its own error instead of asking for git', function (): void {
|
||||
$project = Project::make('master');
|
||||
|
||||
|
||||
@@ -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();
|
||||
@@ -179,7 +179,7 @@ test('a graph from a schema this build does not know is rebuilt, not read', func
|
||||
$project->seed('master');
|
||||
|
||||
$project->mutateGraph(function (array $graph): array {
|
||||
$graph['schema'] = 2;
|
||||
$graph['schema'] = 99;
|
||||
|
||||
return $graph;
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
test('a changed file whose name is not valid UTF-8 keeps the graph writable', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$project->write("caf\xe9.txt", "one\n");
|
||||
|
||||
$first = $project->pest('--tia', ...$arguments);
|
||||
|
||||
expect($first->exitCode)->toBe(0, $first->describe())
|
||||
->and($first->output)->not->toContain('Could not write the dependency graph')
|
||||
->and($project->graph()['baselines']['master']['tree'] ?? [])->toHaveKey("caf\xe9.txt");
|
||||
|
||||
$second = $project->pest('--tia', ...$arguments);
|
||||
|
||||
expect($second->exitCode)->toBe(0, $second->describe())
|
||||
->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->onlyOnLinux();
|
||||
@@ -25,6 +25,19 @@ function tiaRecordWithSourceReadingTest(Project $project, string ...$arguments):
|
||||
$project->pest('--tia', ...$arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
function tiaEdgeFiles(Project $project, string $testFile): array
|
||||
{
|
||||
$graph = $project->graph() ?? [];
|
||||
|
||||
return array_map(
|
||||
fn (int $id): string => $graph['files'][$id],
|
||||
$graph['edges'][$testFile] ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
test('a test that reads a file records an edge to it', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
|
||||
@@ -108,3 +121,68 @@ test('a file a test reads does not select it when another file changes', functio
|
||||
expect($result->affected())->toBe(4, $result->describe())
|
||||
->and($result->replayed())->toBe(3, $result->describe());
|
||||
})->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a test that reads an excluded file records no edge to it', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
|
||||
"\npest()->tia()->withoutReadCapture(['app/Greeter.php']);\n");
|
||||
|
||||
tiaRecordWithSourceReadingTest($project, ...$arguments);
|
||||
|
||||
expect(tiaEdgeFiles($project, 'tests/Unit/GreeterTest.php'))->toContain('app/Greeter.php')
|
||||
->and(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->not->toContain('app/Greeter.php');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a test that reads a file outside the excluded globs still records an edge to it', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
|
||||
"\npest()->tia()->withoutReadCapture(['lang/*.json']);\n");
|
||||
|
||||
tiaRecordWithSourceReadingTest($project, ...$arguments);
|
||||
|
||||
expect(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->toContain('app/Greeter.php');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('no read records an edge when read capture is off', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
|
||||
"\npest()->tia()->withoutReadCapture();\n");
|
||||
|
||||
tiaRecordWithSourceReadingTest($project, ...$arguments);
|
||||
|
||||
expect(tiaEdgeFiles($project, 'tests/Unit/GreeterTest.php'))->toContain('app/Greeter.php')
|
||||
->and(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->not->toContain('app/Greeter.php');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a watch pattern reruns tests after an excluded file changes', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
|
||||
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).<<<'PHP'
|
||||
|
||||
pest()->tia()
|
||||
->withoutReadCapture(['data/*.json'])
|
||||
->watch(['data/*.json' => 'tests/Unit/GreeterTest.php']);
|
||||
|
||||
PHP);
|
||||
$project->write('data/status.json', '"ready"');
|
||||
|
||||
$testFile = 'tests/Unit/GreeterTest.php';
|
||||
$project->write($testFile, str_replace(
|
||||
' expect((new Greeter)->greet(\'Nuno\'))->toBe(\'Hello, Nuno!\');',
|
||||
' expect(file_get_contents(__DIR__.\'/../../data/status.json\'))->toBe(\'"ready"\');',
|
||||
file_get_contents($project->path($testFile)),
|
||||
));
|
||||
|
||||
$project->git()->commit('add a watched JSON fixture');
|
||||
$project->seed('master');
|
||||
|
||||
$project->write('data/status.json', '"broken"');
|
||||
$project->git()->commit('change the watched fixture');
|
||||
|
||||
$result = $project->pest('--tia', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(1, $result->describe())
|
||||
->and($result->affected())->toBe(2, $result->describe())
|
||||
->and($result->replayed())->toBe(4, $result->describe())
|
||||
->and($result->output)->toContain('greets a person', 'broken');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->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();
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use PHPUnit\Framework\TestStatus\TestStatus;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
@@ -385,3 +386,25 @@ test('a full suite run without a coverage driver clears the tree it could not re
|
||||
->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe())
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a full suite run without a coverage driver records the results it ran', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$id = Project::testId('tests/Unit/CalculatorTest.php', 'adds two numbers');
|
||||
|
||||
expect($project->graph()['baselines']['master']['results'][$id]['status'])->toBe(TestStatus::success()->asInt());
|
||||
|
||||
$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('break the adder');
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), ['XDEBUG_MODE' => 'off'], '--tia', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(1, $result->describe())
|
||||
->and($result->output)->toContain('no coverage driver is available')
|
||||
->and($project->graph()['baselines']['master']['results'][$id]['status'])->toBe(TestStatus::failure()->asInt());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
@@ -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);
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Fixtures\Tia;
|
||||
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class CallForwardingFileWrapper
|
||||
{
|
||||
/**
|
||||
* @var resource|null
|
||||
*/
|
||||
public mixed $context = null;
|
||||
|
||||
/**
|
||||
* @var resource
|
||||
*/
|
||||
private mixed $resource;
|
||||
|
||||
public static function enable(): void
|
||||
{
|
||||
stream_wrapper_unregister('file');
|
||||
stream_wrapper_register('file', self::class);
|
||||
}
|
||||
|
||||
public static function disable(): void
|
||||
{
|
||||
stream_wrapper_restore('file');
|
||||
}
|
||||
|
||||
public function stream_open(string $path, string $mode, int $options): bool
|
||||
{
|
||||
$resource = $this->native(fn (): mixed => @fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0));
|
||||
|
||||
if ($resource === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->resource = $resource;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function dir_opendir(string $path): bool
|
||||
{
|
||||
$resource = $this->native(fn (): mixed => @opendir($path));
|
||||
|
||||
if ($resource === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->resource = $resource;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, mixed> $arguments
|
||||
*/
|
||||
public function __call(string $method, array $arguments): mixed
|
||||
{
|
||||
return match ($method) {
|
||||
'stream_read' => fread($this->resource, max(1, (int) $arguments[0])),
|
||||
'stream_write' => fwrite($this->resource, (string) $arguments[0]),
|
||||
'stream_eof' => feof($this->resource),
|
||||
'stream_close' => fclose($this->resource),
|
||||
'stream_stat' => fstat($this->resource),
|
||||
'dir_readdir' => readdir($this->resource),
|
||||
'dir_closedir' => closedir($this->resource) ?? true,
|
||||
'url_stat' => $this->native(fn (): mixed => @stat((string) $arguments[0])),
|
||||
'unlink' => $this->native(fn (): bool => @unlink((string) $arguments[0])),
|
||||
default => false,
|
||||
};
|
||||
}
|
||||
|
||||
private function native(Closure $callback): mixed
|
||||
{
|
||||
self::disable();
|
||||
|
||||
try {
|
||||
return $callback();
|
||||
} finally {
|
||||
self::enable();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,10 @@ namespace Tests\Fixtures\Tia;
|
||||
|
||||
use FilesystemIterator;
|
||||
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;
|
||||
@@ -131,6 +133,9 @@ final class Project
|
||||
}
|
||||
|
||||
self::copy(__DIR__.'/app', $path);
|
||||
|
||||
$this->write($directory.DIRECTORY_SEPARATOR.'.gitignore', implode("\n", ['/vendor/', '/.phpunit.cache/', '']));
|
||||
|
||||
$this->scaffoldVendor($path);
|
||||
|
||||
return $path;
|
||||
@@ -157,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',
|
||||
@@ -181,6 +200,7 @@ final class Project
|
||||
'GITHUB_REF_NAME' => false,
|
||||
'GITLAB_CI' => false,
|
||||
'CIRCLECI' => false,
|
||||
'COMPOSER' => false,
|
||||
...$environment,
|
||||
],
|
||||
);
|
||||
@@ -189,7 +209,7 @@ final class Project
|
||||
$process->run();
|
||||
|
||||
return new PestResult(
|
||||
array_values($arguments),
|
||||
$arguments,
|
||||
$process->getOutput().$process->getErrorOutput(),
|
||||
(int) $process->getExitCode(),
|
||||
);
|
||||
@@ -200,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));
|
||||
|
||||
@@ -245,13 +291,7 @@ final class Project
|
||||
}
|
||||
}
|
||||
|
||||
$json = $graph->encode();
|
||||
|
||||
if ($json === null) {
|
||||
throw new RuntimeException('Unable to encode the seeded graph.');
|
||||
}
|
||||
|
||||
if (! $this->state()->write(Tia::KEY_GRAPH, $json)) {
|
||||
if (! $this->state()->write(Tia::KEY_GRAPH, $graph->encode())) {
|
||||
throw new RuntimeException('Unable to persist the seeded graph.');
|
||||
}
|
||||
|
||||
@@ -362,7 +402,7 @@ final class Project
|
||||
throw new RuntimeException('There is no graph to mutate.');
|
||||
}
|
||||
|
||||
$this->state()->write(Tia::KEY_GRAPH, (string) json_encode($callback($graph), JSON_UNESCAPED_SLASHES));
|
||||
$this->state()->write(Tia::KEY_GRAPH, ByteSafeJson::encode($callback($graph)));
|
||||
|
||||
$this->snapshot();
|
||||
}
|
||||
@@ -378,7 +418,7 @@ final class Project
|
||||
return null;
|
||||
}
|
||||
|
||||
$graph = json_decode($json, true);
|
||||
$graph = ByteSafeJson::decode($json);
|
||||
|
||||
return is_array($graph) ? $graph : null;
|
||||
}
|
||||
@@ -395,7 +435,12 @@ final class Project
|
||||
|
||||
public function graphDir(): string
|
||||
{
|
||||
return $this->withHome(fn (): string => Storage::tempDir($this->graphRoot));
|
||||
return $this->stateDirFor($this->graphRoot);
|
||||
}
|
||||
|
||||
public function stateDirFor(string $root): string
|
||||
{
|
||||
return $this->withHome(fn (): string => Storage::tempDir($root));
|
||||
}
|
||||
|
||||
public function graphExists(): bool
|
||||
@@ -415,29 +460,12 @@ final class Project
|
||||
|
||||
public function scaffoldVendor(string $directory): void
|
||||
{
|
||||
$pestRoot = dirname(__DIR__, 3);
|
||||
$pest = $directory.'/vendor/pestphp/pest';
|
||||
$this->scaffoldPest($directory.'/vendor/pestphp/pest', $directory.'/vendor', '/pestphp/pest/src');
|
||||
}
|
||||
|
||||
foreach (['src', 'overrides', 'resources', 'stubs'] as $tree) {
|
||||
self::mirror($pestRoot.'/'.$tree, $pest.'/'.$tree);
|
||||
}
|
||||
|
||||
foreach (['pest', 'worker.php'] as $binary) {
|
||||
self::mirror($pestRoot.'/bin/'.$binary, $pest.'/bin/'.$binary);
|
||||
}
|
||||
|
||||
self::mirror($pestRoot.'/composer.json', $pest.'/composer.json');
|
||||
|
||||
file_put_contents($directory.'/vendor/autoload.php', sprintf(
|
||||
"<?php\n\n\$loader = require %s;\n\$loader->addPsr4('Pest\\\\', __DIR__.'/pestphp/pest/src', true);\n\nreturn \$loader;\n",
|
||||
var_export($pestRoot.'/vendor/autoload.php', true),
|
||||
));
|
||||
|
||||
if (! is_dir($directory.'/vendor/bin') && ! @mkdir($directory.'/vendor/bin', 0755, true)) {
|
||||
throw new RuntimeException(sprintf('Unable to create [%s].', $directory.'/vendor/bin'));
|
||||
}
|
||||
|
||||
self::mirror($pestRoot.'/vendor/pest-plugins.json', $directory.'/vendor/pest-plugins.json');
|
||||
public function scaffoldCheckout(string $directory): void
|
||||
{
|
||||
$this->scaffoldPest($directory, $directory.'/vendor', '/../src');
|
||||
}
|
||||
|
||||
public function destroy(): void
|
||||
@@ -504,6 +532,33 @@ final class Project
|
||||
return $project;
|
||||
}
|
||||
|
||||
private function scaffoldPest(string $pest, string $vendor, string $sourceFromVendor): void
|
||||
{
|
||||
$pestRoot = dirname(__DIR__, 3);
|
||||
|
||||
foreach (['src', 'overrides', 'resources', 'stubs'] as $tree) {
|
||||
self::mirror($pestRoot.'/'.$tree, $pest.'/'.$tree);
|
||||
}
|
||||
|
||||
foreach (['pest', 'worker.php'] as $binary) {
|
||||
self::mirror($pestRoot.'/bin/'.$binary, $pest.'/bin/'.$binary);
|
||||
}
|
||||
|
||||
self::mirror($pestRoot.'/composer.json', $pest.'/composer.json');
|
||||
|
||||
if (! is_dir($vendor.'/bin') && ! @mkdir($vendor.'/bin', 0755, true)) {
|
||||
throw new RuntimeException(sprintf('Unable to create [%s].', $vendor.'/bin'));
|
||||
}
|
||||
|
||||
file_put_contents($vendor.'/autoload.php', sprintf(
|
||||
"<?php\n\n\$loader = require %s;\n\$loader->addPsr4('Pest\\\\', __DIR__.%s, true);\n\nreturn \$loader;\n",
|
||||
var_export($pestRoot.'/vendor/autoload.php', true),
|
||||
var_export($sourceFromVendor, true),
|
||||
));
|
||||
|
||||
self::mirror($pestRoot.'/vendor/pest-plugins.json', $vendor.'/pest-plugins.json');
|
||||
}
|
||||
|
||||
private static function mirror(string $from, string $to): void
|
||||
{
|
||||
if (is_dir($from)) {
|
||||
|
||||
@@ -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,114 @@
|
||||
<?php
|
||||
|
||||
use Pest\Contracts\Plugins\AddsOutput;
|
||||
use Pest\Contracts\Plugins\ObservesExitCode;
|
||||
use Pest\Plugin\Loader;
|
||||
use Pest\Plugins\Actions\CallsAddsOutput;
|
||||
|
||||
function withExitCodePlugins(array $plugins, Closure $test): void
|
||||
{
|
||||
$loader = new ReflectionClass(Loader::class);
|
||||
$instances = $loader->getProperty('instances');
|
||||
$loaded = $loader->getProperty('loaded');
|
||||
$previousInstances = $instances->getValue();
|
||||
$previousLoaded = $loaded->getValue();
|
||||
|
||||
try {
|
||||
$instances->setValue(null, $plugins);
|
||||
$loaded->setValue(null, true);
|
||||
|
||||
$test();
|
||||
} finally {
|
||||
$instances->setValue(null, $previousInstances);
|
||||
$loaded->setValue(null, $previousLoaded);
|
||||
}
|
||||
}
|
||||
|
||||
test('exit code observers run after every output plugin', function (): void {
|
||||
$events = new ArrayObject;
|
||||
$observer = new readonly class($events) implements ObservesExitCode
|
||||
{
|
||||
public function __construct(private ArrayObject $events) {}
|
||||
|
||||
public function observeExitCode(int $exitCode): void
|
||||
{
|
||||
$this->events[] = ['observed', $exitCode];
|
||||
}
|
||||
};
|
||||
$output = new readonly class($events) implements AddsOutput
|
||||
{
|
||||
public function __construct(private ArrayObject $events) {}
|
||||
|
||||
public function addOutput(int $exitCode): int
|
||||
{
|
||||
$this->events[] = ['output', $exitCode];
|
||||
|
||||
return $exitCode + 1;
|
||||
}
|
||||
};
|
||||
|
||||
withExitCodePlugins([$observer, $output, clone $observer, clone $output], function () use ($events): void {
|
||||
expect(CallsAddsOutput::execute(0))->toBe(2)
|
||||
->and($events->getArrayCopy())->toBe([
|
||||
['output', 0],
|
||||
['output', 1],
|
||||
['observed', 2],
|
||||
['observed', 2],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
test('exit code observers receive unchanged codes when there are no output plugins', function (int $exitCode): void {
|
||||
$observer = new class implements ObservesExitCode
|
||||
{
|
||||
public ?int $exitCode = null;
|
||||
|
||||
public function observeExitCode(int $exitCode): void
|
||||
{
|
||||
$this->exitCode = $exitCode;
|
||||
}
|
||||
};
|
||||
|
||||
withExitCodePlugins([$observer], function () use ($observer, $exitCode): void {
|
||||
expect(CallsAddsOutput::execute($exitCode))->toBe($exitCode)
|
||||
->and($observer->exitCode)->toBe($exitCode);
|
||||
});
|
||||
})->with([0, 1, 2, 42]);
|
||||
|
||||
test('output plugins work without exit code observers', function (): void {
|
||||
$output = new class implements AddsOutput
|
||||
{
|
||||
public function addOutput(int $exitCode): int
|
||||
{
|
||||
return 42;
|
||||
}
|
||||
};
|
||||
|
||||
withExitCodePlugins([$output], function (): void {
|
||||
expect(CallsAddsOutput::execute(0))->toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
test('exit code observers are not called when an output plugin throws', function (): void {
|
||||
$observer = new class implements ObservesExitCode
|
||||
{
|
||||
public bool $called = false;
|
||||
|
||||
public function observeExitCode(int $exitCode): void
|
||||
{
|
||||
$this->called = true;
|
||||
}
|
||||
};
|
||||
$output = new class implements AddsOutput
|
||||
{
|
||||
public function addOutput(int $exitCode): int
|
||||
{
|
||||
throw new RuntimeException('Output failed');
|
||||
}
|
||||
};
|
||||
|
||||
withExitCodePlugins([$observer, $output], function () use ($observer): void {
|
||||
expect(fn (): int => CallsAddsOutput::execute(0))->toThrow(RuntimeException::class, 'Output failed')
|
||||
->and($observer->called)->toBeFalse();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Pest\Exceptions\InvalidOption;
|
||||
use Pest\Plugins\Retry;
|
||||
|
||||
it('orders by defects and stop on defects if when --retry is used ', function (): void {
|
||||
@@ -12,3 +13,10 @@ it('orders by defects and stop on defects if when --retry is used ', function ()
|
||||
'--stop-on-failure',
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects retry with a parallel flag', function (string $parallelFlag): void {
|
||||
(new Retry)->handleArguments(['--retry', $parallelFlag]);
|
||||
})->with(['--parallel', '-p'])->throws(
|
||||
InvalidOption::class,
|
||||
'The [--retry] option is not supported when running in parallel.',
|
||||
);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
use Pest\Exceptions\InvalidOption;
|
||||
use Pest\Plugins\Shard;
|
||||
use Pest\Subscribers\EnsureShardTimingsAreCollected;
|
||||
use Pest\Support\Arr;
|
||||
use SebastianBergmann\CliParser\Parser;
|
||||
use Symfony\Component\Console\Input\ArgvInput;
|
||||
use Symfony\Component\Console\Output\BufferedOutput;
|
||||
@@ -563,6 +565,37 @@ describe('buildListTestsCommand', function (): void {
|
||||
'--list-tests',
|
||||
]);
|
||||
});
|
||||
|
||||
it('strips paratest-only options when building the list-tests command', function (array $arguments): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$reflection = new ReflectionClass($shard);
|
||||
$method = $reflection->getMethod('buildListTestsCommand');
|
||||
|
||||
$command = $method->invoke($shard, ['vendor/bin/pest', '--parallel', ...$arguments, '--stop-on-failure', '--update-shards'], 'tests');
|
||||
|
||||
expect($command)->toBe([
|
||||
PHP_BINARY,
|
||||
'vendor/bin/pest',
|
||||
'--stop-on-failure',
|
||||
'--update-shards',
|
||||
'--test-directory=tests',
|
||||
'--list-tests',
|
||||
]);
|
||||
})->with([
|
||||
'--max-batch-size=N' => [['--max-batch-size=100']],
|
||||
'--max-batch-size N' => [['--max-batch-size', '100']],
|
||||
'-m N' => [['-m', '100']],
|
||||
'-mN' => [['-m100']],
|
||||
'-m=N' => [['-m=100']],
|
||||
'--processes N' => [['--processes', '8']],
|
||||
'--max-processes=N' => [['--max-processes=8']],
|
||||
'--passthru-php' => [['--passthru-php=-d memory_limit=1G']],
|
||||
'--tmp-dir' => [['--tmp-dir', '/tmp/paratest']],
|
||||
'--functional' => [['--functional']],
|
||||
'--no-test-tokens' => [['--no-test-tokens']],
|
||||
]);
|
||||
});
|
||||
|
||||
describe('addOutput', function (): void {
|
||||
@@ -624,3 +657,308 @@ describe('addOutput', function (): void {
|
||||
->and($outputText)->not->toContain('Shard:');
|
||||
});
|
||||
});
|
||||
|
||||
describe('timings file', function (): void {
|
||||
afterEach(function (): void {
|
||||
$reflection = new ReflectionClass(Shard::class);
|
||||
$reflection->getProperty('timingsFilename')->setValue(null, null);
|
||||
$reflection->getProperty('externalTimings')->setValue(null, null);
|
||||
$reflection->getProperty('collectedTimings')->setValue(null, null);
|
||||
$reflection->getProperty('knownTests')->setValue(null, null);
|
||||
$reflection->getProperty('updateShards')->setValue(null, false);
|
||||
$reflection->getProperty('shard')->setValue(null, null);
|
||||
|
||||
new ReflectionClass(EnsureShardTimingsAreCollected::class)
|
||||
->getProperty('timings')
|
||||
->setValue(null, []);
|
||||
});
|
||||
|
||||
it('reads and writes shards.json until a plugin overrides the filename', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('shardsPath');
|
||||
|
||||
expect($method->invoke($shard))->toEndWith('.pest'.DIRECTORY_SEPARATOR.'shards.json');
|
||||
|
||||
Shard::useTimingsFile('mutation-shards.json');
|
||||
|
||||
expect($method->invoke($shard))->toEndWith('.pest'.DIRECTORY_SEPARATOR.'mutation-shards.json');
|
||||
});
|
||||
|
||||
it('prefers timings supplied by a plugin over the ones collected from the test run', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
new ReflectionClass(EnsureShardTimingsAreCollected::class)
|
||||
->getProperty('timings')
|
||||
->setValue(null, ['Tests\\Unit\\CollectedTest' => 9.0]);
|
||||
|
||||
Shard::useTimings(['Tests\\Unit\\SuppliedTest' => 1.5]);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('collectTimings');
|
||||
|
||||
expect($method->invoke($shard))->toBe(['Tests\\Unit\\SuppliedTest' => 1.5]);
|
||||
});
|
||||
|
||||
it('records known tests without supplied timings as zero', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$reflection = new ReflectionClass($shard);
|
||||
$reflection->getProperty('knownTests')->setValue(null, ['Tests\\Unit\\MutatedTest', 'Tests\\Unit\\PlainTest']);
|
||||
|
||||
Shard::useTimingsFile('shards-fixture.json');
|
||||
Shard::useTimings($timings = ['Tests\\Unit\\MutatedTest' => 4.5]);
|
||||
|
||||
$path = $reflection->getMethod('shardsPath')->invoke($shard);
|
||||
|
||||
try {
|
||||
$reflection->getMethod('writeTimings')->invoke($shard, $timings);
|
||||
|
||||
expect(json_decode((string) file_get_contents($path), true)['timings'])->toEqual([
|
||||
'Tests\\Unit\\MutatedTest' => 4.5,
|
||||
'Tests\\Unit\\PlainTest' => 0.0,
|
||||
]);
|
||||
} finally {
|
||||
@unlink($path);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps timings supplied by a plugin even when the test suite did not pass', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
new ReflectionClass($shard)->getProperty('updateShards')->setValue(null, true);
|
||||
|
||||
Shard::useTimingsFile('mutation-shards.json');
|
||||
Shard::useTimings(['Tests\\Unit\\SuppliedTest' => 1.5]);
|
||||
|
||||
$paratest = Arr::get($_SERVER, 'PARATEST');
|
||||
unset($_SERVER['PARATEST']);
|
||||
|
||||
try {
|
||||
expect($shard->addOutput(1))->toBe(1)
|
||||
->and($output->fetch())->toContain('mutation-shards.json updated with timings for 1 test class.');
|
||||
} finally {
|
||||
if ($paratest !== null) {
|
||||
$_SERVER['PARATEST'] = $paratest;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('strips coverage arguments when building the list-tests command', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
|
||||
|
||||
$command = $method->invoke($shard, ['bin/pest', '--coverage-php=/tmp/coverage.php', '--update-shards'], 'tests');
|
||||
|
||||
expect($command)->toBe([
|
||||
PHP_BINARY,
|
||||
'bin/pest',
|
||||
'--update-shards',
|
||||
'--test-directory=tests',
|
||||
'--list-tests',
|
||||
]);
|
||||
});
|
||||
|
||||
it('strips the separate path of a coverage argument when building the list-tests command', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
|
||||
|
||||
$command = $method->invoke($shard, ['bin/pest', '--coverage-php', '/tmp/coverage.php', '--update-shards'], 'tests');
|
||||
|
||||
expect($command)->toBe([
|
||||
PHP_BINARY,
|
||||
'bin/pest',
|
||||
'--update-shards',
|
||||
'--test-directory=tests',
|
||||
'--list-tests',
|
||||
]);
|
||||
});
|
||||
|
||||
it('strips the separate value of a coverage option when building the list-tests command', function (string $option): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
|
||||
|
||||
$command = $method->invoke($shard, ['bin/pest', $option, '/tmp/value', '--update-shards'], 'tests');
|
||||
|
||||
expect($command)->toBe([
|
||||
PHP_BINARY,
|
||||
'bin/pest',
|
||||
'--update-shards',
|
||||
'--test-directory=tests',
|
||||
'--list-tests',
|
||||
]);
|
||||
})->with(['--coverage-jsonl', '--coverage-filter', '--min', '--exactly']);
|
||||
|
||||
it('strips the separate value of the parallel processes option when building the list-tests command', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
|
||||
|
||||
$command = $method->invoke($shard, ['bin/pest', '--parallel', '--processes', '4', '--update-shards'], 'tests');
|
||||
|
||||
expect($command)->toBe([
|
||||
PHP_BINARY,
|
||||
'bin/pest',
|
||||
'--update-shards',
|
||||
'--test-directory=tests',
|
||||
'--list-tests',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps a unit saved with no test classes, but drops one emptied by removed classes', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('withoutRemovedTests');
|
||||
|
||||
$units = [
|
||||
'src/Explicit.php' => ['time' => 1.0, 'tests' => []],
|
||||
'src/Emptied.php' => ['time' => 2.0, 'tests' => ['Tests\\Unit\\RemovedTest']],
|
||||
];
|
||||
|
||||
expect($method->invoke($shard, $units, ['Tests\\Unit\\AliveTest']))->toBe([
|
||||
'src/Explicit.php' => ['time' => 1.0, 'tests' => []],
|
||||
]);
|
||||
});
|
||||
|
||||
it('drops test classes that no longer exist from the stored units', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('withoutRemovedTests');
|
||||
|
||||
$units = [
|
||||
'Tests\\Unit\\AliveTest' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\AliveTest']],
|
||||
'Tests\\Unit\\RemovedTest' => ['time' => 100.0, 'tests' => ['Tests\\Unit\\RemovedTest']],
|
||||
'src/Bundle.php' => ['time' => 2.0, 'tests' => ['Tests\\Unit\\AliveTest', 'Tests\\Unit\\RemovedTest']],
|
||||
];
|
||||
|
||||
expect($method->invoke($shard, $units, ['Tests\\Unit\\AliveTest']))->toBe([
|
||||
'Tests\\Unit\\AliveTest' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\AliveTest']],
|
||||
'src/Bundle.php' => ['time' => 2.0, 'tests' => ['Tests\\Unit\\AliveTest']],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('units', function (): void {
|
||||
afterEach(function (): void {
|
||||
$reflection = new ReflectionClass(Shard::class);
|
||||
$reflection->getProperty('timingsFilename')->setValue(null, null);
|
||||
$reflection->getProperty('externalTimings')->setValue(null, null);
|
||||
$reflection->getProperty('collectedTimings')->setValue(null, null);
|
||||
$reflection->getProperty('knownTests')->setValue(null, null);
|
||||
$reflection->getProperty('ownership')->setValue(null, null);
|
||||
$reflection->getProperty('shardsOutdated')->setValue(null, false);
|
||||
});
|
||||
|
||||
it('treats a bare timing as a unit bundling only its own test class', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('normaliseUnits');
|
||||
|
||||
expect($method->invoke($shard, ['Tests\\Unit\\FooTest' => 1.5]))->toBe([
|
||||
'Tests\\Unit\\FooTest' => ['time' => 1.5, 'tests' => ['Tests\\Unit\\FooTest']],
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps the test classes a unit bundles together in one shard', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('partitionByTime');
|
||||
|
||||
$partitions = $method->invoke($shard, [
|
||||
'app/Heavy.php' => ['time' => 10.0, 'tests' => ['Tests\\Unit\\OneTest', 'Tests\\Unit\\TwoTest']],
|
||||
'app/Light.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\ThreeTest']],
|
||||
'app/Medium.php' => ['time' => 4.0, 'tests' => ['Tests\\Unit\\FourTest']],
|
||||
], 2);
|
||||
|
||||
expect(array_keys($partitions[0]))->toBe(['app/Heavy.php'])
|
||||
->and(array_keys($partitions[1]))->toBe(['app/Medium.php', 'app/Light.php']);
|
||||
});
|
||||
|
||||
it('owns every unit when the run is not time-balanced', function (): void {
|
||||
expect(Shard::owns('app/Anything.php'))->toBeTrue();
|
||||
});
|
||||
|
||||
it('owns only the units allocated to the current shard', function (): void {
|
||||
new ReflectionClass(Shard::class)->getProperty('ownership')->setValue(null, [
|
||||
'app/Mine.php' => true,
|
||||
'app/Theirs.php' => false,
|
||||
]);
|
||||
|
||||
expect(Shard::owns('app/Mine.php'))->toBeTrue()
|
||||
->and(Shard::owns('app/Theirs.php'))->toBeFalse()
|
||||
->and(new ReflectionClass(Shard::class)->getProperty('shardsOutdated')->getValue())->toBeFalse();
|
||||
});
|
||||
|
||||
it('owns a unit the timings file does not know in every shard, and reports the file as out of date', function (): void {
|
||||
$reflection = new ReflectionClass(Shard::class);
|
||||
$reflection->getProperty('ownership')->setValue(null, ['app/Theirs.php' => false]);
|
||||
|
||||
expect(Shard::owns('app/New.php'))->toBeTrue()
|
||||
->and($reflection->getProperty('shardsOutdated')->getValue())->toBeTrue();
|
||||
});
|
||||
|
||||
it('keeps a unit that bundles no test class when writing', function (): void {
|
||||
$shard = new Shard(new BufferedOutput);
|
||||
|
||||
$reflection = new ReflectionClass($shard);
|
||||
$reflection->getProperty('knownTests')->setValue(null, ['Tests\\Unit\\FooTest']);
|
||||
|
||||
expect(array_keys($reflection->getMethod('unitsToWrite')->invoke($shard, [
|
||||
'app/Uncovered.php' => ['time' => 0.0, 'tests' => []],
|
||||
'app/Gone.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\GoneTest']],
|
||||
])))->toBe(['app/Uncovered.php', 'Tests\\Unit\\FooTest']);
|
||||
});
|
||||
|
||||
it('collects every test class the given units bundle', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$method = new ReflectionClass($shard)->getMethod('testsOf');
|
||||
|
||||
expect($method->invoke($shard, [
|
||||
'app/One.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\FooTest', 'Tests\\Unit\\BarTest']],
|
||||
'app/Two.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\BarTest']],
|
||||
]))->toBe(['Tests\\Unit\\FooTest', 'Tests\\Unit\\BarTest']);
|
||||
});
|
||||
|
||||
it('writes bundled units, and reads back both shapes', function (): void {
|
||||
$output = new BufferedOutput;
|
||||
$shard = new Shard($output);
|
||||
|
||||
$reflection = new ReflectionClass($shard);
|
||||
$reflection->getProperty('knownTests')->setValue(null, ['Tests\\Unit\\FooTest', 'Tests\\Unit\\BarTest']);
|
||||
|
||||
Shard::useTimingsFile('units-fixture.json');
|
||||
Shard::useTimings($units = [
|
||||
'app/One.php' => ['time' => 4.5, 'tests' => ['Tests\\Unit\\FooTest']],
|
||||
]);
|
||||
|
||||
$path = $reflection->getMethod('shardsPath')->invoke($shard);
|
||||
|
||||
try {
|
||||
$reflection->getMethod('writeTimings')->invoke($shard, $units);
|
||||
|
||||
expect(json_decode((string) file_get_contents($path), true))->toHaveKey('units')
|
||||
->and($reflection->getMethod('loadShardsFile')->invoke($shard))->toEqual([
|
||||
'app/One.php' => ['time' => 4.5, 'tests' => ['Tests\\Unit\\FooTest']],
|
||||
'Tests\\Unit\\BarTest' => ['time' => 0.0, 'tests' => ['Tests\\Unit\\BarTest']],
|
||||
]);
|
||||
} finally {
|
||||
@unlink($path);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Parallel;
|
||||
use Pest\Plugins\Tia\ByteSafeJson;
|
||||
|
||||
it('round-trips keys and values that are not valid UTF-8', function (): void {
|
||||
$value = [
|
||||
"app/caf\xe9.php" => ["tests/caf\xe9Test.php", 'tests/PlainTest.php'],
|
||||
'plain' => "message \xff\xfe",
|
||||
'count' => 3,
|
||||
'list' => [1, 2.5, true, null],
|
||||
];
|
||||
|
||||
expect(ByteSafeJson::decode(ByteSafeJson::encode($value)))->toBe($value);
|
||||
});
|
||||
|
||||
it('keeps valid UTF-8 as plain JSON', function (): void {
|
||||
expect(ByteSafeJson::encode(['app/café.php' => ['tests/a/b.php']]))
|
||||
->toBe('{"app/caf\\u00e9.php":["tests/a/b.php"]}');
|
||||
});
|
||||
|
||||
it('does not confuse a real string with an escaped one', function (): void {
|
||||
$lookalike = "\0base64:".base64_encode("caf\xe9");
|
||||
$value = [$lookalike => $lookalike, "caf\xe9" => "caf\xe9"];
|
||||
|
||||
expect(ByteSafeJson::decode(ByteSafeJson::encode($value)))->toBe($value);
|
||||
});
|
||||
|
||||
it('leaves a malformed escape untouched', function (): void {
|
||||
expect(ByteSafeJson::decode('["\u0000base64:!!"]'))->toBe(["\0base64:!!"]);
|
||||
});
|
||||
|
||||
it('returns null for invalid JSON', function (): void {
|
||||
expect(ByteSafeJson::decode('{'))->toBeNull();
|
||||
});
|
||||
|
||||
it('throws with the reason when a value cannot be encoded', function (): void {
|
||||
ByteSafeJson::encode(['time' => INF]);
|
||||
})->throws(JsonException::class, 'Inf and NaN cannot be JSON encoded');
|
||||
|
||||
it('carries a string that is not valid UTF-8 through a parallel global', function (): void {
|
||||
Parallel::setGlobal('BYTE_SAFE_JSON_TEST', ByteSafeJson::encode("feature/caf\xe9"));
|
||||
|
||||
try {
|
||||
expect(ByteSafeJson::decode((string) Parallel::getGlobal('BYTE_SAFE_JSON_TEST')))->toBe("feature/caf\xe9");
|
||||
} finally {
|
||||
unset($_ENV['PEST_PARALLEL_GLOBAL_BYTE_SAFE_JSON_TEST']);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,444 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\ChangedFiles;
|
||||
use Pest\Plugins\Tia\ExternalSources;
|
||||
use Pest\Plugins\Tia\Fingerprint;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Tests\Fixtures\Tia\GitRepo;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
function tiaMonorepoRoots(?string $created = null): array
|
||||
{
|
||||
static $roots = [];
|
||||
|
||||
if ($created !== null) {
|
||||
$roots[] = $created;
|
||||
|
||||
return $roots;
|
||||
}
|
||||
|
||||
$all = $roots;
|
||||
$roots = [];
|
||||
|
||||
return $all;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{root: string, project: string, repo: GitRepo, sha: string}
|
||||
*/
|
||||
function tiaMonorepoRepository(): array
|
||||
{
|
||||
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-monorepo-'.bin2hex(random_bytes(8));
|
||||
|
||||
mkdir($root.'/backend/app', 0755, true);
|
||||
mkdir($root.'/frontend', 0755, true);
|
||||
|
||||
file_put_contents($root.'/backend/app/Service.php', "<?php\n\$service = 1;\n");
|
||||
file_put_contents($root.'/frontend/widget.php', "<?php\n\$widget = 1;\n");
|
||||
|
||||
tiaMonorepoRoots($root);
|
||||
|
||||
$repo = new GitRepo($root);
|
||||
$repo->init('master');
|
||||
|
||||
return ['root' => $root, 'project' => $root.'/backend', 'repo' => $repo, 'sha' => $repo->sha()];
|
||||
}
|
||||
|
||||
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 {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
expect(new ChangedFiles($monorepo['project'])->gitPrefix())->toBe('backend/')
|
||||
->and(new ChangedFiles($monorepo['root'])->gitPrefix())->toBeEmpty();
|
||||
})->skipOnWindows();
|
||||
|
||||
it('keeps a space that begins the name of the project directory', function (): void {
|
||||
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-monorepo-'.bin2hex(random_bytes(8));
|
||||
|
||||
mkdir($root.'/ backend/app', 0755, true);
|
||||
file_put_contents($root.'/ backend/app/Service.php', "<?php\n\$service = 1;\n");
|
||||
|
||||
tiaMonorepoRoots($root);
|
||||
|
||||
$repo = new GitRepo($root);
|
||||
$repo->init('master');
|
||||
|
||||
file_put_contents($root.'/ backend/app/Service.php', "<?php\n\$service = 2;\n");
|
||||
|
||||
$project = new ChangedFiles($root.'/ backend');
|
||||
|
||||
expect($project->gitPrefix())->toBe(' backend/')
|
||||
->and($project->since($repo->sha()))->toBe(['app/Service.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('keeps the character that ends the name of the repository root', function (string $lastCharacter): void {
|
||||
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-monorepo-'.bin2hex(random_bytes(8)).$lastCharacter;
|
||||
|
||||
mkdir($root.'/backend/app', 0755, true);
|
||||
mkdir($root.'/frontend', 0755, true);
|
||||
file_put_contents($root.'/backend/app/Service.php', "<?php\n\$service = 1;\n");
|
||||
file_put_contents($root.'/frontend/widget.php', "<?php\n\$widget = 1;\n");
|
||||
|
||||
tiaMonorepoRoots($root);
|
||||
|
||||
$repo = new GitRepo($root);
|
||||
$repo->init('master');
|
||||
|
||||
file_put_contents($root.'/backend/app/Service.php', "<?php\n\$service = 2;\n");
|
||||
file_put_contents($root.'/frontend/widget.php', "<?php\n\$widget = 2;\n");
|
||||
|
||||
$project = new ChangedFiles($root.'/backend');
|
||||
|
||||
expect($project->since($repo->sha()))->toBe(['app/Service.php'])
|
||||
->and($project->outsideProject())->toBe(['frontend/widget.php']);
|
||||
})->with(['a space' => ' ', 'a carriage return' => "\r"])->skipOnWindows();
|
||||
|
||||
it('reports working tree changes relative to the project, dropping siblings', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['project'].'/app/Service.php', "<?php\n\$service = 2;\n");
|
||||
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
|
||||
|
||||
expect(new ChangedFiles($monorepo['project'])->since($monorepo['sha']))
|
||||
->toBe(['app/Service.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reports committed changes relative to the project, dropping siblings', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['project'].'/app/Service.php', "<?php\n\$service = 2;\n");
|
||||
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
|
||||
|
||||
$monorepo['repo']->commit('Second commit');
|
||||
|
||||
expect(new ChangedFiles($monorepo['project'])->since($monorepo['sha']))
|
||||
->toBe(['app/Service.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('drops a file whose content came back to its baseline across the prefix boundary', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['project'].'/app/Service.php', "<?php\n\$service = 2;\n");
|
||||
$monorepo['repo']->commit('Change the service');
|
||||
|
||||
file_put_contents($monorepo['project'].'/app/Service.php', "<?php\n\$service = 1;\n");
|
||||
$monorepo['repo']->commit('Put the service back');
|
||||
|
||||
expect(new ChangedFiles($monorepo['project'])->since($monorepo['sha']))->toBe([]);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('honours a gitignore inside the project', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['project'].'/.gitignore', "/ignored.php\n");
|
||||
file_put_contents($monorepo['project'].'/ignored.php', "<?php\n");
|
||||
file_put_contents($monorepo['project'].'/app/Service.php', "<?php\n\$service = 2;\n");
|
||||
|
||||
expect(new ChangedFiles($monorepo['project'])->since($monorepo['sha']))
|
||||
->toContain('app/Service.php')
|
||||
->not->toContain('ignored.php');
|
||||
})->skipOnWindows();
|
||||
|
||||
it('leaves a project at the repository root untouched', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
|
||||
|
||||
expect(new ChangedFiles($monorepo['root'])->since($monorepo['sha']))
|
||||
->toBe(['frontend/widget.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reports the changes it left outside the project', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['project'].'/app/Service.php', "<?php\n\$service = 2;\n");
|
||||
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
$changedFiles->since($monorepo['sha']);
|
||||
|
||||
expect($changedFiles->outsideProject())->toBe(['frontend/widget.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reports nothing outside the project for a project at the repository root', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['root']);
|
||||
$changedFiles->since($monorepo['sha']);
|
||||
|
||||
expect($changedFiles->outsideProject())->toBeEmpty();
|
||||
})->skipOnWindows();
|
||||
|
||||
it('ties a fingerprint to the project location inside the repository', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
mkdir($monorepo['root'].'/admin/app', 0755, true);
|
||||
file_put_contents($monorepo['root'].'/admin/app/Service.php', "<?php\n\$service = 1;\n");
|
||||
$monorepo['repo']->commit('add a second project');
|
||||
|
||||
$nested = Fingerprint::compute($monorepo['project']);
|
||||
$sibling = Fingerprint::compute($monorepo['root'].'/admin');
|
||||
$root = Fingerprint::compute($monorepo['root']);
|
||||
|
||||
expect($nested['structural']['project_prefix'])->toBe('backend/')
|
||||
->and($sibling['structural']['project_prefix'])->toBe('admin/')
|
||||
->and($root['structural'])->not->toHaveKey('project_prefix')
|
||||
->and(Fingerprint::structuralMatches($nested, $sibling))->toBeFalse()
|
||||
->and(Fingerprint::structuralMatches($nested, $root))->toBeFalse()
|
||||
->and(Fingerprint::structuralDrift($sibling, $nested))->toContain('project_prefix');
|
||||
})->skipOnWindows();
|
||||
|
||||
it('sees a committed non-ascii path that git would otherwise quote', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
mkdir($monorepo['project'].'/resources/views', 0755, true);
|
||||
file_put_contents($monorepo['project'].'/resources/views/\u{26a1}orders.blade.php', "<div>a</div>\n");
|
||||
$monorepo['repo']->commit('add a lightning view');
|
||||
|
||||
$sha = $monorepo['repo']->sha();
|
||||
|
||||
file_put_contents($monorepo['project'].'/resources/views/\u{26a1}orders.blade.php', "<div>b</div>\n");
|
||||
$monorepo['repo']->commit('reword the lightning view');
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
|
||||
expect($changedFiles->since($sha))->toBe(['resources/views/\u{26a1}orders.blade.php'])
|
||||
->and($changedFiles->outsideProject())->toBeEmpty();
|
||||
})->skipOnWindows();
|
||||
|
||||
it('sees a committed non-ascii path at the repository root too', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/\u{26a1}widget.php', "<?php\n\$widget = 1;\n");
|
||||
$monorepo['repo']->commit('add a lightning widget');
|
||||
|
||||
$sha = $monorepo['repo']->sha();
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/\u{26a1}widget.php', "<?php\n\$widget = 2;\n");
|
||||
$monorepo['repo']->commit('rework the lightning widget');
|
||||
|
||||
expect(new ChangedFiles($monorepo['root'])->since($sha))
|
||||
->toBe(['frontend/\u{26a1}widget.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('keeps a tracked outside change and drops an untracked ignored one', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/.gitignore', "dist/\n");
|
||||
mkdir($monorepo['root'].'/frontend/dist', 0755, true);
|
||||
file_put_contents($monorepo['root'].'/frontend/dist/bundle.js', "var a = 1;\n");
|
||||
$monorepo['repo']->run(['add', '-f', 'frontend/dist/bundle.js']);
|
||||
$monorepo['repo']->commit('track a built bundle that the ignore rules match');
|
||||
|
||||
$sha = $monorepo['repo']->sha();
|
||||
|
||||
file_put_contents($monorepo['root'].'/frontend/dist/bundle.js', "var a = 2;\n");
|
||||
file_put_contents($monorepo['root'].'/frontend/dist/untracked.js', "var b = 1;\n");
|
||||
$monorepo['repo']->commit('rebuild the bundle');
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
$changedFiles->since($sha);
|
||||
|
||||
expect($changedFiles->outsideProject())->toBe(['frontend/dist/bundle.js']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('keeps a tracked project change that the ignore rules match', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
file_put_contents($monorepo['root'].'/.gitignore', "build/\n");
|
||||
mkdir($monorepo['project'].'/build', 0755, true);
|
||||
file_put_contents($monorepo['project'].'/build/Generated.php', "<?php\n\$built = 1;\n");
|
||||
$monorepo['repo']->run(['add', '-f', 'backend/build/Generated.php']);
|
||||
$monorepo['repo']->commit('track a generated file that the ignore rules match');
|
||||
|
||||
$sha = $monorepo['repo']->sha();
|
||||
|
||||
file_put_contents($monorepo['project'].'/build/Generated.php', "<?php\n\$built = 2;\n");
|
||||
file_put_contents($monorepo['project'].'/build/Untracked.php', "<?php\n");
|
||||
$monorepo['repo']->commit('regenerate the file');
|
||||
|
||||
expect(new ChangedFiles($monorepo['project'])->since($sha))
|
||||
->toBe(['build/Generated.php']);
|
||||
})->skipOnWindows();
|
||||
|
||||
it('reads committed paths from the repository root even when git is told to be relative', function (): void {
|
||||
$monorepo = tiaMonorepoRepository();
|
||||
|
||||
$monorepo['repo']->run(['config', 'diff.relative', 'true']);
|
||||
|
||||
file_put_contents($monorepo['project'].'/app/Service.php', "<?php\n\$service = 2;\n");
|
||||
file_put_contents($monorepo['root'].'/frontend/widget.php', "<?php\n\$widget = 2;\n");
|
||||
$monorepo['repo']->commit('rework both sides');
|
||||
|
||||
$changedFiles = new ChangedFiles($monorepo['project']);
|
||||
|
||||
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']);
|
||||
});
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Configuration;
|
||||
use Pest\Plugins\Tia\ConfigurationFile;
|
||||
|
||||
beforeEach(function (): void {
|
||||
$this->projectRoot = sys_get_temp_dir().'/pest-tia-configuration-'.bin2hex(random_bytes(4));
|
||||
mkdir($this->projectRoot, 0755, true);
|
||||
mkdir($this->projectRoot.'/lib', 0755, true);
|
||||
|
||||
$contents = "<?xml version=\"1.0\"?>\n<phpunit/>\n";
|
||||
file_put_contents($this->projectRoot.'/phpunit.xml', $contents);
|
||||
@@ -14,8 +15,13 @@ beforeEach(function (): void {
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
@unlink($this->projectRoot.'/phpunit.xml');
|
||||
@unlink($this->projectRoot.'/phpunit.copy.xml');
|
||||
foreach (['phpunit.xml', 'phpunit.copy.xml'] as $file) {
|
||||
if (is_file($this->projectRoot.'/'.$file)) {
|
||||
unlink($this->projectRoot.'/'.$file);
|
||||
}
|
||||
}
|
||||
|
||||
@rmdir($this->projectRoot.'/lib');
|
||||
@rmdir($this->projectRoot);
|
||||
});
|
||||
|
||||
@@ -40,3 +46,172 @@ it('gives a run with --no-configuration its own fingerprint', function (): void
|
||||
->toBe('none')
|
||||
->not->toBe(ConfigurationFile::projectDefault()->fingerprint($this->projectRoot));
|
||||
});
|
||||
|
||||
it('fingerprints the configuration Pest generates the way the Xdebug restarter does', function (array $leftovers): void {
|
||||
unlink($this->projectRoot.'/phpunit.xml');
|
||||
|
||||
foreach ($leftovers as $leftover) {
|
||||
file_put_contents($this->projectRoot.'/'.$leftover, '');
|
||||
}
|
||||
|
||||
$workingDirectory = (string) getcwd();
|
||||
chdir($this->projectRoot);
|
||||
$configuration = new Configuration;
|
||||
|
||||
try {
|
||||
$arguments = $configuration->handleArguments(['pest', '--tia']);
|
||||
$generatedPath = $configuration->generatedConfigurationPath();
|
||||
|
||||
expect($generatedPath)->toBeString()
|
||||
->and(basename((string) $generatedPath))->not->toBeIn($leftovers)
|
||||
->and(ConfigurationFile::fromArguments($arguments, $generatedPath)->fingerprint($this->projectRoot))
|
||||
->toBeNull()
|
||||
->toBe(ConfigurationFile::fromArguments(['pest', '--tia'])->fingerprint($this->projectRoot));
|
||||
} finally {
|
||||
$configuration->terminate();
|
||||
chdir($workingDirectory);
|
||||
|
||||
foreach ($leftovers as $leftover) {
|
||||
unlink($this->projectRoot.'/'.$leftover);
|
||||
}
|
||||
}
|
||||
})->with([
|
||||
'first name' => [[]],
|
||||
'fallback name' => [['.pest.xml']],
|
||||
'random name' => [['.pest.xml', '.pest-fallback.xml']],
|
||||
]);
|
||||
|
||||
it('fingerprints an explicit configuration apart from the one Pest generates', function (): void {
|
||||
$generatedPath = $this->projectRoot.'/.pest.xml';
|
||||
file_put_contents($generatedPath, '');
|
||||
|
||||
try {
|
||||
expect(ConfigurationFile::fromArguments(['-c'.$this->projectRoot.'/phpunit.copy.xml'], $generatedPath)->fingerprint($this->projectRoot))
|
||||
->toBe(ConfigurationFile::at($this->projectRoot.'/phpunit.copy.xml')->fingerprint($this->projectRoot))
|
||||
->not->toBe(ConfigurationFile::fromArguments(['--configuration', $generatedPath], $generatedPath)->fingerprint($this->projectRoot));
|
||||
} finally {
|
||||
unlink($generatedPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the bootstrap and the include path the command line sets with the configuration Pest generates', function (): void {
|
||||
$generatedPath = $this->projectRoot.'/.pest.xml';
|
||||
file_put_contents($generatedPath, '');
|
||||
|
||||
$workingDirectory = (string) getcwd();
|
||||
chdir($this->projectRoot);
|
||||
|
||||
try {
|
||||
$configuration = ConfigurationFile::fromArguments(['--configuration', $generatedPath, '--bootstrap', 'phpunit.copy.xml', '--include-path', 'lib'], $generatedPath);
|
||||
|
||||
expect($configuration->fingerprint($this->projectRoot))->toBe(ConfigurationFile::projectDefault()->fingerprint($this->projectRoot))
|
||||
->and($configuration->bootstrapFingerprint($this->projectRoot))->toBe('phpunit.copy.xml')
|
||||
->and($configuration->includePathFingerprint($this->projectRoot))->toBe('lib');
|
||||
} finally {
|
||||
chdir($workingDirectory);
|
||||
unlink($generatedPath);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the fingerprint of a run that sets no bootstrap and no include path', function (): void {
|
||||
$configuration = ConfigurationFile::fromArguments(['--tia', '--parallel', '--configuration', $this->projectRoot.'/phpunit.xml']);
|
||||
|
||||
expect($configuration->fingerprint($this->projectRoot))
|
||||
->toBe(ConfigurationFile::at($this->projectRoot.'/phpunit.xml')->fingerprint($this->projectRoot))
|
||||
->and($configuration->bootstrapFingerprint($this->projectRoot))->toBeNull()
|
||||
->and($configuration->includePathFingerprint($this->projectRoot))->toBeNull();
|
||||
});
|
||||
|
||||
it('fingerprints the bootstrap the command line sets relative to the project', function (array $bootstrap): void {
|
||||
$configuration = ConfigurationFile::fromArguments(['--tia', '--configuration', $this->projectRoot.'/phpunit.xml', ...$bootstrap]);
|
||||
|
||||
expect($configuration->bootstrapFingerprint($this->projectRoot))->toBe('phpunit.copy.xml')
|
||||
->and($configuration->fingerprint($this->projectRoot))->toBe(ConfigurationFile::at($this->projectRoot.'/phpunit.xml')->fingerprint($this->projectRoot));
|
||||
})->with([
|
||||
'separate value' => fn (): array => ['--bootstrap', $this->projectRoot.'/phpunit.copy.xml'],
|
||||
'equals form' => fn (): array => ['--bootstrap='.$this->projectRoot.'/phpunit.copy.xml'],
|
||||
]);
|
||||
|
||||
it('tells two bootstraps apart', function (): void {
|
||||
$configuration = ['--configuration', $this->projectRoot.'/phpunit.xml'];
|
||||
|
||||
expect(ConfigurationFile::fromArguments([...$configuration, '--bootstrap', 'one.php'])->bootstrapFingerprint($this->projectRoot))
|
||||
->not->toBe(ConfigurationFile::fromArguments([...$configuration, '--bootstrap', 'two.php'])->bootstrapFingerprint($this->projectRoot));
|
||||
});
|
||||
|
||||
it('tells a bootstrap with a backslash in its name apart from a bootstrap in a directory', function (): void {
|
||||
$configuration = ['--configuration', $this->projectRoot.'/phpunit.xml'];
|
||||
|
||||
expect(ConfigurationFile::fromArguments([...$configuration, '--bootstrap', 'tests\\Boot.php'])->bootstrapFingerprint($this->projectRoot))
|
||||
->toBe('tests\\Boot.php')
|
||||
->not->toBe(ConfigurationFile::fromArguments([...$configuration, '--bootstrap', 'tests/Boot.php'])->bootstrapFingerprint($this->projectRoot));
|
||||
})->skipOnWindows();
|
||||
|
||||
it('fingerprints each include path the command line sets relative to the project', function (): void {
|
||||
$includePath = $this->projectRoot.'/lib'.PATH_SEPARATOR.'/elsewhere';
|
||||
|
||||
expect(ConfigurationFile::fromArguments(['--configuration', $this->projectRoot.'/phpunit.xml', '--include-path', $includePath])->includePathFingerprint($this->projectRoot))
|
||||
->toBe("lib\0/elsewhere");
|
||||
});
|
||||
|
||||
it('fingerprints the bootstrap of a run with --no-configuration', function (): void {
|
||||
$configuration = ConfigurationFile::fromArguments(['--no-configuration', '--bootstrap', 'boot.php']);
|
||||
|
||||
expect($configuration->fingerprint($this->projectRoot))->toBe('none')
|
||||
->and($configuration->bootstrapFingerprint($this->projectRoot))->toBe('boot.php');
|
||||
});
|
||||
|
||||
it('fingerprints an include path equal to the project root as the project root', function (): void {
|
||||
$includePath = $this->projectRoot.PATH_SEPARATOR.$this->projectRoot.'/lib';
|
||||
|
||||
expect(ConfigurationFile::fromArguments(['--configuration', $this->projectRoot.'/phpunit.xml', '--include-path', $includePath])->includePathFingerprint($this->projectRoot))
|
||||
->toBe(".\0lib");
|
||||
});
|
||||
|
||||
it('keeps an empty include path entry empty', function (): void {
|
||||
expect(ConfigurationFile::fromArguments(['--configuration', $this->projectRoot.'/phpunit.xml', '--include-path', PATH_SEPARATOR.'lib'])->includePathFingerprint($this->projectRoot))
|
||||
->toBe("\0lib");
|
||||
});
|
||||
|
||||
it('keeps the fingerprint of a relative bootstrap when the working directory changes during the run', function (): void {
|
||||
$workingDirectory = (string) getcwd();
|
||||
chdir($this->projectRoot);
|
||||
|
||||
try {
|
||||
$configuration = ConfigurationFile::fromArguments(['--configuration', 'phpunit.xml', '--bootstrap', './phpunit.copy.xml', '--include-path', './lib']);
|
||||
|
||||
chdir($this->projectRoot.'/lib');
|
||||
|
||||
expect($configuration->bootstrapFingerprint($this->projectRoot))->toBe('phpunit.copy.xml')
|
||||
->and($configuration->includePathFingerprint($this->projectRoot))->toBe('lib');
|
||||
} finally {
|
||||
chdir($workingDirectory);
|
||||
}
|
||||
});
|
||||
|
||||
it('tells an include path through a symlink to a directory with a separator in its name apart from two include paths', function (): void {
|
||||
$directories = ['lib-a', 'lib-b', 'lib-a'.PATH_SEPARATOR.'lib-b'];
|
||||
|
||||
foreach ($directories as $directory) {
|
||||
mkdir($this->projectRoot.'/'.$directory);
|
||||
}
|
||||
|
||||
symlink($this->projectRoot.'/lib-a'.PATH_SEPARATOR.'lib-b', $this->projectRoot.'/alias');
|
||||
|
||||
$workingDirectory = (string) getcwd();
|
||||
chdir($this->projectRoot);
|
||||
|
||||
try {
|
||||
$configuration = ['--configuration', 'phpunit.xml'];
|
||||
|
||||
expect(ConfigurationFile::fromArguments([...$configuration, '--include-path', 'alias'])->includePathFingerprint($this->projectRoot))
|
||||
->not->toBe(ConfigurationFile::fromArguments([...$configuration, '--include-path', 'lib-a'.PATH_SEPARATOR.'lib-b'])->includePathFingerprint($this->projectRoot));
|
||||
} finally {
|
||||
chdir($workingDirectory);
|
||||
unlink($this->projectRoot.'/alias');
|
||||
|
||||
foreach ($directories as $directory) {
|
||||
rmdir($this->projectRoot.'/'.$directory);
|
||||
}
|
||||
}
|
||||
})->skipOnWindows();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,8 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\ConfigurationFile;
|
||||
use Pest\Plugins\Tia\ExternalSources;
|
||||
use Pest\Plugins\Tia\Fingerprint;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
@@ -106,4 +108,86 @@ 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();
|
||||
|
||||
try {
|
||||
$structural = Fingerprint::compute($root, ConfigurationFile::fromArguments(['--tia']))['structural'];
|
||||
|
||||
expect($structural)->not->toHaveKey('phpunit_bootstrap')
|
||||
->and($structural)->not->toHaveKey('phpunit_include_path');
|
||||
} finally {
|
||||
fingerprintRemoveDirectory($root);
|
||||
}
|
||||
});
|
||||
|
||||
it('tells a bootstrap whose name looks like an include path apart from a bootstrap and an include path', function (): void {
|
||||
$root = fingerprintRepository();
|
||||
|
||||
try {
|
||||
$bootstrapOnly = Fingerprint::compute($root, ConfigurationFile::fromArguments(['--bootstrap', 'bootstrap.php;include-path=app']));
|
||||
$bootstrapAndIncludePath = Fingerprint::compute($root, ConfigurationFile::fromArguments(['--bootstrap', 'bootstrap.php', '--include-path', 'app']));
|
||||
|
||||
expect(Fingerprint::structuralMatches($bootstrapOnly, $bootstrapAndIncludePath))->toBeFalse()
|
||||
->and(Fingerprint::structuralDrift($bootstrapOnly, $bootstrapAndIncludePath))->toBe(['phpunit_bootstrap', 'phpunit_include_path']);
|
||||
} finally {
|
||||
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);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -409,3 +409,80 @@ describe('branch baseline over the fallback', function (): void {
|
||||
->and($graph->getTime('feature', 'Tests\BarTest::it passes', 'main'))->toBe(0.5);
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
$graph = new Graph($root);
|
||||
$graph->link("tests/caf\xe9Test.php", "app/caf\xe9.php");
|
||||
$graph->setLastRunTree('master', ["caf\xe9.txt" => 'hash']);
|
||||
$graph->setResult('master', "P\\Tests\\caf\xe9Test::__pest_evaluable_it_works", 0, "caf\xe9", 0.1, 1, "tests/caf\xe9Test.php");
|
||||
|
||||
$decoded = Graph::decode($graph->encode(), $root);
|
||||
|
||||
expect($decoded)->toBeInstanceOf(Graph::class)
|
||||
->and($decoded->affected(["app/caf\xe9.php"]))->toBe(["tests/caf\xe9Test.php"])
|
||||
->and($decoded->lastRunTree('master'))->toBe(["caf\xe9.txt" => 'hash'])
|
||||
->and($decoded->getAssertions('master', "P\\Tests\\caf\xe9Test::__pest_evaluable_it_works"))->toBe(1)
|
||||
->and($decoded->testFilesToRerun('master'))->toBeEmpty();
|
||||
});
|
||||
|
||||
it('lists a branch whose name is not valid UTF-8', function (): void {
|
||||
$graph = new Graph(sys_get_temp_dir());
|
||||
$graph->setRecordedAtSha("feature/caf\xe9", 'abc');
|
||||
|
||||
expect(Graph::branchesIn($graph->encode()))->toBe(["feature/caf\xe9"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('legacy schema', function (): void {
|
||||
it('reads a graph of the previous schema without unescaping its strings', function (): void {
|
||||
$root = sys_get_temp_dir();
|
||||
$id = 'P\\Tests\\FooTest::__pest_evaluable_it_skips';
|
||||
$legacy = json_encode([
|
||||
'schema' => 1,
|
||||
'baselines' => ['master' => [
|
||||
'sha' => null,
|
||||
'tree' => [],
|
||||
'results' => [$id => ['status' => 1, 'message' => "\0base64:b2xk", 'time' => 0.1]],
|
||||
]],
|
||||
], JSON_UNESCAPED_SLASHES);
|
||||
|
||||
$graph = Graph::decode((string) $legacy, $root);
|
||||
|
||||
expect($graph)->toBeInstanceOf(Graph::class)
|
||||
->and($graph->getResult('master', $id)?->message())->toBe("\0base64:b2xk")
|
||||
->and(Graph::decode($graph->encode(), $root)?->getResult('master', $id)?->message())->toBe("\0base64:b2xk");
|
||||
});
|
||||
|
||||
it('rebuilds a graph of an unknown schema but still lists its branches', function (): void {
|
||||
expect(Graph::decode('{"schema":99}', sys_get_temp_dir()))->toBeNull()
|
||||
->and(Graph::branchesIn('{"schema":99,"baselines":{"master":{}}}'))->toBe(['master']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
@@ -2,8 +2,12 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\Configuration;
|
||||
use Pest\Plugins\Tia\ReadCapture;
|
||||
use Pest\Plugins\Tia\Recorder;
|
||||
use Pest\Plugins\Tia\WatchPatterns;
|
||||
use Pest\Support\Container;
|
||||
use Tests\Fixtures\Tia\CallForwardingFileWrapper;
|
||||
use Tests\Fixtures\Tia\LoggingFileWrapper;
|
||||
|
||||
/**
|
||||
@@ -202,6 +206,145 @@ describe('the file wrapper', function (): void {
|
||||
}
|
||||
});
|
||||
|
||||
it('reports a missing path to the error handler 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));
|
||||
$warnings = [];
|
||||
$results = [];
|
||||
|
||||
set_error_handler(function (int $level, string $message) use (&$warnings): bool {
|
||||
$warnings[] = $message;
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
try {
|
||||
tiaReadCaptureLinks(function () use ($missing, &$warnings, &$results): void {
|
||||
clearstatcache();
|
||||
|
||||
$results['quiet'] = [file_exists($missing), is_file($missing), is_dir($missing), is_link($missing)];
|
||||
$results['warnings after quiet probes'] = count($warnings);
|
||||
|
||||
$results['stat'] = stat($missing);
|
||||
$results['warnings after stat'] = count($warnings);
|
||||
});
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
|
||||
expect($results)->toBe([
|
||||
'quiet' => [false, false, false, false],
|
||||
'warnings after quiet probes' => 0,
|
||||
'stat' => false,
|
||||
'warnings after stat' => 1,
|
||||
]);
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
tiaReadCaptureLinks(function () use (&$growth): void {
|
||||
fclose(fopen(__FILE__, 'rb'));
|
||||
|
||||
$before = memory_get_usage();
|
||||
|
||||
for ($i = 0; $i < 10_000; $i++) {
|
||||
fclose(fopen(__FILE__, 'rb'));
|
||||
}
|
||||
|
||||
$growth = memory_get_usage() - $before;
|
||||
});
|
||||
|
||||
expect($growth)->toBeLessThan(100_000);
|
||||
});
|
||||
|
||||
it('keeps no memory for each test it records', function (): void {
|
||||
tiaReadCaptureLinks(fn (): bool => true);
|
||||
|
||||
$before = memory_get_usage();
|
||||
|
||||
for ($i = 0; $i < 5_000; $i++) {
|
||||
tiaReadCaptureLinks(fn (): bool => true);
|
||||
}
|
||||
|
||||
expect(memory_get_usage() - $before)->toBeLessThan(100_000);
|
||||
});
|
||||
|
||||
it('is restored quietly when the test already restored it', function (): void {
|
||||
$errors = [];
|
||||
|
||||
set_error_handler(function (int $level, string $message) use (&$errors): bool {
|
||||
$errors[] = $message;
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
try {
|
||||
tiaReadCaptureLinks(fn (): bool => stream_wrapper_restore('file'));
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
|
||||
expect($errors)->toBeEmpty()
|
||||
->and(tiaReadCaptureWrapperType())->toBe('plainfile');
|
||||
});
|
||||
|
||||
it('is restored quietly when the test unregistered it', function (): void {
|
||||
$errors = [];
|
||||
|
||||
set_error_handler(function (int $level, string $message) use (&$errors): bool {
|
||||
$errors[] = $message;
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
try {
|
||||
tiaReadCaptureLinks(fn (): bool => stream_wrapper_unregister('file'));
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
|
||||
if (! in_array('file', stream_get_wrappers(), true)) {
|
||||
stream_wrapper_restore('file');
|
||||
}
|
||||
}
|
||||
|
||||
expect($errors)->toBeEmpty()
|
||||
->and(tiaReadCaptureWrapperType())->toBe('plainfile');
|
||||
});
|
||||
|
||||
it('reports symlinks as links while a test records', function (bool $targetExists, bool $expectedExists): void {
|
||||
$directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-read-capture-'.bin2hex(random_bytes(8));
|
||||
mkdir($directory);
|
||||
@@ -294,3 +437,134 @@ describe('a wrapper already registered for file://', function (): void {
|
||||
->and(tiaReadCaptureWrapperClass())->toBe(LoggingFileWrapper::class);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a __call wrapper already registered for file://', function (): void {
|
||||
beforeEach(function (): void {
|
||||
CallForwardingFileWrapper::enable();
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
CallForwardingFileWrapper::disable();
|
||||
});
|
||||
|
||||
it('passes reads, includes and directory listings through it', function (): void {
|
||||
$source = (string) realpath(dirname(__DIR__, 4).'/src/Plugins/Tia/ReadCapture.php');
|
||||
$path = __DIR__.'/read-capture-'.bin2hex(random_bytes(8)).'.php';
|
||||
file_put_contents($path, "<?php\n\nreturn 1;\n");
|
||||
|
||||
$results = [];
|
||||
|
||||
try {
|
||||
$links = tiaReadCaptureLinks(function () use ($source, $path, &$results): void {
|
||||
$results['read'] = file_get_contents($source) !== '';
|
||||
$results['include'] = require $path;
|
||||
$results['scandir'] = in_array(basename($path), (array) scandir(__DIR__), true);
|
||||
});
|
||||
} finally {
|
||||
@unlink($path);
|
||||
}
|
||||
|
||||
expect($results)->toBe([
|
||||
'read' => true,
|
||||
'include' => 1,
|
||||
'scandir' => true,
|
||||
])->and($links)->toBe([$source]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('withoutReadCapture()', function (): void {
|
||||
beforeEach(function (): void {
|
||||
Container::getInstance()->add(WatchPatterns::class, new WatchPatterns);
|
||||
|
||||
$this->excluded = (string) realpath(dirname(__DIR__, 4).'/src/Plugins/Tia/ReadCapture.php');
|
||||
$this->kept = (string) realpath(dirname(__DIR__, 4).'/src/Plugins/Tia/Recorder.php');
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
Container::getInstance()->add(WatchPatterns::class, new WatchPatterns);
|
||||
});
|
||||
|
||||
it('does not link a file matching an excluded glob', function (): void {
|
||||
(new Configuration)->withoutReadCapture(['src/Plugins/Tia/Read*.php']);
|
||||
|
||||
expect(tiaReadCaptureLinks(fn (): string|false => file_get_contents($this->excluded)))->toBeEmpty();
|
||||
});
|
||||
|
||||
it('still links a file outside the excluded globs', function (): void {
|
||||
(new Configuration)->withoutReadCapture(['src/Plugins/Tia/Read*.php']);
|
||||
|
||||
$links = tiaReadCaptureLinks(function (): void {
|
||||
file_get_contents($this->excluded);
|
||||
file_get_contents($this->kept);
|
||||
});
|
||||
|
||||
expect($links)->toBe([$this->kept]);
|
||||
});
|
||||
|
||||
it('keeps the file wrapper registered while globs are excluded', function (): void {
|
||||
(new Configuration)->withoutReadCapture(['src/Plugins/Tia/Read*.php']);
|
||||
|
||||
$during = '';
|
||||
|
||||
tiaReadCaptureLinks(function () use (&$during): void {
|
||||
$during = tiaReadCaptureWrapperType();
|
||||
});
|
||||
|
||||
expect($during)->toBe('user-space');
|
||||
});
|
||||
|
||||
it('links every read when the list of globs is empty', function (): void {
|
||||
(new Configuration)->withoutReadCapture([]);
|
||||
|
||||
expect(tiaReadCaptureLinks(fn (): string|false => file_get_contents($this->excluded)))->toBe([$this->excluded]);
|
||||
});
|
||||
|
||||
it('registers no wrapper and links no read when called without globs', function (): void {
|
||||
(new Configuration)->withoutReadCapture();
|
||||
|
||||
$during = '';
|
||||
|
||||
$links = tiaReadCaptureLinks(function () use (&$during): void {
|
||||
$during = tiaReadCaptureWrapperType();
|
||||
file_get_contents($this->kept);
|
||||
});
|
||||
|
||||
expect($during)->toBe('plainfile')
|
||||
->and($links)->toBeEmpty()
|
||||
->and(tiaReadCaptureWrapperType())->toBe('plainfile');
|
||||
});
|
||||
|
||||
it('keeps the explicit links when called without globs', function (): void {
|
||||
(new Configuration)->withoutReadCapture();
|
||||
|
||||
$recorder = new Recorder;
|
||||
$recorder->activateLinkTracking();
|
||||
|
||||
$recorder->beginTest('Some\Missing\TestClass', 'it links', '/project/tests/Feature/LinksTest.php');
|
||||
$recorder->linkSource('/project/resources/views/welcome.blade.php');
|
||||
$recorder->endTest();
|
||||
|
||||
expect($recorder->perTestFiles())
|
||||
->toBe(['/project/tests/Feature/LinksTest.php' => ['/project/resources/views/welcome.blade.php']]);
|
||||
});
|
||||
|
||||
it('leaves a wrapper already registered for file:// untouched when called without globs', function (): void {
|
||||
(new Configuration)->withoutReadCapture();
|
||||
|
||||
LoggingFileWrapper::enable();
|
||||
|
||||
try {
|
||||
$during = null;
|
||||
|
||||
$links = tiaReadCaptureLinks(function () use (&$during): void {
|
||||
$during = tiaReadCaptureWrapperClass();
|
||||
file_get_contents($this->kept);
|
||||
});
|
||||
} finally {
|
||||
LoggingFileWrapper::disable();
|
||||
}
|
||||
|
||||
expect($during)->toBe(LoggingFileWrapper::class)
|
||||
->and($links)->toBeEmpty();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,8 @@ use Pest\Plugins\Tia\FileState;
|
||||
use Pest\Plugins\Tia\Storage;
|
||||
use Pest\Support\Container;
|
||||
use Pest\TestSuite;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Tests\Fixtures\Tia\GitRepo;
|
||||
|
||||
afterEach(function (): void {
|
||||
Storage::useDirectory(null);
|
||||
@@ -37,3 +39,32 @@ it('uses an absolute configured directory', function (): void {
|
||||
|
||||
expect(Storage::tempDir('/project'))->toBe('/tmp/pest-tia');
|
||||
});
|
||||
|
||||
it('keeps the state directory of a project at the repository root', function (): void {
|
||||
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-storage-'.bin2hex(random_bytes(8));
|
||||
|
||||
mkdir($root.'/backend', 0755, true);
|
||||
|
||||
$repo = new GitRepo($root);
|
||||
$repo->init('master');
|
||||
$repo->addOrigin('git@github.com:pestphp/tia-fixture.git');
|
||||
|
||||
$home = $root.DIRECTORY_SEPARATOR.'.home';
|
||||
mkdir($home, 0755, true);
|
||||
|
||||
$original = getenv('HOME');
|
||||
putenv('HOME='.$home);
|
||||
|
||||
try {
|
||||
$rootDir = Storage::tempDir($root);
|
||||
$nestedDir = Storage::tempDir($root.'/backend');
|
||||
} finally {
|
||||
putenv($original === false ? 'HOME' : 'HOME='.$original);
|
||||
new Process(['rm', '-rf', $root])->run();
|
||||
}
|
||||
|
||||
$identity = substr(hash('sha256', 'github.com/pestphp/tia-fixture'), 0, 16);
|
||||
|
||||
expect(basename($rootDir))->toEndWith('-'.$identity)
|
||||
->and(basename($nestedDir))->not->toEndWith('-'.$identity);
|
||||
})->skipOnWindows();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Symfony\Component\Process\Exception\ProcessFailedException;
|
||||
use Symfony\Component\Process\ExecutableFinder;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
@@ -473,6 +474,18 @@ function tiaSfcFixtures(): array
|
||||
"<script setup>\nimport A from '@/A.vue'\nconst hint = 'export default'\n</script>",
|
||||
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
|
||||
],
|
||||
'generic-attribute' => [
|
||||
"<script setup lang=\"ts\" generic=\"T extends Record<string, unknown>\">\nimport E from '@/E.vue'\n</script>",
|
||||
['imports' => ['@/E.vue'], 'moduleType' => 'ts'],
|
||||
],
|
||||
'generic-attribute-single-quoted' => [
|
||||
"<script setup lang='ts' generic='T extends Array<string>'>\nimport F from '@/F.vue'\n</script>",
|
||||
['imports' => ['@/F.vue'], 'moduleType' => 'ts'],
|
||||
],
|
||||
'generic-attribute-before-lang' => [
|
||||
"<script setup generic=\"K extends string, V extends Map<K, number>\" lang=\"ts\">\nimport G from '@/G.vue'\n</script>",
|
||||
['imports' => ['@/G.vue'], 'moduleType' => 'ts'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -555,6 +568,59 @@ function tiaBuildOptionResults(): array
|
||||
return $cache = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
function tiaLoadRolldownResults(): array
|
||||
{
|
||||
static $cache = null;
|
||||
if ($cache !== null) {
|
||||
return $cache;
|
||||
}
|
||||
|
||||
$vitePlus = sys_get_temp_dir().'/pest-tia-vite-plus-'.bin2hex(random_bytes(6));
|
||||
$missing = sys_get_temp_dir().'/pest-tia-no-rolldown-'.bin2hex(random_bytes(6));
|
||||
|
||||
mkdir($vitePlus.'/node_modules/vite', 0755, true);
|
||||
mkdir($missing, 0755, true);
|
||||
file_put_contents($vitePlus.'/package.json', '{}');
|
||||
file_put_contents($vitePlus.'/node_modules/vite/package.json', tiaJson([
|
||||
'name' => 'vite',
|
||||
'type' => 'module',
|
||||
'exports' => ['./package.json' => './package.json', './rolldown' => './rolldown.mjs'],
|
||||
]));
|
||||
file_put_contents($vitePlus.'/node_modules/vite/rolldown.mjs', "export const rolldown = 'vite-plus-stub'\n");
|
||||
file_put_contents($missing.'/package.json', '{}');
|
||||
|
||||
$helper = str_replace('\\', '/', tiaViteHelperPath());
|
||||
$roots = tiaJson(['vite-plus' => str_replace('\\', '/', $vitePlus), 'missing' => str_replace('\\', '/', $missing)]);
|
||||
|
||||
$script = <<<JS
|
||||
import { loadRolldown } from '{$helper}'
|
||||
const out = {}
|
||||
for (const [name, root] of Object.entries({$roots})) {
|
||||
const loaded = await loadRolldown(root)
|
||||
out[name] = loaded === null ? null : { rolldown: loaded.rolldown }
|
||||
}
|
||||
process.stdout.write(JSON.stringify(out))
|
||||
JS;
|
||||
|
||||
$process = new Process(['node', '--input-type=module', '-e', $script]);
|
||||
$process->run();
|
||||
|
||||
foreach (['node_modules/vite/rolldown.mjs', 'node_modules/vite/package.json', 'package.json'] as $file) {
|
||||
@unlink($vitePlus.'/'.$file);
|
||||
}
|
||||
foreach (['node_modules/vite', 'node_modules', ''] as $dir) {
|
||||
@rmdir($vitePlus.'/'.$dir);
|
||||
}
|
||||
@unlink($missing.'/package.json');
|
||||
@rmdir($missing);
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new ProcessFailedException($process);
|
||||
}
|
||||
|
||||
return $cache = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
beforeEach(function (): void {
|
||||
if ((new ExecutableFinder)->find('node') === null) {
|
||||
$this->markTestSkipped('node is not available.');
|
||||
@@ -630,6 +696,10 @@ it('always leaves a default export for importers to resolve against', function (
|
||||
expect(tiaSfcResults()[$name]['code'])->toMatch('/export\s+default\b/');
|
||||
})->with(array_keys(tiaSfcFixtures()));
|
||||
|
||||
it('ends the opening script tag after a quoted attribute that holds a closing angle bracket', function (string $name): void {
|
||||
expect(tiaSfcResults()[$name]['code'])->toStartWith("\nimport ");
|
||||
})->with(['generic-attribute', 'generic-attribute-single-quoted', 'generic-attribute-before-lang']);
|
||||
|
||||
it('does not add a second default export when the block already has one', function (): void {
|
||||
preg_match_all('/export\s+default\b/', tiaSfcResults()['plain-script-with-default']['code'], $matches);
|
||||
|
||||
@@ -665,6 +735,14 @@ it('ignores a default export that only appears in a comment or string', function
|
||||
->and($matches[0])->toHaveCount(2);
|
||||
})->with(['default-export-in-line-comment', 'default-export-in-block-comment', 'default-export-in-string']);
|
||||
|
||||
it('loads the rolldown that Vite+ exposes as vite/rolldown', function (): void {
|
||||
expect(tiaLoadRolldownResults()['vite-plus'])->toBe(['rolldown' => 'vite-plus-stub']);
|
||||
});
|
||||
|
||||
it('finds no rolldown when neither rolldown nor vite/rolldown resolves', function (): void {
|
||||
expect(tiaLoadRolldownResults()['missing'])->toBeNull();
|
||||
});
|
||||
|
||||
it('bundles a script setup component that mentions export default in a comment', function (): void {
|
||||
$rolldown = tiaRolldownPackageDir();
|
||||
if ($rolldown === null) {
|
||||
@@ -711,3 +789,50 @@ it('bundles a script setup component that mentions export default in a comment',
|
||||
'resources/js/components/format.js' => ['Dashboard'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('bundles a generic component whose script tag holds a closing angle bracket', function (): void {
|
||||
$rolldown = tiaRolldownPackageDir();
|
||||
if ($rolldown === null) {
|
||||
$this->markTestSkipped('rolldown is not resolvable.');
|
||||
}
|
||||
|
||||
$root = sys_get_temp_dir().'/pest-tia-rolldown-generic-'.bin2hex(random_bytes(6));
|
||||
mkdir($root.'/resources/js/pages', 0755, true);
|
||||
mkdir($root.'/resources/js/components', 0755, true);
|
||||
mkdir($root.'/node_modules', 0755, true);
|
||||
$root = realpath($root);
|
||||
|
||||
symlink($rolldown, $root.'/node_modules/rolldown');
|
||||
file_put_contents($root.'/package.json', '{}');
|
||||
file_put_contents($root.'/resources/js/pages/Items.vue', <<<'VUE'
|
||||
<script setup lang="ts">
|
||||
import SortableList from '../components/SortableList.vue'
|
||||
</script>
|
||||
<template><SortableList :items="[]" /></template>
|
||||
VUE);
|
||||
file_put_contents($root.'/resources/js/components/SortableList.vue', <<<'VUE'
|
||||
<script setup lang="ts" generic="T extends Record<string, unknown>">
|
||||
import { label } from './label.ts'
|
||||
defineProps<{ items: T[] }>()
|
||||
</script>
|
||||
<template><li v-for="item in items">{{ label(item) }}</li></template>
|
||||
VUE);
|
||||
file_put_contents($root.'/resources/js/components/label.ts', "export const label = (v: unknown): string => String(v)\n");
|
||||
|
||||
$process = new Process(['node', tiaViteHelperPath(), $root]);
|
||||
$process->run();
|
||||
|
||||
unlink($root.'/node_modules/rolldown');
|
||||
foreach (['resources/js/pages/Items.vue', 'resources/js/components/SortableList.vue', 'resources/js/components/label.ts', 'package.json'] as $file) {
|
||||
@unlink($root.'/'.$file);
|
||||
}
|
||||
foreach (['node_modules', 'resources/js/pages', 'resources/js/components', 'resources/js', 'resources', ''] as $dir) {
|
||||
@rmdir($root.'/'.$dir);
|
||||
}
|
||||
|
||||
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
|
||||
->and(json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR))->toMatchArray([
|
||||
'resources/js/components/SortableList.vue' => ['Items'],
|
||||
'resources/js/components/label.ts' => ['Items'],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -181,3 +181,88 @@ it('uses custom mappings for an unknown Vue page with defaults disabled', functi
|
||||
|
||||
expect($graph->affected(['resources/js/Pages/Enroll.vue']))->toBe(['tests/Unit/CalculatorTest.php']);
|
||||
});
|
||||
|
||||
it('captures every read by default', function (): void {
|
||||
expect($this->watchPatterns->isReadCaptureEnabled())->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('excludes reads of files matching a glob', function (): void {
|
||||
$configuration = new Configuration;
|
||||
|
||||
expect($configuration->withoutReadCapture(['lang/*.json']))->toBe($configuration)
|
||||
->and($this->watchPatterns->isReadCaptureEnabled())->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('lang/vendor/package/fr.json'))->toBeFalse()
|
||||
->and($this->watchPatterns->excludesRead('resources/lang/fr.json'))->toBeFalse()
|
||||
->and($this->watchPatterns->excludesRead('lang/fr.php'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('matches read globs like watch patterns', function (): void {
|
||||
(new Configuration)->withoutReadCapture([
|
||||
'lang/**/*.json !lang/vendor/keep/**',
|
||||
'tests/Fixtures/*.csv',
|
||||
'.env.testing',
|
||||
]);
|
||||
|
||||
expect($this->watchPatterns->excludesRead('lang/vendor/package/fr.json'))->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('lang/vendor/keep/fr.json'))->toBeFalse()
|
||||
->and($this->watchPatterns->excludesRead('tests/Fixtures/orders.csv'))->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('tests/Fixtures/nested/orders.csv'))->toBeFalse()
|
||||
->and($this->watchPatterns->excludesRead('.env.testing'))->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('.env.local'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('does not exclude a dotfile unless the glob names it', function (): void {
|
||||
(new Configuration)->withoutReadCapture(['**']);
|
||||
|
||||
expect($this->watchPatterns->excludesRead('lang/fr.json'))->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('.env.testing'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('accumulates read exclusions from repeated calls', function (): void {
|
||||
(new Configuration)
|
||||
->withoutReadCapture(['lang/*.json'])
|
||||
->withoutReadCapture(['resources/lang/*.json']);
|
||||
|
||||
expect($this->watchPatterns->excludesRead('lang/fr.json'))->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('resources/lang/fr.json'))->toBeTrue();
|
||||
});
|
||||
|
||||
it('does not turn read capture off for an empty exclusion list', function (): void {
|
||||
(new Configuration)->withoutReadCapture([]);
|
||||
|
||||
expect($this->watchPatterns->isReadCaptureEnabled())->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('turns read capture off without a list of globs', function (): void {
|
||||
(new Configuration)->withoutReadCapture();
|
||||
|
||||
expect($this->watchPatterns->isReadCaptureEnabled())->toBeFalse();
|
||||
});
|
||||
|
||||
it('keeps read capture off when globs are added afterwards', function (): void {
|
||||
(new Configuration)
|
||||
->withoutReadCapture()
|
||||
->withoutReadCapture(['lang/*.json']);
|
||||
|
||||
expect($this->watchPatterns->isReadCaptureEnabled())->toBeFalse();
|
||||
});
|
||||
|
||||
it('captures reads again on reset', function (): void {
|
||||
(new Configuration)
|
||||
->withoutReadCapture()
|
||||
->withoutReadCapture(['lang/*.json']);
|
||||
|
||||
$this->watchPatterns->reset();
|
||||
|
||||
expect($this->watchPatterns->isReadCaptureEnabled())->toBeTrue()
|
||||
->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('does not change the default watch fallbacks of an excluded read', function (): void {
|
||||
(new Configuration)->withoutReadCapture(['.env.testing']);
|
||||
|
||||
expect($this->watchPatterns->matchedDirectories(getcwd(), ['.env.testing']))->toBe(['tests']);
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Support\InstalledPackages;
|
||||
|
||||
$project = [
|
||||
'root' => ['install_path' => '/project/vendor/composer/../../'],
|
||||
'versions' => [
|
||||
'pestphp/pest' => ['dev_requirement' => true],
|
||||
'symfony/console' => ['dev_requirement' => false],
|
||||
],
|
||||
];
|
||||
|
||||
$pharTool = [
|
||||
'root' => ['install_path' => 'phar:///tools/dump.phar/vendor/composer/../../'],
|
||||
'versions' => [
|
||||
'laravel/framework' => ['dev_requirement' => false],
|
||||
],
|
||||
];
|
||||
|
||||
it('finds a package that the project installs', function () use ($project, $pharTool): void {
|
||||
$packages = new InstalledPackages([$pharTool, $project]);
|
||||
|
||||
expect($packages->contains('symfony/console'))->toBeTrue()
|
||||
->and($packages->contains('pestphp/pest'))->toBeTrue();
|
||||
});
|
||||
|
||||
it('ignores a package that only a tool bundled in a PHAR installs', function () use ($project, $pharTool): void {
|
||||
$packages = new InstalledPackages([$pharTool, $project]);
|
||||
|
||||
expect($packages->contains('laravel/framework'))->toBeFalse()
|
||||
->and($packages->contains('laravel/framework', false))->toBeFalse();
|
||||
});
|
||||
|
||||
it('leaves out a development requirement when asked', function () use ($project): void {
|
||||
$packages = new InstalledPackages([$project]);
|
||||
|
||||
expect($packages->contains('pestphp/pest', false))->toBeFalse()
|
||||
->and($packages->contains('symfony/console', false))->toBeTrue();
|
||||
});
|
||||
|
||||
it('reads an installed set that has no install path', function (): void {
|
||||
$packages = new InstalledPackages([
|
||||
['root' => [], 'versions' => ['laravel/framework' => ['dev_requirement' => false]]],
|
||||
]);
|
||||
|
||||
expect($packages->contains('laravel/framework'))->toBeTrue()
|
||||
->and($packages->contains('symfony/console'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('reads the packages that Composer loaded', function (): void {
|
||||
expect(InstalledPackages::has('pestphp/pest'))->toBeTrue()
|
||||
->and(InstalledPackages::has('pestphp/pest-plugin-that-does-not-exist'))->toBeFalse();
|
||||
});
|
||||
|
||||
it('is the only class of src that reads Composer packages', function (): void {
|
||||
$source = dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'src';
|
||||
$readers = [];
|
||||
|
||||
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS)) as $file) {
|
||||
if ($file->getExtension() === 'php' && str_contains((string) file_get_contents($file->getPathname()), 'InstalledVersions')) {
|
||||
$readers[] = substr($file->getPathname(), strlen($source) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
expect($readers)->toBe(['Support'.DIRECTORY_SEPARATOR.'InstalledPackages.php']);
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user