-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestsCommand.php
More file actions
301 lines (258 loc) · 10.9 KB
/
TestsCommand.php
File metadata and controls
301 lines (258 loc) · 10.9 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
<?php
declare(strict_types=1);
/**
* This file is part of fast-forward/dev-tools.
*
* This source file is subject to the license bundled
* with this source code in the file LICENSE.
*
* @copyright Copyright (c) 2026 Felipe Sayão Lobato Abreu <github@mentordosnerds.com>
* @license https://opensource.org/licenses/MIT MIT License
*
* @see https://github.com/php-fast-forward/dev-tools
* @see https://github.com/php-fast-forward
* @see https://datatracker.ietf.org/doc/html/rfc2119
*/
namespace FastForward\DevTools\Command;
use FastForward\DevTools\PhpUnit\Coverage\CoverageSummaryLoader;
use FastForward\DevTools\PhpUnit\Coverage\CoverageSummaryLoaderInterface;
use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
use function is_numeric;
/**
* Facilitates the execution of the PHPUnit testing framework.
* This class MUST NOT be overridden and SHALL configure testing parameters dynamically.
*/
final class TestsCommand extends AbstractCommand
{
/**
* @var string identifies the local configuration file for PHPUnit processes
*/
public const string CONFIG = 'phpunit.xml';
/**
* @param Filesystem|null $filesystem the filesystem utility used for path resolution
* @param CoverageSummaryLoaderInterface $coverageSummaryLoader the loader used for `coverage-php` summaries
*/
public function __construct(
?Filesystem $filesystem = null,
private readonly CoverageSummaryLoaderInterface $coverageSummaryLoader = new CoverageSummaryLoader(),
) {
parent::__construct($filesystem);
}
/**
* 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
->setName('tests')
->setDescription('Runs PHPUnit tests.')
->setHelp('This command runs PHPUnit to execute your tests.')
->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: 'cache-dir',
mode: InputOption::VALUE_OPTIONAL,
description: 'Path to the PHPUnit cache directory.',
default: './tmp/cache/phpunit',
)
->addOption(
name: 'no-cache',
mode: InputOption::VALUE_NONE,
description: 'Whether to disable PHPUnit caching.',
)
->addOption(
name: 'coverage',
shortcut: 'c',
mode: InputOption::VALUE_OPTIONAL,
description: 'Whether to generate code coverage reports.',
)
->addOption(
name: 'filter',
shortcut: 'f',
mode: InputOption::VALUE_OPTIONAL,
description: 'Filter which tests to run based on a pattern.',
)
->addOption(
name: 'parallel',
shortcut: 'p',
mode: InputOption::VALUE_OPTIONAL,
description: 'Run tests in parallel using ParaTest. Optional number of workers.',
)
->addOption(
name: 'min-coverage',
mode: InputOption::VALUE_REQUIRED,
description: 'Minimum line coverage percentage required for a successful run.',
);
}
/**
* 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
{
try {
$minimumCoverage = $this->resolveMinimumCoverage($input);
} catch (InvalidArgumentException $invalidArgumentException) {
$output->writeln('<error>' . $invalidArgumentException->getMessage() . '</error>');
return self::FAILURE;
}
$arguments = [
'--configuration=' . parent::getConfigFile(self::CONFIG),
'--bootstrap=' . $this->resolvePath($input, 'bootstrap'),
];
if (! $input->getOption('no-cache')) {
$arguments[] = '--cache-directory=' . $this->resolvePath($input, 'cache-dir');
}
$coverageReportPath = $this->configureCoverageArguments($input, $arguments, null !== $minimumCoverage);
if (null !== $input->getOption('filter')) {
$arguments[] = '--filter=' . $input->getOption('filter');
}
$parallel = null !== $input->getOption('parallel');
$command = $this->getAbsolutePath(\sprintf('vendor/bin/%s', $parallel ? 'paratest' : 'phpunit'));
if (! $parallel) {
$arguments[] = '--display-deprecations';
$arguments[] = '--display-phpunit-deprecations';
$arguments[] = '--display-incomplete';
$arguments[] = '--display-skipped';
} else {
$arguments[] = '--processes=' . ($input->getOption('parallel') ?: 'auto');
}
$output->writeln('<info>Running tests using ' . ($parallel ? 'ParaTest' : 'PHPUnit') . '...</info>');
$command = new Process([$command, ...$arguments, $input->getArgument('path')]);
$result = parent::runProcess($command, $output);
if (self::SUCCESS !== $result || null === $minimumCoverage || null === $coverageReportPath) {
return $result;
}
return $this->validateMinimumCoverage($coverageReportPath, $minimumCoverage, $output);
}
/**
* 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->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 array<int, string> $arguments the mutable argument list for the PHPUnit process
* @param bool $requiresCoverageReport indicates whether a `coverage-php` report is required
*
* @return string|null the absolute path to the generated `coverage-php` report
*/
private function configureCoverageArguments(
InputInterface $input,
array &$arguments,
bool $requiresCoverageReport,
): ?string {
$coverageOption = $input->getOption('coverage');
if (null === $coverageOption && ! $requiresCoverageReport) {
return null;
}
$coveragePath = null !== $coverageOption
? $this->resolvePath($input, 'coverage')
: $this->resolvePath($input, 'cache-dir');
foreach ($this->getPsr4Namespaces() as $path) {
$arguments[] = '--coverage-filter=' . $this->getAbsolutePath($path);
}
if (null !== $coverageOption) {
$arguments[] = '--coverage-text';
$arguments[] = '--coverage-html=' . $coveragePath;
$arguments[] = '--testdox-html=' . $coveragePath . '/testdox.html';
$arguments[] = '--coverage-clover=' . $coveragePath . '/clover.xml';
}
$coverageReportPath = $coveragePath . '/coverage.php';
$arguments[] = '--coverage-php=' . $coverageReportPath;
return $coverageReportPath;
}
/**
* @param string $coverageReportPath the generated `coverage-php` report path
* @param float $minimumCoverage the required line coverage percentage
* @param OutputInterface $output the output interface to log validation results
*
* @return int the final status code after validating minimum coverage
*/
private function validateMinimumCoverage(
string $coverageReportPath,
float $minimumCoverage,
OutputInterface $output,
): int {
try {
$coverageSummary = $this->coverageSummaryLoader->load($coverageReportPath);
} catch (RuntimeException $runtimeException) {
$output->writeln('<error>' . $runtimeException->getMessage() . '</error>');
return self::FAILURE;
}
$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(),
);
if ($coverageSummary->percentage() >= $minimumCoverage) {
$output->writeln('<info>' . $message . '</info>');
return self::SUCCESS;
}
$output->writeln('<error>' . $message . '</error>');
return self::FAILURE;
}
}