-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestsCommand.php
More file actions
379 lines (337 loc) · 14.5 KB
/
TestsCommand.php
File metadata and controls
379 lines (337 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<?php
declare(strict_types=1);
/**
* Fast Forward Development Tools for PHP projects.
*
* This file is part of fast-forward/dev-tools project.
*
* @author Felipe Sayão Lobato Abreu <github@mentordosnerds.com>
* @license https://opensource.org/licenses/MIT MIT License
*
* @see https://github.com/php-fast-forward/
* @see https://github.com/php-fast-forward/dev-tools
* @see https://github.com/php-fast-forward/dev-tools/issues
* @see https://php-fast-forward.github.io/dev-tools/
* @see https://datatracker.ietf.org/doc/html/rfc2119
*/
namespace FastForward\DevTools\Console\Command;
use FastForward\DevTools\Console\Command\Traits\LogsCommandResults;
use Composer\Command\BaseCommand;
use FastForward\DevTools\Console\Input\HasCacheOption;
use FastForward\DevTools\Console\Input\HasJsonOption;
use FastForward\DevTools\Composer\Json\ComposerJsonInterface;
use FastForward\DevTools\Filesystem\FilesystemInterface;
use FastForward\DevTools\PhpUnit\Coverage\CoverageSummaryLoaderInterface;
use FastForward\DevTools\Process\ProcessBuilderInterface;
use FastForward\DevTools\Process\ProcessQueueInterface;
use FastForward\DevTools\Path\ManagedWorkspace;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use function is_numeric;
/**
* Facilitates the execution of the PHPUnit testing framework.
* This class MUST NOT be overridden and SHALL configure testing parameters dynamically.
*/
#[AsCommand(name: 'tests', description: 'Runs PHPUnit tests.')]
final class TestsCommand extends BaseCommand implements LoggerAwareCommandInterface
{
use HasCacheOption;
use HasJsonOption;
use LogsCommandResults;
/**
* @var string identifies the local configuration file for PHPUnit processes
*/
public const string CONFIG = 'phpunit.xml';
/**
* @param CoverageSummaryLoaderInterface $coverageSummaryLoader the loader used for `coverage-php` summaries
* @param ComposerJsonInterface $composer the composer.json reader for autoload information
* @param FilesystemInterface $filesystem the filesystem utility used for path resolution
* @param FileLocatorInterface $fileLocator the file locator used to resolve PHPUnit configuration
* @param ProcessBuilderInterface $processBuilder the builder used to assemble the PHPUnit process
* @param ProcessQueueInterface $processQueue the queue used to execute PHPUnit
* @param LoggerInterface $logger the output-aware logger
*/
public function __construct(
private readonly CoverageSummaryLoaderInterface $coverageSummaryLoader,
private readonly ComposerJsonInterface $composer,
private readonly FilesystemInterface $filesystem,
private readonly FileLocatorInterface $fileLocator,
private readonly ProcessBuilderInterface $processBuilder,
private readonly ProcessQueueInterface $processQueue,
private readonly LoggerInterface $logger,
) {
parent::__construct();
}
/**
* Configures the testing command input constraints.
*
* The method MUST specify valid arguments for testing paths, caching directories,
* bootstrap scripts, and coverage instructions. It SHALL align with robust testing standards.
*
* @return void
*/
protected function configure(): void
{
$this->setHelp('This command runs PHPUnit to execute your tests.');
$this
->addJsonOption()
->addCacheOption('Whether to enable PHPUnit result caching.')
->addCacheDirOption(
description: 'Path to the PHPUnit cache directory.',
default: ManagedWorkspace::getCacheDirectory(ManagedWorkspace::PHPUNIT),
)
->addArgument(
name: 'path',
mode: InputArgument::OPTIONAL,
description: 'Path to the tests directory.',
default: './tests',
)
->addOption(
name: 'bootstrap',
shortcut: 'b',
mode: InputOption::VALUE_OPTIONAL,
description: 'Path to the bootstrap file.',
default: './vendor/autoload.php',
)
->addOption(
name: 'coverage',
shortcut: 'c',
mode: InputOption::VALUE_OPTIONAL,
description: 'Whether to generate code coverage reports.',
)
->addOption(
name: 'coverage-summary',
mode: InputOption::VALUE_NONE,
description: 'Whether to show only the summary for text coverage output.',
)
->addOption(
name: 'filter',
shortcut: 'f',
mode: InputOption::VALUE_OPTIONAL,
description: 'Filter which tests to run based on a pattern.',
)
->addOption(
name: 'min-coverage',
mode: InputOption::VALUE_REQUIRED,
description: 'Minimum line coverage percentage required for a successful run.',
)
->addOption(
name: 'progress',
mode: InputOption::VALUE_NONE,
description: 'Whether to enable progress output from PHPUnit.',
);
}
/**
* Triggers the PHPUnit engine based on resolved paths and settings.
*
* The method MUST assemble the necessary commands to initiate PHPUnit securely.
* It SHOULD optionally construct advanced configuration arguments such as caching and coverage.
*
* @param InputInterface $input the runtime instruction set from the CLI
* @param OutputInterface $output the console feedback relay
*
* @return int the status integer describing the termination code
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$jsonOutput = $this->isJsonOutput($input);
$processOutput = $jsonOutput ? new BufferedOutput() : $output;
$cacheEnabled = $this->isCacheEnabled($input);
$this->getLogger()
->info('Running PHPUnit tests...', [
'input' => $input,
]);
try {
$minimumCoverage = $this->resolveMinimumCoverage($input);
} catch (InvalidArgumentException $invalidArgumentException) {
return $this->failure($invalidArgumentException->getMessage(), $input, [
'output' => $processOutput,
]);
}
$processBuilder = $this->processBuilder
->withArgument('--configuration', $this->fileLocator->locate(self::CONFIG))
->withArgument('--bootstrap', $this->resolvePath($input, 'bootstrap'))
->withArgument('--display-deprecations')
->withArgument('--display-phpunit-deprecations')
->withArgument('--display-incomplete')
->withArgument('--display-skipped');
if (! $input->getOption('progress') || $jsonOutput) {
$processBuilder = $processBuilder->withArgument('--no-progress');
}
if ($cacheEnabled) {
$processBuilder = $processBuilder->withArgument(
'--cache-result',
)->withArgument('--cache-directory', $this->resolvePath($input, 'cache-dir'));
} else {
$processBuilder = $processBuilder->withArgument('--do-not-cache-result');
}
[$processBuilder, $coverageReportPath] = $this->configureCoverageArguments(
$input,
$processBuilder,
null !== $minimumCoverage,
);
if ($input->getOption('filter')) {
$processBuilder = $processBuilder->withArgument('--filter', $input->getOption('filter'));
}
$this->processQueue->add(
$processBuilder
->withArgument($input->getArgument('path'))
->build('vendor/bin/phpunit')
);
$result = $this->processQueue->run($processOutput);
if (self::SUCCESS !== $result || null === $minimumCoverage || null === $coverageReportPath) {
if (self::SUCCESS === $result) {
return $this->success(
'PHPUnit tests completed successfully.',
$input,
[
'output' => $processOutput,
],
);
}
return $this->failure('PHPUnit tests failed.', $input, [
'output' => $processOutput,
]);
}
[$validationResult, $message, $coverageContext] = $this->validateMinimumCoverage(
$coverageReportPath,
$minimumCoverage,
);
if (self::SUCCESS === $validationResult) {
return $this->success($message, $input, [
'output' => $processOutput,
...$coverageContext,
]);
}
return $this->failure($message, $input, [
'output' => $processOutput,
...$coverageContext,
]);
}
/**
* Safely constructs an absolute path tied to a defined capability option.
*
* The method MUST compute absolute properties based on the supplied input parameters.
* It SHALL strictly return a securely bounded path string.
*
* @param InputInterface $input the raw parameter definitions
* @param string $option the requested option key to resolve
*
* @return string validated absolute path string
*/
private function resolvePath(InputInterface $input, string $option): string
{
return $this->filesystem->getAbsolutePath($input->getOption($option));
}
/**
* @param InputInterface $input the raw parameter definitions
*
* @return float|null the validated minimum coverage percentage, if configured
*/
private function resolveMinimumCoverage(InputInterface $input): ?float
{
$minimumCoverage = $input->getOption('min-coverage');
if (null === $minimumCoverage) {
return null;
}
if (! is_numeric($minimumCoverage)) {
throw new InvalidArgumentException('The --min-coverage option MUST be a numeric percentage.');
}
$minimumCoverage = (float) $minimumCoverage;
if (0.0 > $minimumCoverage || 100.0 < $minimumCoverage) {
throw new InvalidArgumentException('The --min-coverage option MUST be between 0 and 100.');
}
return $minimumCoverage;
}
/**
* @param InputInterface $input the raw parameter definitions
* @param ProcessBuilderInterface $processBuilder the process builder to extend with coverage arguments
* @param bool $requiresCoverageReport indicates whether a `coverage-php` report is required
*
* @return array{ProcessBuilderInterface, string|null} the extended builder and generated `coverage-php` report path
*/
private function configureCoverageArguments(
InputInterface $input,
ProcessBuilderInterface $processBuilder,
bool $requiresCoverageReport,
): array {
$coverageOption = $input->getOption('coverage');
if (null === $coverageOption && ! $requiresCoverageReport) {
return [$processBuilder, null];
}
$coveragePath = null !== $coverageOption
? $this->resolvePath($input, 'coverage')
: (
$this->isCacheEnabled($input)
? $this->resolvePath($input, 'cache-dir')
: ManagedWorkspace::getOutputDirectory(ManagedWorkspace::COVERAGE)
);
foreach ($this->composer->getAutoload('psr-4') as $path) {
$processBuilder = $processBuilder->withArgument(
'--coverage-filter',
$this->filesystem->getAbsolutePath($path)
);
}
if (null !== $coverageOption) {
$processBuilder = $processBuilder
->withArgument('--coverage-text')
->withArgument('--coverage-html', $coveragePath)
->withArgument('--testdox-html', $coveragePath . '/testdox.html')
->withArgument('--coverage-clover', $coveragePath . '/clover.xml')
->withArgument('--log-junit', $coveragePath . '/junit.xml');
if ($input->getOption('coverage-summary')) {
$processBuilder = $processBuilder->withArgument('--only-summary-for-coverage-text');
}
}
$coverageReportPath = $coveragePath . '/coverage.php';
$processBuilder = $processBuilder->withArgument('--coverage-php', $coverageReportPath);
return [$processBuilder, $coverageReportPath];
}
/**
* @param string $coverageReportPath the generated `coverage-php` report path
* @param float $minimumCoverage the required line coverage percentage
*
* @return array{int, string, array<string, float|int|string|null>} validation result, human message, and structured coverage context
*/
private function validateMinimumCoverage(string $coverageReportPath, float $minimumCoverage): array
{
try {
$coverageSummary = $this->coverageSummaryLoader->load($coverageReportPath);
} catch (RuntimeException $runtimeException) {
return [
self::FAILURE,
$runtimeException->getMessage(),
[
'line_coverage' => null,
'covered_lines' => null,
'total_lines' => null,
],
];
}
$message = \sprintf(
'Minimum line coverage of %01.2F%% %s. Current coverage: %s (%d/%d lines).',
$minimumCoverage,
$coverageSummary->percentage() >= $minimumCoverage ? 'satisfied' : 'was not met',
$coverageSummary->percentageAsString(),
$coverageSummary->executedLines(),
$coverageSummary->executableLines(),
);
return [
$coverageSummary->percentage() >= $minimumCoverage ? self::SUCCESS : self::FAILURE,
$message,
[
'line_coverage' => $coverageSummary->percentage(),
'covered_lines' => $coverageSummary->executedLines(),
'total_lines' => $coverageSummary->executableLines(),
],
];
}
}