-
Notifications
You must be signed in to change notification settings - Fork 0
/
MakefileTestCase.php
377 lines (325 loc) · 12.7 KB
/
MakefileTestCase.php
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
<?php
declare(strict_types=1);
/*
* This file is part of the Sigwin Infra project.
*
* (c) sigwin.hr
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Sigwin\Infra\Test\Functional;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
/**
* @internal
*/
#[\PHPUnit\Framework\Attributes\CoversNothing]
#[\PHPUnit\Framework\Attributes\Medium]
abstract class MakefileTestCase extends TestCase
{
/**
* @var array<string, string>
*/
private array $help = [
'analyze' => 'Analyze the codebase',
'analyze/lighthouse' => 'Analyze built files using Lighthouse',
'build' => 'Build app for "APP_ENV" target (defaults to "prod")',
'build/dev' => 'Build app for "dev" target',
'build/prod' => 'Build app for "prod" target',
'clean' => 'Clear logs and system cache',
'dist' => 'Prepare the codebase for commit',
'help' => 'Prints this help',
'setup/filesystem' => 'Setup: filesystem (var, public/var folders)',
'setup/test' => 'Setup: create a functional test runtime',
'sh/app' => 'Run application shell',
'sh/node' => 'Run Node shell',
'sh/php' => 'Run PHP shell',
'start' => 'Start app in APP_ENV mode (defined in .env)',
'start/dev' => 'Start app in "dev" mode',
'start/prod' => 'Start app in "prod" mode',
'start/test' => 'Start app in "test" mode',
'stop' => 'Stop app',
'test' => 'Test the codebase',
'test/functional' => 'Test the codebase, functional tests',
'test/unit' => 'Test the codebase, unit tests',
'visual/reference' => 'Generate visual testing references',
];
/**
* @var array<string, string>
*/
protected array $helpOverride = [];
/**
* @param null|array<string, string> $env
*
* @return array<string, list<string>>
*/
abstract protected static function getExpectedHelpCommandsExecutionPath(?array $env = null): array;
/**
* @return list<string>
*/
abstract protected function getExpectedInitPaths(): array;
public function testMakefileExists(): void
{
self::assertFileExists(
self::getRoot().\DIRECTORY_SEPARATOR.self::getMakefilePath()
);
}
public function testMakefileHasHelp(): void
{
$actual = self::getMakefileHelp();
$expected = $this->getExpectedHelp();
if (\PHP_OS_FAMILY === 'Windows') {
$expected = preg_replace('/\r\n|\r|\n/', "\n", self::stripColoring($expected));
}
self::assertSame($expected, $actual);
}
public function testHelpIsTheDefaultCommand(): void
{
$expected = self::dryRun('help');
$actual = self::dryRun();
self::assertSame($expected, $actual);
}
public function testMakefileHasInit(): void
{
$expected = array_map(static fn (string $path): string => \sprintf('if [ -d "$ROOT/resources/%1$s" ]; then cp -a $ROOT/resources/%1$s/. .; fi', $path), $this->getExpectedInitPaths());
$expected = array_merge(...array_map(static fn ($value) => [$value, 'if [ -f .gitattributes.dist ]; then mv .gitattributes.dist .gitattributes; fi'], $expected));
$actual = self::dryRun('init');
self::assertSame($expected, $actual);
}
/**
* @param list<string> $expected
* @param array<string, string> $env
*/
#[\PHPUnit\Framework\Attributes\DataProvider('provideMakefileCommandsWorkCases')]
public function testMakefileCommandsWork(string $command, array $expected, array $env): void
{
$actual = self::dryRun($command, env: $env);
self::assertSame($expected, $actual);
}
/**
* @return iterable<array<string, string>>
*/
protected static function getEnvs(): iterable
{
yield [];
}
protected function getExpectedHelp(): string
{
return $this->generateHelpList(array_keys(static::getExpectedHelpCommandsExecutionPath([])));
}
/**
* @param list<string> $commands
*/
protected function generateHelpList(array $commands): string
{
$help = [];
sort($commands);
foreach ($commands as $command) {
$help[] = \sprintf('%1$s[45m%2$s%1$s[0m %3$s', "\e", mb_str_pad($command, 20), $this->helpOverride[$command] ?? $this->help[$command] ?? '');
}
return implode("\n", $help)."\n";
}
/**
* @param list<string> $files
* @param list<string> $additionalFiles
*/
protected static function generateHelpExecutionPath(array $files = [], array $additionalFiles = []): string
{
$files = array_merge($files, [
__DIR__.'/../../resources/Common/default.mk',
__DIR__.'/../../resources/Common/Platform/'.\PHP_OS_FAMILY.'/default.mk',
]);
$files = array_map('realpath', $files);
$files = array_merge($files, $additionalFiles);
$command = match (\PHP_OS_FAMILY) {
'Darwin' => 'grep --no-filename --extended-regexp \'^ *[-a-zA-Z0-9_/]+ *:.*## \' '.implode(' ', $files).' | awk \'BEGIN {FS = ":.*?## "}; {printf "\033[45m%-20s\033[0m %s\n", $1, $2}\' | sort',
'Linux' => 'grep -h -E \'^ *[-a-zA-Z0-9_/]+ *:.*## \' '.implode(' ', $files).' | awk \'BEGIN {FS = ":.*?## "}; {printf "\033[45m%-20s\033[0m %s\n", $1, $2}\' | sort',
'Windows' => 'Select-String -Pattern \'^ *(?<name>[-a-zA-Z0-9_/]+) *:.*## *(?<help>.+)\' '.implode(',', array_map(static function (false|string $item, int $index): string {
if ($item === false) {
throw new \LogicException('Invalid item');
}
if ($index === 0) {
return $item;
}
return str_replace('$ROOT/resources', '$ROOT\resources', str_replace('\\', '/', self::normalize($item)));
}, $files, array_keys($files))).' | Sort-Object {$_.Matches[0].Groups["name"]} | ForEach-Object{"{0, -20}" -f $_.Matches[0].Groups["name"] | Write-Host -NoNewline -BackgroundColor Magenta -ForegroundColor White; " {0}" -f $_.Matches[0].Groups["help"] | Write-Host -ForegroundColor White}',
default => throw new \LogicException('Unknown OS family'),
};
return self::normalize($command);
}
/**
* @param list<string> $dirs
*
* @return list<string>
*/
protected static function generatePermissionsExecutionPath(array $dirs): array
{
$commands = [];
foreach ($dirs as $dir) {
$commands[] = \sprintf('mkdir -p %1$s', $dir);
if (\PHP_OS_FAMILY === 'Linux') {
$commands[] = \sprintf('setfacl -dRm m:rwX %1$s', $dir);
$commands[] = \sprintf('setfacl -Rm m:rwX %1$s', $dir);
$commands[] = \sprintf('setfacl -dRm u:`whoami`:rwX %1$s', $dir);
$commands[] = \sprintf('setfacl -Rm u:`whoami`:rwX %1$s', $dir);
$commands[] = \sprintf('setfacl -dRm u:999:rwX %1$s', $dir);
$commands[] = \sprintf('setfacl -Rm u:999:rwX %1$s', $dir);
$commands[] = \sprintf('setfacl -dRm u:root:rwX %1$s', $dir);
$commands[] = \sprintf('setfacl -Rm u:root:rwX %1$s', $dir);
}
}
return $commands;
}
/**
* @return iterable<array-key, array{string, list<string>, array<string, string>}>
*
* @psalm-suppress PossiblyUnusedMethod false positive
*/
public static function provideMakefileCommandsWorkCases(): iterable
{
$commands = self::getMakefileHelpCommands();
$envs = self::getEnvs();
foreach ($envs as $env) {
$expected = static::getExpectedHelpCommandsExecutionPath($env);
foreach ($commands as $command) {
self::assertArrayHasKey($command, $expected, \sprintf('No expected execution path defined for command "%1$s"', $command));
}
foreach ($expected as $command => $path) {
yield [$command, $path, $env];
}
}
}
protected static function getMakefilePath(): string
{
$path = str_replace([__NAMESPACE__.'\\', '\\'], ['', \DIRECTORY_SEPARATOR], static::class);
$dir = pathinfo($path, \PATHINFO_DIRNAME);
$name = pathinfo($path, \PATHINFO_FILENAME);
if (! str_ends_with($name, 'Test')) {
throw new \LogicException('Invalid test class name, expected to end with "Test"');
}
$name = mb_substr($name, 0, -4);
return \sprintf('resources%2$s%1$s%2$s%3$s.mk', $dir, \DIRECTORY_SEPARATOR, mb_strtolower($name));
}
/**
* @param list<string> $args
* @param null|array<string, int|string> $env
*
* @return list<string>
*
* @psalm-suppress MoreSpecificReturnType
* @psalm-suppress LessSpecificReturnStatement
*/
protected static function dryRun(
?string $makeCommand = null,
?array $args = null,
?array $env = null,
?string $makefile = null,
string $directory = __DIR__.'/../..',
): array {
$args[] = '--dry-run';
return array_filter(explode("\n", self::execute($makeCommand, $args, $env, $makefile, $directory)));
}
/**
* @param list<string> $args
* @param null|array<string, int|string> $env
*/
protected static function execute(
?string $command = null,
?array $args = null,
?array $env = null,
?string $makefile = null,
string $directory = __DIR__.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'..',
): string {
$makefile = str_replace('/', \DIRECTORY_SEPARATOR, $makefile ?? self::getMakefilePath());
$fullCommand = ['make', '-f', self::getRoot().\DIRECTORY_SEPARATOR.ltrim($makefile, '/\\')];
if ($args !== null) {
array_push($fullCommand, ...$args);
}
if ($command !== null) {
$fullCommand[] = $command;
}
/** @var string $directory */
$directory = realpath($directory);
$process = new Process(
$fullCommand,
$directory,
array_replace([
'HOME' => '/home/user',
'SIGWIN_INFRA_ROOT' => self::getRoot().\DIRECTORY_SEPARATOR.'resources',
// streamline these to ensure consistent runtime environment
'RUNNER' => '999',
'APP_ENV' => 'env',
'APP_ROOT' => self::getRoot(),
'PHP_VERSION' => '',
'GITHUB_ACTIONS' => '',
'COMPOSE_PROJECT_NAME' => 'infra',
'PIMCORE_KERNEL_CLASS' => 'App\Kernel',
], $env ?? []),
);
$filesystem = new Filesystem();
$filesystem->remove(__DIR__.'/../../var/phpqa');
$process->mustRun();
$output = $process->getOutput();
if (\PHP_OS_FAMILY === 'Windows') {
/** @var string $output */
$output = preg_replace('/\r\n|\r|\n/', "\n", $output);
}
return self::normalize($output);
}
private static function getMakefileHelp(): string
{
return self::execute('help');
}
/**
* @return list<string>
*/
private static function getMakefileHelpCommands(): array
{
$help = explode("\n", trim(self::stripColoring(self::getMakefileHelp())));
$commands = [];
foreach ($help as $command) {
$index = mb_strpos($command, ' ');
if ($index === false) {
throw new \LogicException('Invalid command');
}
$commands[] = mb_substr($command, 0, $index);
}
return $commands;
}
private static function getRoot(): string
{
/** @var string $root */
$root = realpath(__DIR__.'/../..');
return $root;
}
private static function stripColoring(string $input): string
{
/** @var string $output */
$output = preg_replace('/\033\[\d+m/', '', $input);
return $output;
}
protected static function normalize(string $output): string
{
return str_replace(
[
self::getRoot(),
str_replace('\\', '/', self::getRoot()),
'/home/user',
'Common/Platform/'.\PHP_OS_FAMILY,
],
[
'$ROOT',
'$ROOT',
'$HOME',
'Common/Platform/$PLATFORM',
],
$output,
);
}
protected static function generateDockerComposeExecutionUser(): string
{
return \PHP_OS_FAMILY !== 'Windows' ? \sprintf('--user "%1$s:%2$s"', getmyuid(), getmygid()) : '';
}
}