diff --git a/src/Bootstrappers/BootFiles.php b/src/Bootstrappers/BootFiles.php
index 8ddcd9326..87335e3b8 100644
--- a/src/Bootstrappers/BootFiles.php
+++ b/src/Bootstrappers/BootFiles.php
@@ -7,6 +7,7 @@
use Pest\Contracts\Bootstrapper;
use Pest\Exceptions\FatalException;
use Pest\Plugins\Concerns\HandleArguments;
+use Pest\Support\BootstrappedFiles;
use Pest\Support\DatasetInfo;
use Pest\Support\Str;
use Pest\TestSuite;
@@ -89,7 +90,13 @@ private function load(string $filename): void
if (! file_exists($filename)) {
return;
}
+
+ $before = get_included_files();
include_once $filename;
+
+ foreach (array_diff(get_included_files(), $before) as $included) {
+ BootstrappedFiles::add($included);
+ }
}
private function bootDatasets(string $testsPath): void
diff --git a/src/Support/Backtrace.php b/src/Support/Backtrace.php
index 872000867..d38946ab1 100644
--- a/src/Support/Backtrace.php
+++ b/src/Support/Backtrace.php
@@ -17,53 +17,51 @@ final class Backtrace
public static function testFile(): string
{
- $current = null;
+ return self::callSiteFile('Test file not found.');
+ }
+
+ public static function datasetsFile(): string
+ {
+ return self::callSiteFile('Dataset file not found.');
+ }
+
+ private static function callSiteFile(string $missingMessage): string
+ {
+ $fallback = null;
foreach (debug_backtrace(self::BACKTRACE_OPTIONS) as $trace) {
- if (array_key_exists(self::FILE, $trace) === false) {
+ if (! isset($trace[self::FILE])) {
break;
}
- $traceFile = str_replace(DIRECTORY_SEPARATOR, '/', $trace[self::FILE]);
+ $filename = $trace[self::FILE];
+ $traceFile = str_replace(DIRECTORY_SEPARATOR, '/', $filename);
if (
- Str::endsWith($traceFile, 'overrides/Runner/TestSuiteLoader.php') ||
- Str::endsWith($traceFile, 'src/Bootstrappers/BootFiles.php')
+ Str::endsWith($traceFile, 'overrides/Runner/TestSuiteLoader.php')
+ || Str::endsWith($traceFile, 'src/Bootstrappers/BootFiles.php')
) {
break;
}
- $current = $trace;
- }
-
- if ($current === null) {
- throw ShouldNotHappen::fromMessage('Test file not found.');
- }
-
- return $current[self::FILE];
- }
-
- public static function datasetsFile(): string
- {
- $current = null;
-
- foreach (debug_backtrace(self::BACKTRACE_OPTIONS) as $trace) {
- assert(array_key_exists(self::FILE, $trace));
+ if (self::isFrameworkFile($traceFile)) {
+ continue;
+ }
- $traceFile = str_replace(DIRECTORY_SEPARATOR, '/', $trace[self::FILE]);
+ if (BootstrappedFiles::contains($filename)) {
+ $fallback ??= $filename;
- if (Str::endsWith($traceFile, 'Bootstrappers/BootFiles.php') || Str::endsWith($traceFile, 'overrides/Runner/TestSuiteLoader.php')) {
- break;
+ continue;
}
- $current = $trace;
+ return $filename;
}
- if ($current === null) {
- throw ShouldNotHappen::fromMessage('Dataset file not found.');
+ if (is_string($fallback)) {
+ return $fallback;
}
- return $current[self::FILE];
+ throw ShouldNotHappen::fromMessage($missingMessage);
}
public static function file(): string
@@ -99,7 +97,9 @@ private static function backtrace(): array
continue;
}
- if (str_starts_with($trace['file'], dirname(__DIR__).DIRECTORY_SEPARATOR)) {
+ $traceFile = str_replace(DIRECTORY_SEPARATOR, '/', $trace['file']);
+
+ if (self::isFrameworkFile($traceFile)) {
continue;
}
@@ -108,4 +108,19 @@ private static function backtrace(): array
throw ShouldNotHappen::fromMessage('Backtrace not found.');
}
+
+ private static function isFrameworkFile(string $traceFile): bool
+ {
+ $packageRoot = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__DIR__, 2));
+
+ if (
+ str_starts_with($traceFile, $packageRoot.'/src/')
+ || str_starts_with($traceFile, $packageRoot.'/overrides/')
+ ) {
+ return true;
+ }
+
+ return str_contains($traceFile, '/pestphp/pest/src/')
+ || str_contains($traceFile, '/pestphp/pest/overrides/');
+ }
}
diff --git a/src/Support/BootstrappedFiles.php b/src/Support/BootstrappedFiles.php
new file mode 100644
index 000000000..9bfba735c
--- /dev/null
+++ b/src/Support/BootstrappedFiles.php
@@ -0,0 +1,33 @@
+
+ */
+ private static array $files = [];
+
+ public static function add(string $filename): void
+ {
+ self::$files[self::key($filename)] = true;
+ }
+
+ public static function contains(string $filename): bool
+ {
+ return isset(self::$files[self::key($filename)]);
+ }
+
+ private static function key(string $filename): string
+ {
+ $real = realpath($filename);
+
+ return str_replace('\\', '/', $real !== false ? $real : $filename);
+ }
+}
diff --git a/tests/Features/RequiredTestFile.php b/tests/Features/RequiredTestFile.php
new file mode 100644
index 000000000..223a1280e
--- /dev/null
+++ b/tests/Features/RequiredTestFile.php
@@ -0,0 +1,259 @@
+requiredProject)) {
+ return;
+ }
+
+ removeRequiredProject($this->requiredProject);
+});
+
+test('a required test file keeps its own cases and groups', function (): void {
+ $root = makeRequiredProject(withHelper: true, withGamma: false);
+ $this->requiredProject = $root;
+ $junit = $root.DIRECTORY_SEPARATOR.'junit.xml';
+
+ $result = runRequiredProject($root, '--colors=never', '--log-junit', $junit);
+
+ expect($result->getExitCode())->toBe(0, $result->getOutput().$result->getErrorOutput())
+ ->and($result->getOutput())->toMatch('/Tests:\s+5 passed/');
+
+ $files = junitFiles($junit);
+
+ expect($files['alpha one'] ?? '')->toContain('AlphaTest.php')
+ ->and($files['beta one'] ?? '')->toContain('BetaTest.php')
+ ->and($files['beta two'] ?? '')->toContain('BetaTest.php')
+ ->and($files['from helper'] ?? '')->toContain('ViaHelperTest.php')
+ ->and($files['defined in pest php'] ?? '')->toContain('Pest.php');
+
+ $excluded = runRequiredProject($root, '--colors=never', '--exclude-group=beta');
+
+ expect($excluded->getExitCode())->toBe(0, $excluded->getOutput().$excluded->getErrorOutput())
+ ->and($excluded->getOutput())->toContain('alpha one')
+ ->and($excluded->getOutput())->not->toContain('No tests found')
+ ->and($excluded->getOutput())->toMatch('/Tests:\s+3 passed/');
+});
+
+test('parallel workers do not run a required file once per requiring file', function (): void {
+ $root = makeRequiredProject(withHelper: false, withGamma: true);
+ $this->requiredProject = $root;
+
+ $serial = runRequiredProject($root, '--colors=never');
+ $parallel = runRequiredProject($root, '--colors=never', '--parallel', '--processes=2');
+
+ expect($serial->getExitCode())->toBe(0, $serial->getOutput().$serial->getErrorOutput())
+ ->and($serial->getOutput())->toMatch('/Tests:\s+4 passed/')
+ ->and($parallel->getExitCode())->toBe(0, $parallel->getOutput().$parallel->getErrorOutput())
+ ->and($parallel->getOutput())->toMatch('/Tests:\s+4 passed/');
+});
+
+function makeRequiredProject(bool $withHelper, bool $withGamma): string
+{
+ $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-required-'.bin2hex(random_bytes(4));
+
+ mkdir($root.DIRECTORY_SEPARATOR.'tests', 0777, true);
+ mkdir($root.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'bin', 0777, true);
+
+ $vendorAutoload = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php';
+
+ copy(
+ dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'pest-plugins.json',
+ $root.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'pest-plugins.json',
+ );
+
+ file_put_contents(
+ $root.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php',
+ '
+
+
+
+ ./tests
+
+
+
+XML);
+
+ $helper = $withHelper ? <<<'PHP'
+function helperTest(string $description, Closure $closure): void
+{
+ test($description, $closure);
+}
+
+test('defined in pest php', function (): void {
+ expect(true)->toBeTrue();
+});
+PHP : '';
+
+ file_put_contents($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Pest.php', "toBeTrue();
+});
+PHP);
+
+ file_put_contents($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'BetaTest.php', <<<'PHP'
+group('beta');
+
+test('beta one', function (): void {
+ expect(true)->toBeTrue();
+});
+
+test('beta two', function (): void {
+ expect(true)->toBeTrue();
+});
+PHP);
+
+ if ($withHelper) {
+ file_put_contents($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'ViaHelperTest.php', <<<'PHP'
+toBeTrue();
+});
+PHP);
+ }
+
+ if ($withGamma) {
+ file_put_contents($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'GammaTest.php', <<<'PHP'
+toBeTrue();
+});
+PHP);
+ }
+
+ $autoload = var_export(
+ dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php',
+ true,
+ );
+
+ file_put_contents($root.DIRECTORY_SEPARATOR.'run.php', <<handle(\$_SERVER['argv'], \$_SERVER['argv']);
+ \$kernel->terminate();
+} catch (Throwable \$throwable) {
+ Panic::with(\$throwable);
+}
+
+exit(\$result);
+PHP);
+
+ return $root;
+}
+
+function runRequiredProject(string $root, string ...$command): Process
+{
+ $process = new Process(
+ [PHP_BINARY, 'run.php', ...$command],
+ $root,
+ [
+ 'PEST_NO_SUPPORT' => 'true',
+ 'COLLISION_PRINTER' => 'DefaultPrinter',
+ 'COLLISION_IGNORE_DURATION' => 'true',
+ ],
+ );
+
+ $process->setTimeout(120);
+ $process->run();
+
+ return $process;
+}
+
+/**
+ * @return array
+ */
+function junitFiles(string $path): array
+{
+ $xml = simplexml_load_string((string) file_get_contents($path));
+
+ if ($xml === false) {
+ return [];
+ }
+
+ $files = [];
+
+ foreach ($xml->xpath('//testcase') ?: [] as $case) {
+ $files[(string) $case['name']] = (string) $case['file'];
+ }
+
+ return $files;
+}
+
+function removeRequiredProject(string $root): void
+{
+ if (! is_dir($root)) {
+ return;
+ }
+
+ $items = new RecursiveIteratorIterator(
+ new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
+ RecursiveIteratorIterator::CHILD_FIRST,
+ );
+
+ foreach ($items as $item) {
+ if ($item->isDir() && ! $item->isLink()) {
+ rmdir($item->getPathname());
+
+ continue;
+ }
+
+ unlink($item->getPathname());
+ }
+
+ rmdir($root);
+}
diff --git a/tests/Unit/Support/Backtrace.php b/tests/Unit/Support/Backtrace.php
index 0e04a6787..f3b6f3ec0 100644
--- a/tests/Unit/Support/Backtrace.php
+++ b/tests/Unit/Support/Backtrace.php
@@ -7,3 +7,13 @@
expect($a())->toBe(__FILE__);
});
+
+it('attributes the call site to this file', function (): void {
+ expect(Backtrace::testFile())->toBe(__FILE__)
+ ->and(backtrace_helper_calls_test_file())->toBe(__FILE__);
+});
+
+function backtrace_helper_calls_test_file(): string
+{
+ return Backtrace::testFile();
+}