Skip to content

Commit e1e6b88

Browse files
committed
feat: boot the orchestrated application outside PHPUnit
1 parent e189032 commit e1e6b88

5 files changed

Lines changed: 388 additions & 29 deletions

File tree

‎docs/testing/packages.md‎

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,12 @@ The following methods can be overridden:
5959

6060
- `getFixtures()` returns a list of directories that are mirrored onto the root of the skeleton, in order, after the framework files. A later directory overwrites an earlier one. Use them to add controllers, routes, configuration or a `Registrar`, for example **Fixtures/app/Config/Routes.php**. A fixture **app/Config/Paths.php** must keep the default `$systemDirectory`, which `build()` then points at the framework.
6161
- `getEnv()` returns settings for the skeleton's **.env** file. Values are quoted, so they may contain spaces, `#` and quotes, but a value with a line break is refused. Names may only contain letters, digits, `.`, `_`, `-` and `\`, which covers forms such as `app.baseURL` and `Config\App.baseURL`. `CI_ENVIRONMENT` defaults to `development`, because `spark` does not run in the `testing` environment.
62-
- `getFrameworkPath()` returns the framework that the skeleton is copied from, which is the one that provides the orchestrator. Expose it from your subclass if your tests need the framework's location.
62+
- `getFrameworkPath()` returns the framework that the skeleton is copied from, which is the one that provides the orchestrator.
6363
- `afterBuild()` runs when the skeleton is complete, for example to create a database.
64-
- `getPath()` returns the skeleton's location, **build/orchestrator** in the package root by default. A token is appended to it so that parallel processes do not share a skeleton. The token is read from `ORCHESTRATOR_TEST_TOKEN`, or else from `TEST_TOKEN`, which parallel runners such as ParaTest set for each process. It may only contain letters, digits, hyphens and underscores: an invalid `ORCHESTRATOR_TEST_TOKEN` throws an exception, and an invalid `TEST_TOKEN` is ignored. Set `ORCHESTRATOR_TEST_TOKEN` to an empty string to opt out of `TEST_TOKEN`.
64+
- `getSkeletonPath()` returns the skeleton's location, **build/orchestrator** in the package root by default. `getPath()` appends `-console` to it after `bootConsole()`, and then a token so that parallel processes do not share a skeleton. The token is read from `ORCHESTRATOR_TEST_TOKEN`, or else from `TEST_TOKEN`, which parallel runners such as ParaTest set for each process. It may only contain letters, digits, hyphens and underscores: an invalid `ORCHESTRATOR_TEST_TOKEN` throws an exception, and an invalid `TEST_TOKEN` is ignored. Set `ORCHESTRATOR_TEST_TOKEN` to an empty string to opt out of `TEST_TOKEN`.
6565

6666
!!! note "Note"
67-
The skeleton is generated, so add its location to your **.gitignore**, which is **build/** unless `getPath()` is overridden.
67+
The skeleton is generated, so add its location to your **.gitignore**, which is **build/** unless `getSkeletonPath()` is overridden.
6868

6969
!!! note "Note"
7070
The skeleton is copied from the framework installed with your package, so only that version is tested. To build it from another version, keep a copy of that framework in a separate directory and return its path from `getFrameworkPath()`.
@@ -90,6 +90,47 @@ Point `bootstrap` at this file in your **phpunit.dist.xml**. Since it replaces C
9090
!!! important "Important"
9191
The path constants and the framework's static state last for the whole process, so one process hosts one skeleton.
9292

93+
`getPathConstants()` returns the constants that `boot()` defines, keyed by name: `HOMEPATH`, `CONFIGPATH` and `PUBLICPATH` for the skeleton, and `TESTPATH` and, when **tests/_support** exists, `SUPPORTPATH` for the package. Call it after `build()`. Use it with `getFrameworkPath()` to load another bootstrap file against the skeleton:
94+
95+
```php
96+
$orchestrator->build();
97+
98+
foreach ($orchestrator->getPathConstants() as $name => $value) {
99+
defined($name) || define($name, $value);
100+
}
101+
102+
require $orchestrator->getFrameworkPath() . '/system/Test/bootstrap.php';
103+
```
104+
105+
## Booting Outside PHPUnit
106+
107+
Code that runs outside PHPUnit, such as a package script or a static analysis bootstrap file, can call `bootConsole()` to use the framework's functions and services, like `env()`, `helper()` and `service()`. It loads the framework's **system/util_bootstrap.php** against a skeleton of its own, in **build/orchestrator-console** by default, so that it does not share a skeleton with a running test suite:
108+
109+
```php
110+
<?php
111+
112+
// bin/blog
113+
114+
use Acme\Blog\Tests\BlogOrchestrator;
115+
116+
require_once __DIR__ . '/../vendor/autoload.php';
117+
118+
(new BlogOrchestrator())->bootConsole();
119+
```
120+
121+
Unlike `boot()`, it builds the skeleton only when it is missing or a previous build did not finish. A reused skeleton skips `getEnv()` and `afterBuild()`, so work in those hooks must tolerate being skipped. Pass `rebuild: true` to rebuild it after changing your fixtures or updating the framework, since `build()` called before `bootConsole()` rebuilds the PHPUnit skeleton instead, and called after it, changes files that are already loaded:
122+
123+
```php
124+
(new BlogOrchestrator())->bootConsole(rebuild: true);
125+
```
126+
127+
The environment is read from `CI_ENVIRONMENT`, `development` by default, a `CLIRequest` is created, and the routes are loaded, as with **spark**. Routes are loaded last, so an error in a route file is thrown from `bootConsole()`. The test helpers of **system/Test/bootstrap.php**, like the mocked `is_cli()`, are not loaded.
128+
129+
!!! note "Note"
130+
Processes that boot at the same time share **build/orchestrator-console**, so a build in one removes the skeleton in use by the other. Give each tool its own `ORCHESTRATOR_TEST_TOKEN`, as described under `getSkeletonPath()`.
131+
132+
After `bootConsole()`, the instance keeps addressing the console skeleton, and `boot()` on it throws an exception.
133+
93134
## Testing Through spark
94135

95136
`spark()` runs the skeleton's **spark** in a separate process and returns a `SparkResult` with the `exitCode`, `stdout`, `stderr` and `timedOut` properties:

‎system/Test/Orchestrator/AbstractOrchestrator.php‎

Lines changed: 110 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,17 @@ abstract class AbstractOrchestrator
2828
*/
2929
private const KILL_GRACE_PERIOD = 2.0;
3030

31+
private const BUILT_MARKER = '.orchestrator-built';
32+
33+
private bool $console = false;
34+
3135
/**
32-
* Absolute path of the skeleton, suffixed with `ORCHESTRATOR_TEST_TOKEN`, or else a valid `TEST_TOKEN`, so parallel runs do not collide.
36+
* Absolute path of the skeleton, which is `getSkeletonPath()` followed by:
37+
*
38+
* - `-console` after `bootConsole()`
39+
* - `-` and `ORCHESTRATOR_TEST_TOKEN`, or else a valid `TEST_TOKEN`, so parallel runs do not collide
3340
*/
34-
public function getPath(): string
41+
final public function getPath(): string
3542
{
3643
$token = getenv('ORCHESTRATOR_TEST_TOKEN');
3744

@@ -47,8 +54,9 @@ public function getPath(): string
4754
}
4855

4956
return sprintf(
50-
'%s/build/orchestrator%s',
51-
rtrim($this->getPackageRoot(), '\\/'),
57+
'%s%s%s',
58+
rtrim($this->getSkeletonPath(), '\\/'),
59+
$this->console ? '-console' : '',
5260
is_string($token) && $token !== '' ? '-' . $token : '',
5361
);
5462
}
@@ -66,10 +74,11 @@ final public function build(): void
6674
$this->ensureUnlinkedAncestors();
6775
$this->removePath($path);
6876

69-
foreach (['app', 'public', 'writable'] as $directory) {
77+
foreach (['app', 'public'] as $directory) {
7078
directory_mirror($framework . '/' . $directory, $path . '/' . $directory);
7179
}
7280

81+
$this->mirrorWritable($framework . '/writable', $path . '/writable');
7382
$this->failUnless(copy($framework . '/spark', $path . '/spark'), 'copy spark');
7483
$this->writeAutoloader();
7584
$this->writeEnv();
@@ -80,6 +89,8 @@ final public function build(): void
8089

8190
$this->pointPathsAtTheFramework();
8291
$this->afterBuild();
92+
93+
$this->failUnless(touch($path . '/' . self::BUILT_MARKER), 'mark the build complete');
8394
}
8495

8596
/**
@@ -89,9 +100,48 @@ final public function build(): void
89100
*/
90101
final public function boot(): void
91102
{
103+
if ($this->console) {
104+
throw new RuntimeException('Cannot call boot() after bootConsole().');
105+
}
106+
92107
$this->build();
108+
$this->defineConstants();
109+
110+
require $this->getFrameworkPath() . '/system/Test/bootstrap.php';
111+
}
112+
113+
/**
114+
* Boots the framework in this process through **system/util_bootstrap.php** against its own skeleton.
115+
*
116+
* `getEnv()` and `afterBuild()` run only when the skeleton is incomplete or `$rebuild` is true.
117+
*/
118+
final public function bootConsole(bool $rebuild = false): void
119+
{
120+
$this->console = true;
121+
122+
if ($rebuild || ! is_file($this->getPath() . '/' . self::BUILT_MARKER)) {
123+
$this->build();
124+
}
125+
126+
$this->defineConstants();
93127

94-
$path = realpath($this->getPath()) . DIRECTORY_SEPARATOR;
128+
require $this->getFrameworkPath() . '/system/util_bootstrap.php';
129+
}
130+
131+
/**
132+
* Path constants of the built skeleton and the package, keyed by name.
133+
*
134+
* @return array<string, string>
135+
*/
136+
public function getPathConstants(): array
137+
{
138+
$path = $this->getRealRoot();
139+
140+
if ($path === '') {
141+
throw new RuntimeException('Cannot read the path constants before the orchestrated application is built.');
142+
}
143+
144+
$path .= DIRECTORY_SEPARATOR;
95145
$testPath = rtrim($this->getPackageRoot(), '\\/') . '/tests' . DIRECTORY_SEPARATOR;
96146
$constants = [
97147
'HOMEPATH' => $path,
@@ -104,13 +154,7 @@ final public function boot(): void
104154
$constants['SUPPORTPATH'] = $testPath . '_support' . DIRECTORY_SEPARATOR;
105155
}
106156

107-
foreach ($constants as $name => $value) {
108-
if (! defined($name)) {
109-
define($name, $value);
110-
}
111-
}
112-
113-
require $this->getFrameworkPath() . '/system/Test/bootstrap.php';
157+
return $constants;
114158
}
115159

116160
/**
@@ -206,11 +250,27 @@ final public function clean(): void
206250
$this->removePath($this->getPath());
207251
}
208252

253+
/**
254+
* Absolute path of the framework that the skeleton is copied from.
255+
*/
256+
public function getFrameworkPath(): string
257+
{
258+
return dirname(__DIR__, 3);
259+
}
260+
209261
/**
210262
* Absolute path of the package under test, the directory holding its `vendor/autoload.php`.
211263
*/
212264
abstract protected function getPackageRoot(): string;
213265

266+
/**
267+
* Absolute path of the skeleton before the suffixes added by `getPath()`.
268+
*/
269+
protected function getSkeletonPath(): string
270+
{
271+
return rtrim($this->getPackageRoot(), '\\/') . '/build/orchestrator';
272+
}
273+
214274
/**
215275
* Absolute paths of directories mirrored onto the skeleton, in order, after the framework files.
216276
*
@@ -238,12 +298,13 @@ protected function afterBuild(): void
238298
{
239299
}
240300

241-
/**
242-
* Absolute path of the framework that the skeleton is copied from.
243-
*/
244-
protected function getFrameworkPath(): string
301+
private function defineConstants(): void
245302
{
246-
return dirname(__DIR__, 3);
303+
foreach ($this->getPathConstants() as $name => $value) {
304+
if (! defined($name)) {
305+
define($name, $value);
306+
}
307+
}
247308
}
248309

249310
private function isValidToken(string $token): bool
@@ -395,6 +456,33 @@ private function wait(mixed $process, ?float $timeout): array
395456
return [$exitCode, $timedOut];
396457
}
397458

459+
private function mirrorWritable(string $origin, string $target): void
460+
{
461+
$this->failUnless(is_dir($target) || mkdir($target, 0755, true), 'create writable');
462+
463+
foreach (['index.html', '.htaccess'] as $file) {
464+
if (is_file($origin . '/' . $file)) {
465+
$this->failUnless(copy($origin . '/' . $file, $target . '/' . $file), sprintf('copy writable/%s', $file));
466+
}
467+
}
468+
469+
$entries = scandir($origin);
470+
471+
$this->failUnless($entries !== false, 'read writable');
472+
473+
foreach (array_diff($entries, ['.', '..']) as $directory) {
474+
if (! is_file($origin . '/' . $directory . '/index.html')) {
475+
continue;
476+
}
477+
478+
$this->failUnless(mkdir($target . '/' . $directory, 0755), sprintf('create writable/%s', $directory));
479+
$this->failUnless(
480+
copy($origin . '/' . $directory . '/index.html', $target . '/' . $directory . '/index.html'),
481+
sprintf('copy writable/%s/index.html', $directory),
482+
);
483+
}
484+
}
485+
398486
private function pointPathsAtTheFramework(): void
399487
{
400488
$paths = $this->getPath() . '/app/Config/Paths.php';
@@ -405,7 +493,7 @@ private function pointPathsAtTheFramework(): void
405493
$rewritten = str_replace(
406494
"__DIR__ . '/../../system'",
407495
var_export($this->getFrameworkPath() . '/system', true),
408-
(string) $contents,
496+
$contents,
409497
$count,
410498
);
411499

@@ -446,6 +534,9 @@ private function writeEnv(): void
446534
$this->failUnless(write_file($this->getPath() . '/.env', $contents), 'write .env');
447535
}
448536

537+
/**
538+
* @phpstan-assert true $succeeded
539+
*/
449540
private function failUnless(bool $succeeded, string $step): void
450541
{
451542
if (! $succeeded) {

‎system/util_bootstrap.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@
6565
}
6666

6767
if (is_dir(HOMEPATH . 'vendor/')) {
68-
define('VENDORPATH', realpath(HOMEPATH . 'vendor/') . DIRECTORY_SEPARATOR);
69-
define('COMPOSER_PATH', (string) realpath(HOMEPATH . 'vendor/autoload.php'));
68+
defined('VENDORPATH') || define('VENDORPATH', realpath(HOMEPATH . 'vendor/') . DIRECTORY_SEPARATOR);
69+
defined('COMPOSER_PATH') || define('COMPOSER_PATH', (string) realpath(HOMEPATH . 'vendor/autoload.php'));
7070
}
7171

7272
/*

‎tests/_support/Orchestrator/OrchestratorStub.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ public function __construct(
3131
) {
3232
}
3333

34-
public function getPath(): string
34+
protected function getSkeletonPath(): string
3535
{
36-
return $this->skeleton !== '' ? $this->skeleton : parent::getPath();
36+
return $this->skeleton !== '' ? $this->skeleton : parent::getSkeletonPath();
3737
}
3838

3939
protected function getPackageRoot(): string

0 commit comments

Comments
 (0)