Skip to content

Commit fd17091

Browse files
committed
feat: boot the orchestrated application outside PHPUnit
1 parent d4da78c commit fd17091

5 files changed

Lines changed: 521 additions & 29 deletions

File tree

‎docs/testing/packages.md‎

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

6464
- `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.
6565
- `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.
66-
- `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.
66+
- `getFrameworkPath()` returns the framework that the skeleton is copied from, which is the one that provides the orchestrator.
6767
- `afterBuild()` runs when the skeleton is complete, for example to create a database.
68-
- `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`.
68+
- `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`.
6969

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

7373
!!! note "Note"
7474
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()`.
@@ -94,6 +94,47 @@ Point `bootstrap` at this file in your **phpunit.dist.xml**. Since it replaces C
9494
!!! important "Important"
9595
The path constants and the framework's static state last for the whole process, so one process hosts one skeleton.
9696

97+
`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:
98+
99+
```php
100+
$orchestrator->build();
101+
102+
foreach ($orchestrator->getPathConstants() as $name => $value) {
103+
defined($name) || define($name, $value);
104+
}
105+
106+
require $orchestrator->getFrameworkPath() . '/system/Test/bootstrap.php';
107+
```
108+
109+
## Booting Outside PHPUnit
110+
111+
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:
112+
113+
```php
114+
<?php
115+
116+
// bin/blog
117+
118+
use Acme\Blog\Tests\BlogOrchestrator;
119+
120+
require_once __DIR__ . '/../vendor/autoload.php';
121+
122+
(new BlogOrchestrator())->bootConsole();
123+
```
124+
125+
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:
126+
127+
```php
128+
(new BlogOrchestrator())->bootConsole(rebuild: true);
129+
```
130+
131+
The environment is read from `CI_ENVIRONMENT`, as set in the skeleton's **.env** unless the process already defines it, 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.
132+
133+
!!! note "Note"
134+
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()`.
135+
136+
After `bootConsole()`, the instance keeps addressing the console skeleton, and `boot()` on it throws an exception.
137+
97138
## Testing Through spark
98139

99140
`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: 115 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace CodeIgniter\Test\Orchestrator;
1515

16+
use CodeIgniter\Config\DotEnv;
1617
use CodeIgniter\Exceptions\RuntimeException;
1718
use FilesystemIterator;
1819
use RecursiveDirectoryIterator;
@@ -28,10 +29,17 @@ abstract class AbstractOrchestrator
2829
*/
2930
private const KILL_GRACE_PERIOD = 2.0;
3031

32+
private const BUILT_MARKER = '.orchestrator-built';
33+
34+
private bool $console = false;
35+
3136
/**
32-
* Absolute path of the skeleton, suffixed with `ORCHESTRATOR_TEST_TOKEN`, or else a valid `TEST_TOKEN`, so parallel runs do not collide.
37+
* Absolute path of the skeleton, which is `getSkeletonPath()` followed by:
38+
*
39+
* - `.console` after `bootConsole()`
40+
* - `-` and `ORCHESTRATOR_TEST_TOKEN`, or else a valid `TEST_TOKEN`, so parallel runs do not collide
3341
*/
34-
public function getPath(): string
42+
final public function getPath(): string
3543
{
3644
$token = getenv('ORCHESTRATOR_TEST_TOKEN');
3745

@@ -47,8 +55,9 @@ public function getPath(): string
4755
}
4856

4957
return sprintf(
50-
'%s/build/orchestrator%s',
51-
rtrim($this->getPackageRoot(), '\\/'),
58+
'%s%s%s',
59+
rtrim($this->getSkeletonPath(), '\\/'),
60+
$this->console ? '.console' : '',
5261
is_string($token) && $token !== '' ? '-' . $token : '',
5362
);
5463
}
@@ -64,12 +73,14 @@ final public function build(): void
6473
require_once $framework . '/system/Helpers/filesystem_helper.php';
6574

6675
$this->ensureUnlinkedAncestors();
76+
$this->removePath($path . '/' . self::BUILT_MARKER);
6777
$this->removePath($path);
6878

69-
foreach (['app', 'public', 'writable'] as $directory) {
79+
foreach (['app', 'public'] as $directory) {
7080
directory_mirror($framework . '/' . $directory, $path . '/' . $directory);
7181
}
7282

83+
$this->mirrorWritable($framework . '/writable', $path . '/writable');
7384
$this->failUnless(copy($framework . '/spark', $path . '/spark'), 'copy spark');
7485
$this->writeAutoloader();
7586
$this->writeEnv();
@@ -80,6 +91,8 @@ final public function build(): void
8091

8192
$this->pointPathsAtTheFramework();
8293
$this->afterBuild();
94+
95+
$this->failUnless(touch($path . '/' . self::BUILT_MARKER), 'mark the build complete');
8396
}
8497

8598
/**
@@ -89,9 +102,51 @@ final public function build(): void
89102
*/
90103
final public function boot(): void
91104
{
105+
if ($this->console) {
106+
throw new RuntimeException('Cannot call boot() after bootConsole().');
107+
}
108+
92109
$this->build();
110+
$this->defineConstants();
111+
112+
require $this->getFrameworkPath() . '/system/Test/bootstrap.php';
113+
}
114+
115+
/**
116+
* Boots the framework in this process through **system/util_bootstrap.php** against its own skeleton.
117+
*
118+
* `getEnv()` and `afterBuild()` run only when the skeleton is incomplete or `$rebuild` is true.
119+
*/
120+
final public function bootConsole(bool $rebuild = false): void
121+
{
122+
$this->console = true;
123+
124+
if ($rebuild || ! is_file($this->getPath() . '/' . self::BUILT_MARKER)) {
125+
$this->build();
126+
}
127+
128+
require_once $this->getFrameworkPath() . '/system/Config/DotEnv.php';
129+
(new DotEnv($this->getPath()))->load();
130+
131+
$this->defineConstants();
93132

94-
$path = realpath($this->getPath()) . DIRECTORY_SEPARATOR;
133+
require $this->getFrameworkPath() . '/system/util_bootstrap.php';
134+
}
135+
136+
/**
137+
* Path constants of the built skeleton and the package, keyed by name.
138+
*
139+
* @return array<string, string>
140+
*/
141+
public function getPathConstants(): array
142+
{
143+
$path = $this->getRealRoot();
144+
145+
if ($path === '') {
146+
throw new RuntimeException('Cannot read the path constants before the orchestrated application is built.');
147+
}
148+
149+
$path .= DIRECTORY_SEPARATOR;
95150
$testPath = rtrim($this->getPackageRoot(), '\\/') . '/tests' . DIRECTORY_SEPARATOR;
96151
$constants = [
97152
'HOMEPATH' => $path,
@@ -104,13 +159,7 @@ final public function boot(): void
104159
$constants['SUPPORTPATH'] = $testPath . '_support' . DIRECTORY_SEPARATOR;
105160
}
106161

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';
162+
return $constants;
114163
}
115164

116165
/**
@@ -206,11 +255,27 @@ final public function clean(): void
206255
$this->removePath($this->getPath());
207256
}
208257

258+
/**
259+
* Absolute path of the framework that the skeleton is copied from.
260+
*/
261+
public function getFrameworkPath(): string
262+
{
263+
return dirname(__DIR__, 3);
264+
}
265+
209266
/**
210267
* Absolute path of the package under test, the directory holding its `vendor/autoload.php`.
211268
*/
212269
abstract protected function getPackageRoot(): string;
213270

271+
/**
272+
* Absolute path of the skeleton before the suffixes added by `getPath()`.
273+
*/
274+
protected function getSkeletonPath(): string
275+
{
276+
return rtrim($this->getPackageRoot(), '\\/') . '/build/orchestrator';
277+
}
278+
214279
/**
215280
* Absolute paths of directories mirrored onto the skeleton, in order, after the framework files.
216281
*
@@ -238,12 +303,13 @@ protected function afterBuild(): void
238303
{
239304
}
240305

241-
/**
242-
* Absolute path of the framework that the skeleton is copied from.
243-
*/
244-
protected function getFrameworkPath(): string
306+
private function defineConstants(): void
245307
{
246-
return dirname(__DIR__, 3);
308+
foreach ($this->getPathConstants() as $name => $value) {
309+
if (! defined($name)) {
310+
define($name, $value);
311+
}
312+
}
247313
}
248314

249315
private function isValidToken(string $token): bool
@@ -395,6 +461,33 @@ private function wait(mixed $process, ?float $timeout): array
395461
return [$exitCode, $timedOut];
396462
}
397463

464+
private function mirrorWritable(string $origin, string $target): void
465+
{
466+
$this->failUnless(is_dir($target) || mkdir($target, 0755, true), 'create writable');
467+
468+
foreach (['index.html', '.htaccess'] as $file) {
469+
if (is_file($origin . '/' . $file)) {
470+
$this->failUnless(copy($origin . '/' . $file, $target . '/' . $file), sprintf('copy writable/%s', $file));
471+
}
472+
}
473+
474+
$entries = scandir($origin);
475+
476+
$this->failUnless($entries !== false, 'read writable');
477+
478+
foreach (array_diff($entries, ['.', '..']) as $directory) {
479+
if (! is_file($origin . '/' . $directory . '/index.html')) {
480+
continue;
481+
}
482+
483+
$this->failUnless(mkdir($target . '/' . $directory, 0755), sprintf('create writable/%s', $directory));
484+
$this->failUnless(
485+
copy($origin . '/' . $directory . '/index.html', $target . '/' . $directory . '/index.html'),
486+
sprintf('copy writable/%s/index.html', $directory),
487+
);
488+
}
489+
}
490+
398491
private function pointPathsAtTheFramework(): void
399492
{
400493
$paths = $this->getPath() . '/app/Config/Paths.php';
@@ -405,7 +498,7 @@ private function pointPathsAtTheFramework(): void
405498
$rewritten = str_replace(
406499
"__DIR__ . '/../../system'",
407500
var_export($this->getFrameworkPath() . '/system', true),
408-
(string) $contents,
501+
$contents,
409502
$count,
410503
);
411504

@@ -446,6 +539,9 @@ private function writeEnv(): void
446539
$this->failUnless(write_file($this->getPath() . '/.env', $contents), 'write .env');
447540
}
448541

542+
/**
543+
* @phpstan-assert true $succeeded
544+
*/
449545
private function failUnless(bool $succeeded, string $step): void
450546
{
451547
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)