mirror of
https://github.com/pestphp/pest.git
synced 2026-12-03 22:45:06 +01:00
fix(tia): link files a test reads as text, not only files it executes (#2006)
* fix(tia): link files a test reads as text, not only files it executes * fix(tia): report dangling symlinks as links while reads are captured `is_link()` stats with STREAM_URL_STAT_LINK | STREAM_URL_STAT_QUIET. The `file_exists()` precheck in `ReadCapture::url_stat()` follows the link, so a dangling symlink returned false before reaching `lstat()`, and `is_link()` reported false while a test recorded. Handle STREAM_URL_STAT_LINK first and always answer it through `lstat()`. A quiet stat of a path that is neither a link nor a file still returns false without a warning. The regression test covers a link to an existing file and a dangling link. * test(tia): skip the read-capture feature tests without a coverage driver The fixture runs record a graph from coverage, so with CI's `coverage: none` all five cases failed. Skip them when `Coverage::isAvailable()` is false, as CoveragePiggyback does. * chore: style * Refresh read capture test snapshots --------- Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com> Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
This commit is contained in:
@@ -0,0 +1,382 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia;
|
||||
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class ReadCapture
|
||||
{
|
||||
private const string PROTOCOL = 'file';
|
||||
|
||||
private const int STREAM_OPEN_FOR_INCLUDE = 0x00000080;
|
||||
|
||||
/**
|
||||
* @var resource|null
|
||||
*/
|
||||
public mixed $context = null;
|
||||
|
||||
/**
|
||||
* @var resource|object
|
||||
*/
|
||||
private mixed $handle;
|
||||
|
||||
private static ?Recorder $activeRecorder = null;
|
||||
|
||||
/**
|
||||
* @var class-string|null
|
||||
*/
|
||||
private static ?string $previousWrapper = null;
|
||||
|
||||
public static function start(Recorder $recorder): void
|
||||
{
|
||||
if (self::$activeRecorder instanceof Recorder) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::$previousWrapper = self::registeredWrapper();
|
||||
self::$activeRecorder = $recorder;
|
||||
|
||||
self::enable();
|
||||
}
|
||||
|
||||
public static function stop(): void
|
||||
{
|
||||
if (! self::$activeRecorder instanceof Recorder) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::$activeRecorder = null;
|
||||
|
||||
self::disable();
|
||||
|
||||
self::$previousWrapper = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return class-string|null
|
||||
*/
|
||||
private static function registeredWrapper(): ?string
|
||||
{
|
||||
$handle = @fopen(__FILE__, 'rb');
|
||||
|
||||
if ($handle === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$metadata = stream_get_meta_data($handle);
|
||||
|
||||
fclose($handle);
|
||||
|
||||
$wrapper = $metadata['wrapper_data'] ?? null;
|
||||
|
||||
if ($metadata['wrapper_type'] !== 'user-space' || ! is_object($wrapper) || $wrapper instanceof self) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $wrapper::class;
|
||||
}
|
||||
|
||||
private static function enable(): void
|
||||
{
|
||||
stream_wrapper_unregister(self::PROTOCOL);
|
||||
stream_wrapper_register(self::PROTOCOL, self::class);
|
||||
}
|
||||
|
||||
private static function disable(): void
|
||||
{
|
||||
if (self::$previousWrapper === null) {
|
||||
stream_wrapper_restore(self::PROTOCOL);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
stream_wrapper_unregister(self::PROTOCOL);
|
||||
stream_wrapper_register(self::PROTOCOL, self::$previousWrapper);
|
||||
}
|
||||
|
||||
public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool
|
||||
{
|
||||
$handle = $this->withOriginalWrapper(function () use ($path, $mode, $options, &$openedPath) {
|
||||
$handle = self::$previousWrapper === null
|
||||
? $this->openNatively($path, $mode, $options)
|
||||
: $this->openThroughPreviousWrapper(self::$previousWrapper, $path, $mode, $options, $openedPath);
|
||||
|
||||
if ($handle !== false && $this->isRead($mode, $options)) {
|
||||
self::$activeRecorder?->linkRead($path);
|
||||
}
|
||||
|
||||
return $handle;
|
||||
});
|
||||
|
||||
if ($handle === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->handle = $handle;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function dir_closedir(): bool
|
||||
{
|
||||
closedir($this->resource());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function dir_opendir(string $path): bool
|
||||
{
|
||||
$handle = $this->withOriginalWrapper(fn () => opendir($path, $this->context));
|
||||
|
||||
if (! is_resource($handle)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->handle = $handle;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function dir_readdir(): string|false
|
||||
{
|
||||
return readdir($this->resource());
|
||||
}
|
||||
|
||||
public function dir_rewinddir(): bool
|
||||
{
|
||||
rewinddir($this->resource());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function mkdir(string $path, int $mode, int $options): bool
|
||||
{
|
||||
return $this->withOriginalWrapper(fn (): bool => mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0, $this->context));
|
||||
}
|
||||
|
||||
public function rename(string $pathFrom, string $pathTo): bool
|
||||
{
|
||||
return $this->withOriginalWrapper(fn (): bool => rename($pathFrom, $pathTo, $this->context));
|
||||
}
|
||||
|
||||
public function rmdir(string $path): bool
|
||||
{
|
||||
return $this->withOriginalWrapper(fn (): bool => rmdir($path, $this->context));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return resource|false
|
||||
*/
|
||||
public function stream_cast(int $castAs): mixed
|
||||
{
|
||||
return $this->forward('stream_cast', fn (mixed $resource): mixed => $resource, $castAs);
|
||||
}
|
||||
|
||||
public function stream_close(): void
|
||||
{
|
||||
$this->forward('stream_close', fn (mixed $resource): bool => fclose($resource));
|
||||
}
|
||||
|
||||
public function stream_eof(): bool
|
||||
{
|
||||
return $this->forward('stream_eof', fn (mixed $resource): bool => feof($resource)) === true;
|
||||
}
|
||||
|
||||
public function stream_flush(): bool
|
||||
{
|
||||
return $this->forward('stream_flush', fn (mixed $resource): bool => fflush($resource)) === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int<0, 7> $operation
|
||||
*/
|
||||
public function stream_lock(int $operation): bool
|
||||
{
|
||||
return $this->forward('stream_lock', fn (mixed $resource): bool => flock($resource, $operation), $operation) === true;
|
||||
}
|
||||
|
||||
public function stream_metadata(string $path, int $option, mixed $value): bool
|
||||
{
|
||||
return $this->withOriginalWrapper(fn (): bool => match ($option) {
|
||||
STREAM_META_TOUCH => is_array($value) && is_int($value[0] ?? null) && is_int($value[1] ?? null)
|
||||
? touch($path, $value[0], $value[1])
|
||||
: touch($path),
|
||||
STREAM_META_OWNER_NAME, STREAM_META_OWNER => (is_string($value) || is_int($value)) && chown($path, $value),
|
||||
STREAM_META_GROUP_NAME, STREAM_META_GROUP => (is_string($value) || is_int($value)) && chgrp($path, $value),
|
||||
STREAM_META_ACCESS => is_int($value) && chmod($path, $value),
|
||||
default => false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int<1, max> $count
|
||||
*/
|
||||
public function stream_read(int $count): string|false
|
||||
{
|
||||
$data = $this->forward('stream_read', fn (mixed $resource): string|false => fread($resource, $count), $count);
|
||||
|
||||
return is_string($data) ? $data : false;
|
||||
}
|
||||
|
||||
public function stream_seek(int $offset, int $whence = SEEK_SET): bool
|
||||
{
|
||||
return $this->forward('stream_seek', fn (mixed $resource): bool => fseek($resource, $offset, $whence) === 0, $offset, $whence) === true;
|
||||
}
|
||||
|
||||
public function stream_set_option(int $option, int $arg1, ?int $arg2): bool
|
||||
{
|
||||
return $this->forward('stream_set_option', fn (mixed $resource): bool => match ($option) {
|
||||
STREAM_OPTION_BLOCKING => stream_set_blocking($resource, (bool) $arg1),
|
||||
STREAM_OPTION_READ_TIMEOUT => stream_set_timeout($resource, $arg1, $arg2 ?? 0),
|
||||
STREAM_OPTION_WRITE_BUFFER => stream_set_write_buffer($resource, $arg1) === 0,
|
||||
STREAM_OPTION_READ_BUFFER => stream_set_read_buffer($resource, $arg1) === 0,
|
||||
default => false,
|
||||
}, $option, $arg1, $arg2) === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int|string, int>|false
|
||||
*/
|
||||
public function stream_stat(): array|false
|
||||
{
|
||||
$stat = $this->forward('stream_stat', fn (mixed $resource): array|false => fstat($resource));
|
||||
|
||||
return is_array($stat) ? $stat : false;
|
||||
}
|
||||
|
||||
public function stream_tell(): int|false
|
||||
{
|
||||
$position = $this->forward('stream_tell', fn (mixed $resource): int|false => ftell($resource));
|
||||
|
||||
return is_int($position) ? $position : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int<0, max> $newSize
|
||||
*/
|
||||
public function stream_truncate(int $newSize): bool
|
||||
{
|
||||
return $this->forward('stream_truncate', fn (mixed $resource): bool => ftruncate($resource, $newSize), $newSize) === true;
|
||||
}
|
||||
|
||||
public function stream_write(string $data): int|false
|
||||
{
|
||||
$written = $this->forward('stream_write', fn (mixed $resource): int|false => fwrite($resource, $data), $data);
|
||||
|
||||
return is_int($written) ? $written : false;
|
||||
}
|
||||
|
||||
public function unlink(string $path): bool
|
||||
{
|
||||
return $this->withOriginalWrapper(fn (): bool => unlink($path, $this->context));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int|string, int>|false
|
||||
*/
|
||||
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;
|
||||
|
||||
if (($flags & STREAM_URL_STAT_LINK) !== 0) {
|
||||
if ($isQuiet && ! is_link($path) && ! file_exists($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return @lstat($path);
|
||||
}
|
||||
|
||||
if ($isQuiet && ! file_exists($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return @stat($path);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return resource|false
|
||||
*/
|
||||
private function openNatively(string $path, string $mode, int $options): mixed
|
||||
{
|
||||
return ($options & STREAM_REPORT_ERRORS) !== 0
|
||||
? fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0, $this->context)
|
||||
: @fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0, $this->context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param class-string $wrapperClass
|
||||
*/
|
||||
private function openThroughPreviousWrapper(string $wrapperClass, string $path, string $mode, int $options, ?string &$openedPath): object|false
|
||||
{
|
||||
$wrapper = new $wrapperClass;
|
||||
|
||||
if (property_exists($wrapper, 'context')) {
|
||||
$wrapper->context = $this->context;
|
||||
}
|
||||
|
||||
if (! method_exists($wrapper, 'stream_open') || $wrapper->stream_open($path, $mode, $options, $openedPath) !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $wrapper;
|
||||
}
|
||||
|
||||
private function isRead(string $mode, int $options): bool
|
||||
{
|
||||
if (($options & self::STREAM_OPEN_FOR_INCLUDE) !== 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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
|
||||
*/
|
||||
private function forward(string $method, Closure $native, mixed ...$arguments): mixed
|
||||
{
|
||||
if (! is_object($this->handle)) {
|
||||
return $native($this->handle);
|
||||
}
|
||||
|
||||
if (! method_exists($this->handle, $method)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->handle->{$method}(...$arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T
|
||||
*
|
||||
* @param Closure(): T $callback
|
||||
* @return T
|
||||
*/
|
||||
private function withOriginalWrapper(Closure $callback): mixed
|
||||
{
|
||||
self::disable();
|
||||
|
||||
try {
|
||||
return $callback();
|
||||
} finally {
|
||||
self::enable();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,8 @@ final class Recorder
|
||||
|
||||
$this->currentTestFile = $file;
|
||||
|
||||
ReadCapture::start($this);
|
||||
|
||||
if ($this->classUsesDatabase($className)) {
|
||||
$this->perTestUsesDatabase[$file] = true;
|
||||
}
|
||||
@@ -127,6 +129,8 @@ final class Recorder
|
||||
return;
|
||||
}
|
||||
|
||||
ReadCapture::stop();
|
||||
|
||||
if (! $this->captureCoverage || ! $this->driverAvailable()) {
|
||||
$this->currentTestFile = null;
|
||||
|
||||
@@ -189,6 +193,17 @@ final class Recorder
|
||||
$this->perTestFiles[$this->currentTestFile][$sourceFile] = true;
|
||||
}
|
||||
|
||||
public function linkRead(string $path): void
|
||||
{
|
||||
$real = realpath($path);
|
||||
|
||||
if ($real === false || ! is_file($real) || ! $this->sourceScope()->contains($real)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->linkSource($real);
|
||||
}
|
||||
|
||||
private function classUsesDatabase(string $className): bool
|
||||
{
|
||||
if (array_key_exists($className, $this->classUsesDatabaseCache)) {
|
||||
@@ -374,6 +389,8 @@ final class Recorder
|
||||
|
||||
public function reset(): void
|
||||
{
|
||||
ReadCapture::stop();
|
||||
|
||||
$this->currentTestFile = null;
|
||||
$this->perTestFiles = [];
|
||||
$this->perTestTables = [];
|
||||
|
||||
@@ -2018,6 +2018,25 @@
|
||||
✓ 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\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"
|
||||
✓ reads → it links a project file the test reads with dataset "fopen"
|
||||
✓ reads → it links a project file the test reads with dataset "SplFileObject"
|
||||
✓ reads → it does not link a file the test only writes
|
||||
✓ reads → it does not link a file the test includes
|
||||
✓ reads → it does not link a file outside the project
|
||||
✓ reads → it does not link a directory the test lists
|
||||
✓ reads → it records nothing while inactive
|
||||
✓ the file wrapper → it is replaced while a test records and restored after it
|
||||
✓ 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 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
|
||||
|
||||
PASS Tests\Unit\Plugins\Tia\Recorder
|
||||
✓ activateLinkTracking() → it tracks tables without a coverage driver
|
||||
✓ activateLinkTracking() → it tracks inertia components without a coverage driver
|
||||
@@ -2347,4 +2366,4 @@
|
||||
✓ pass with dataset with ('my-datas-set-value')
|
||||
✓ within describe → pass with dataset with ('my-datas-set-value')
|
||||
|
||||
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 37 skipped, 1666 passed (3706 assertions)
|
||||
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 37 skipped, 1683 passed (3728 assertions)
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Support\Coverage;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
function tiaRecordWithSourceReadingTest(Project $project, string ...$arguments): void
|
||||
{
|
||||
$project->write('tests/Unit/GreeterSourceTest.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
test('keeps the greeting format', function (): void {
|
||||
expect(file_get_contents(__DIR__.'/../../app/Greeter.php'))->toContain("'Hello, %s!'");
|
||||
});
|
||||
PHP);
|
||||
$project->git()->commit('add a test that reads the greeter');
|
||||
|
||||
$project->pest('--tia', ...$arguments);
|
||||
}
|
||||
|
||||
test('a test that reads a file records an edge to it', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
|
||||
tiaRecordWithSourceReadingTest($project, ...$arguments);
|
||||
|
||||
$graph = $project->graph() ?? [];
|
||||
$files = array_map(
|
||||
fn (int $id): string => $graph['files'][$id],
|
||||
$graph['edges']['tests/Unit/GreeterSourceTest.php'] ?? [],
|
||||
);
|
||||
|
||||
expect($files)->toContain('app/Greeter.php');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a changed file selects the test that reads it', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
|
||||
tiaRecordWithSourceReadingTest($project, ...$arguments);
|
||||
|
||||
$project->write('app/Greeter.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Fixture\App;
|
||||
|
||||
final class Greeter
|
||||
{
|
||||
public function greet(string $name): string
|
||||
{
|
||||
return sprintf('Hello, %s!', $name);
|
||||
}
|
||||
|
||||
public function shout(string $name): string
|
||||
{
|
||||
return strtoupper($this->greet($name));
|
||||
}
|
||||
}
|
||||
PHP);
|
||||
|
||||
$result = $project->pest('--tia', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->affected())->toBe(3, $result->describe())
|
||||
->and($result->replayed())->toBe(4, $result->describe());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a file a test reads does not select it when another file changes', function (): void {
|
||||
$project = Project::make('master');
|
||||
|
||||
tiaRecordWithSourceReadingTest($project);
|
||||
|
||||
$project->write('app/Calculator.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Fixture\App;
|
||||
|
||||
final class Calculator
|
||||
{
|
||||
public function add(int $a, int $b): int
|
||||
{
|
||||
return $a + $b;
|
||||
}
|
||||
|
||||
public function subtract(int $a, int $b): int
|
||||
{
|
||||
return $a - $b;
|
||||
}
|
||||
|
||||
public function multiply(int $a, int $b): int
|
||||
{
|
||||
return $a * $b;
|
||||
}
|
||||
}
|
||||
PHP);
|
||||
|
||||
$result = $project->pest('--tia');
|
||||
|
||||
expect($result->affected())->toBe(4, $result->describe())
|
||||
->and($result->replayed())->toBe(3, $result->describe());
|
||||
})->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Fixtures\Tia;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class LoggingFileWrapper
|
||||
{
|
||||
private const int STREAM_OPEN_FOR_INCLUDE = 0x00000080;
|
||||
|
||||
/**
|
||||
* @var array<int, array{path: string, including: bool}>
|
||||
*/
|
||||
public static array $opened = [];
|
||||
|
||||
/**
|
||||
* @var resource|null
|
||||
*/
|
||||
public mixed $context = null;
|
||||
|
||||
/**
|
||||
* @var resource
|
||||
*/
|
||||
private mixed $resource;
|
||||
|
||||
public static function enable(): void
|
||||
{
|
||||
self::$opened = [];
|
||||
|
||||
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
|
||||
{
|
||||
self::disable();
|
||||
|
||||
try {
|
||||
$resource = @fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0);
|
||||
} finally {
|
||||
stream_wrapper_unregister('file');
|
||||
stream_wrapper_register('file', self::class);
|
||||
}
|
||||
|
||||
if ($resource === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self::$opened[] = ['path' => $path, 'including' => ($options & self::STREAM_OPEN_FOR_INCLUDE) !== 0];
|
||||
|
||||
$this->resource = $resource;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function stream_read(int $count): string|false
|
||||
{
|
||||
return fread($this->resource, max(1, $count));
|
||||
}
|
||||
|
||||
public function stream_write(string $data): int|false
|
||||
{
|
||||
return fwrite($this->resource, $data);
|
||||
}
|
||||
|
||||
public function stream_eof(): bool
|
||||
{
|
||||
return feof($this->resource);
|
||||
}
|
||||
|
||||
public function stream_close(): void
|
||||
{
|
||||
fclose($this->resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int|string, int>|false
|
||||
*/
|
||||
public function stream_stat(): array|false
|
||||
{
|
||||
return fstat($this->resource);
|
||||
}
|
||||
|
||||
public function stream_set_option(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int|string, int>|false
|
||||
*/
|
||||
public function url_stat(string $path): array|false
|
||||
{
|
||||
self::disable();
|
||||
|
||||
try {
|
||||
return @stat($path);
|
||||
} finally {
|
||||
stream_wrapper_unregister('file');
|
||||
stream_wrapper_register('file', self::class);
|
||||
}
|
||||
}
|
||||
|
||||
public function dir_opendir(string $path): bool
|
||||
{
|
||||
self::disable();
|
||||
|
||||
try {
|
||||
$resource = @opendir($path);
|
||||
} finally {
|
||||
stream_wrapper_unregister('file');
|
||||
stream_wrapper_register('file', self::class);
|
||||
}
|
||||
|
||||
if ($resource === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->resource = $resource;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function dir_readdir(): string|false
|
||||
{
|
||||
return readdir($this->resource);
|
||||
}
|
||||
|
||||
public function dir_rewinddir(): bool
|
||||
{
|
||||
rewinddir($this->resource);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function dir_closedir(): bool
|
||||
{
|
||||
closedir($this->resource);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function unlink(string $path): bool
|
||||
{
|
||||
self::disable();
|
||||
|
||||
try {
|
||||
return @unlink($path);
|
||||
} finally {
|
||||
stream_wrapper_unregister('file');
|
||||
stream_wrapper_register('file', self::class);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\ReadCapture;
|
||||
use Pest\Plugins\Tia\Recorder;
|
||||
use Tests\Fixtures\Tia\LoggingFileWrapper;
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
function tiaReadCaptureLinks(Closure $callback): array
|
||||
{
|
||||
$recorder = new Recorder;
|
||||
$recorder->activateLinkTracking();
|
||||
|
||||
$recorder->beginTest('Some\Missing\TestClass', 'it reads', '/project/tests/Feature/ReadsTest.php');
|
||||
|
||||
try {
|
||||
$callback();
|
||||
} finally {
|
||||
$recorder->endTest();
|
||||
}
|
||||
|
||||
return $recorder->perTestFiles()['/project/tests/Feature/ReadsTest.php'] ?? [];
|
||||
}
|
||||
|
||||
function tiaReadCaptureWrapperType(): string
|
||||
{
|
||||
$handle = fopen(__FILE__, 'rb');
|
||||
|
||||
if ($handle === false) {
|
||||
throw new RuntimeException(sprintf('Unable to open [%s].', __FILE__));
|
||||
}
|
||||
|
||||
try {
|
||||
return (string) stream_get_meta_data($handle)['wrapper_type'];
|
||||
} finally {
|
||||
fclose($handle);
|
||||
}
|
||||
}
|
||||
|
||||
function tiaReadCaptureWrapperClass(): ?string
|
||||
{
|
||||
$handle = fopen(__FILE__, 'rb');
|
||||
|
||||
if ($handle === false) {
|
||||
throw new RuntimeException(sprintf('Unable to open [%s].', __FILE__));
|
||||
}
|
||||
|
||||
try {
|
||||
$wrapper = stream_get_meta_data($handle)['wrapper_data'] ?? null;
|
||||
|
||||
return is_object($wrapper) ? $wrapper::class : null;
|
||||
} finally {
|
||||
fclose($handle);
|
||||
}
|
||||
}
|
||||
|
||||
describe('reads', function (): void {
|
||||
it('links a project file the test reads', function (Closure $read): void {
|
||||
$source = (string) realpath(dirname(__DIR__, 4).'/src/Plugins/Tia/ReadCapture.php');
|
||||
|
||||
expect(tiaReadCaptureLinks(fn () => $read($source)))->toBe([$source]);
|
||||
})->with([
|
||||
'file_get_contents' => fn (string $path): string|false => file_get_contents($path),
|
||||
'file' => fn (string $path): array|false => file($path),
|
||||
'fopen' => fn (string $path): bool => fclose(fopen($path, 'rb')),
|
||||
'SplFileObject' => fn (string $path): string|false => new SplFileObject($path)->fgets(),
|
||||
]);
|
||||
|
||||
it('does not link a file the test only writes', function (): void {
|
||||
$path = __DIR__.'/read-capture-'.bin2hex(random_bytes(8)).'.txt';
|
||||
|
||||
try {
|
||||
expect(tiaReadCaptureLinks(fn (): int|false => file_put_contents($path, 'written')))->toBeEmpty();
|
||||
} finally {
|
||||
@unlink($path);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not link a file the test includes', function (): void {
|
||||
$path = __DIR__.'/read-capture-'.bin2hex(random_bytes(8)).'.php';
|
||||
file_put_contents($path, "<?php\n\nreturn 1;\n");
|
||||
|
||||
try {
|
||||
expect(tiaReadCaptureLinks(fn (): mixed => require $path))->toBeEmpty();
|
||||
} finally {
|
||||
@unlink($path);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not link a file outside the project', function (): void {
|
||||
$path = (string) tempnam(sys_get_temp_dir(), 'pest_');
|
||||
file_put_contents($path, 'outside');
|
||||
|
||||
try {
|
||||
expect(tiaReadCaptureLinks(fn (): string|false => file_get_contents($path)))->toBeEmpty();
|
||||
} finally {
|
||||
@unlink($path);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not link a directory the test lists', function (): void {
|
||||
expect(tiaReadCaptureLinks(fn (): array|false => scandir(__DIR__)))->toBeEmpty();
|
||||
});
|
||||
|
||||
it('records nothing while inactive', function (): void {
|
||||
$recorder = new Recorder;
|
||||
|
||||
$recorder->beginTest('Some\Missing\TestClass', 'it reads', '/project/tests/Feature/ReadsTest.php');
|
||||
$wrapperType = tiaReadCaptureWrapperType();
|
||||
$recorder->endTest();
|
||||
|
||||
expect($wrapperType)->toBe('plainfile')
|
||||
->and($recorder->perTestFiles())->toBeEmpty();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the file wrapper', function (): void {
|
||||
it('is replaced while a test records and restored after it', function (): void {
|
||||
$during = '';
|
||||
|
||||
tiaReadCaptureLinks(function () use (&$during): void {
|
||||
$during = tiaReadCaptureWrapperType();
|
||||
});
|
||||
|
||||
expect($during)->toBe('user-space')
|
||||
->and(tiaReadCaptureWrapperType())->toBe('plainfile');
|
||||
});
|
||||
|
||||
it('is restored when the recorder resets', function (): void {
|
||||
$recorder = new Recorder;
|
||||
$recorder->activateLinkTracking();
|
||||
|
||||
$recorder->beginTest('Some\Missing\TestClass', 'it reads', '/project/tests/Feature/ReadsTest.php');
|
||||
$recorder->reset();
|
||||
|
||||
expect(tiaReadCaptureWrapperType())->toBe('plainfile');
|
||||
});
|
||||
|
||||
it('passes filesystem operations through while a test records', function (): void {
|
||||
$directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-read-capture-'.bin2hex(random_bytes(8));
|
||||
$results = [];
|
||||
|
||||
tiaReadCaptureLinks(function () use ($directory, &$results): void {
|
||||
$results['mkdir'] = mkdir($directory.'/nested', 0755, true);
|
||||
$results['write'] = file_put_contents($directory.'/nested/a.txt', 'abc');
|
||||
$results['rename'] = rename($directory.'/nested/a.txt', $directory.'/nested/b.txt');
|
||||
$results['touch'] = touch($directory.'/nested/b.txt', 1_000_000_000, 1_000_000_000);
|
||||
$results['mtime'] = filemtime($directory.'/nested/b.txt');
|
||||
$results['chmod'] = chmod($directory.'/nested/b.txt', 0644);
|
||||
$results['exists'] = file_exists($directory.'/nested/b.txt');
|
||||
$results['scandir'] = array_values(array_diff((array) scandir($directory.'/nested'), ['.', '..']));
|
||||
|
||||
$handle = fopen($directory.'/nested/b.txt', 'r+b');
|
||||
assert(is_resource($handle));
|
||||
$results['lock'] = flock($handle, LOCK_EX);
|
||||
$results['seek'] = fseek($handle, 1);
|
||||
$results['read'] = fread($handle, 2);
|
||||
$results['truncate'] = ftruncate($handle, 1);
|
||||
$results['size'] = fstat($handle)['size'] ?? null;
|
||||
$results['unlock'] = flock($handle, LOCK_UN);
|
||||
fclose($handle);
|
||||
|
||||
$results['unlink'] = unlink($directory.'/nested/b.txt');
|
||||
$results['rmdir'] = rmdir($directory.'/nested') && rmdir($directory);
|
||||
});
|
||||
|
||||
expect($results)->toBe([
|
||||
'mkdir' => true,
|
||||
'write' => 3,
|
||||
'rename' => true,
|
||||
'touch' => true,
|
||||
'mtime' => 1_000_000_000,
|
||||
'chmod' => true,
|
||||
'exists' => true,
|
||||
'scandir' => ['b.txt'],
|
||||
'lock' => true,
|
||||
'seek' => 0,
|
||||
'read' => 'bc',
|
||||
'truncate' => true,
|
||||
'size' => 1,
|
||||
'unlock' => true,
|
||||
'unlink' => true,
|
||||
'rmdir' => true,
|
||||
]);
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
$target = $directory.'/target.txt';
|
||||
$link = $directory.'/link.txt';
|
||||
|
||||
if ($targetExists) {
|
||||
file_put_contents($target, 'abc');
|
||||
}
|
||||
|
||||
symlink($target, $link);
|
||||
|
||||
$results = [];
|
||||
|
||||
try {
|
||||
tiaReadCaptureLinks(function () use ($link, &$results): void {
|
||||
clearstatcache();
|
||||
|
||||
$results['is_link'] = is_link($link);
|
||||
$results['exists'] = file_exists($link);
|
||||
$results['lstat'] = lstat($link) !== false;
|
||||
$results['filetype'] = filetype($link);
|
||||
});
|
||||
} finally {
|
||||
unlink($link);
|
||||
|
||||
if ($targetExists) {
|
||||
unlink($target);
|
||||
}
|
||||
|
||||
rmdir($directory);
|
||||
}
|
||||
|
||||
expect($results)->toBe([
|
||||
'is_link' => true,
|
||||
'exists' => $expectedExists,
|
||||
'lstat' => true,
|
||||
'filetype' => 'link',
|
||||
]);
|
||||
})->with([
|
||||
'a link to an existing file' => [true, true],
|
||||
'a dangling link' => [false, false],
|
||||
])->skipOnWindows();
|
||||
});
|
||||
|
||||
describe('a wrapper already registered for file://', function (): void {
|
||||
beforeEach(function (): void {
|
||||
LoggingFileWrapper::enable();
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
LoggingFileWrapper::disable();
|
||||
});
|
||||
|
||||
it('opens reads through it and still links them', function (): void {
|
||||
$source = (string) realpath(dirname(__DIR__, 4).'/src/Plugins/Tia/ReadCapture.php');
|
||||
|
||||
expect(tiaReadCaptureLinks(fn (): string|false => file_get_contents($source)))->toBe([$source])
|
||||
->and(array_column(LoggingFileWrapper::$opened, 'path'))->toContain($source);
|
||||
});
|
||||
|
||||
it('keeps the include flag for the files a test includes', function (): void {
|
||||
$path = __DIR__.'/read-capture-'.bin2hex(random_bytes(8)).'.php';
|
||||
file_put_contents($path, "<?php\n\nreturn 1;\n");
|
||||
|
||||
try {
|
||||
$links = tiaReadCaptureLinks(fn (): mixed => require $path);
|
||||
} finally {
|
||||
@unlink($path);
|
||||
}
|
||||
|
||||
$includes = array_filter(
|
||||
LoggingFileWrapper::$opened,
|
||||
fn (array $open): bool => $open['including'] && basename($open['path']) === basename($path),
|
||||
);
|
||||
|
||||
expect($links)->toBeEmpty()
|
||||
->and($includes)->not->toBeEmpty();
|
||||
});
|
||||
|
||||
it('is registered again after the test', function (): void {
|
||||
$during = null;
|
||||
|
||||
tiaReadCaptureLinks(function () use (&$during): void {
|
||||
$during = tiaReadCaptureWrapperClass();
|
||||
});
|
||||
|
||||
expect($during)->toBe(ReadCapture::class)
|
||||
->and(tiaReadCaptureWrapperClass())->toBe(LoggingFileWrapper::class);
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,7 @@ test('parallel', function () use ($run): void {
|
||||
$output = implode("\n", array_slice(explode("\n", (string) $output), -10));
|
||||
$profileOutput = $run('tests/Fixtures/Suites/SuccessOnly.php', '--profile');
|
||||
|
||||
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 29 skipped, 1637 passed (3628 assertions)';
|
||||
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 29 skipped, 1654 passed (3650 assertions)';
|
||||
|
||||
expect($output)
|
||||
->toContain("Tests: {$expected}")
|
||||
|
||||
Reference in New Issue
Block a user