-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestDiscovery.php
More file actions
executable file
·376 lines (345 loc) · 11.4 KB
/
TestDiscovery.php
File metadata and controls
executable file
·376 lines (345 loc) · 11.4 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
<?php
/**
* FileIterator — Part of the MaplePHP Unitary Testing Library
*
* @package: MaplePHP\Unitary
* @author: Daniel Ronkainen
* @licence: Apache-2.0 license, Copyright © Daniel Ronkainen
* Don't delete this comment, it's part of the license.
*/
declare(strict_types=1);
namespace MaplePHP\Unitary\Discovery;
use Closure;
use ErrorException;
use MaplePHP\Blunder\ExceptionItem;
use MaplePHP\Unitary\Support\Helpers;
use MaplePHP\Unitary\TestCase;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use SplFileInfo;
use Throwable;
use UnexpectedValueException;
use MaplePHP\Blunder\Exceptions\BlunderErrorException;
use MaplePHP\Blunder\Exceptions\BlunderSoftException;
use MaplePHP\Blunder\Handlers\CliHandler;
use MaplePHP\Blunder\Run;
use MaplePHP\Unitary\Unit;
final class TestDiscovery
{
private string $pattern = '*/unitary-*.php';
private bool $verbose = false;
private bool $failFast = false;
private bool $smartSearch = false;
private ?array $exclude = null;
private static ?Unit $unitary = null;
/**
* Enable verbose flag which will show errors that should not always be visible
*
* @param bool $isVerbose
* @return $this
*/
public function enableVerbose(bool $isVerbose): self
{
$this->verbose = $isVerbose;
return $this;
}
/**
* Enable verbose flag which will show errors that should not always be visible
*
* @param bool $failFast
* @return $this
*/
public function enableFailFast(bool $failFast): self
{
$this->failFast = $failFast;
return $this;
}
/**
* Enabling smart search; If no tests I found Unitary will try to traverse
* backwards until a test is found
*
* @param bool $smartSearch
* @return $this
*/
public function enableSmartSearch(bool $smartSearch): self
{
$this->smartSearch = $smartSearch;
return $this;
}
/**
* Exclude paths from file iteration
*
* @param string|array|null $exclude
* @return $this
*/
public function addExcludePaths(string|array|null $exclude): self
{
if ($exclude !== null) {
$this->exclude = is_string($exclude) ? explode(', ', $exclude) : $exclude;
}
return $this;
}
/**
* Change the default test discovery pattern from `unitary-*.php` to a custom pattern.
*
* Notes:
* - Wildcards can be used for paths (`tests/`) and files (`unitary-*.php`).
* - If no file extension is specified, `.php` is assumed.
* - Only PHP files are supported as test files.
*
* @param ?string $pattern null value will fall back to the default value
* @return $this
*/
public function setDiscoverPattern(?string $pattern): self
{
if ($pattern !== null) {
$pattern = rtrim($pattern, '*');
$pattern = ltrim($pattern, '*');
$pattern = ltrim($pattern, '/');
$this->pattern = "*/" . (!str_ends_with($pattern, '.php') ? rtrim($pattern, '/') . "/*.php" : $pattern);
}
return $this;
}
/**
* Get expected exit code
*
* @return int
*/
public function getExitCode(): int
{
return (int)!Unit::isSuccessful();
}
/**
* Will Execute all unitary test files
*
* @param string $path
* @param string|bool $rootDir
* @param callable|null $callback
* @return void
* @throws BlunderErrorException
* @throws BlunderSoftException
* @throws ErrorException
* @throws Throwable
*/
public function executeAll(string $path, string|bool $rootDir = false, ?callable $callback = null): void
{
$rootDir = is_string($rootDir) ? realpath($rootDir) : false;
$path = (!$path && $rootDir !== false) ? $rootDir : $path;
if ($rootDir !== false && !str_starts_with($path, "/") && !str_starts_with($path, $rootDir)) {
$path = $rootDir . "/" . $path;
}
$files = $this->findFiles($path, $rootDir);
if (empty($files) && $this->verbose) {
throw new BlunderSoftException("Unitary could not find any test files matching the pattern \"" .
$this->pattern . "\" in directory \"" . dirname($path) .
"\" and its subdirectories.");
} else {
foreach ($files as $file) {
try {
if (!is_file($file)) {
throw new RuntimeException("File \"$file\" do not exists.");
}
$instance = $callback($file);
if (!$instance instanceof Unit) {
throw new UnexpectedValueException('Callable must return ' . Unit::class);
}
self::$unitary = $instance;
$this->executeUnitFile((string)$file);
} catch (\Throwable $exception) {
if ($this->failFast) {
throw $exception;
}
self::$unitary->group("PHP error", function (TestCase $case) use ($exception) {
$newInst = $case->createTraceError($exception, trace: [
'file' => $exception->getFile(),
'line' => $exception->getLine(),
]);
$newInst->incrementError();
return $newInst;
});
self::$unitary->execute();
}
}
}
}
/**
* Prepares a callable that will include and execute a unit test file in isolation.
*
* Wrapping with Closure achieves:
* Scope isolation, $this unbinding, State separation, Deferred execution
*
* @param string $file The full path to the test file to require.
* @return void
* @throws BlunderErrorException
* @throws ErrorException
* @throws Throwable
*/
private function executeUnitFile(string $file): void
{
$verbose = $this->verbose;
$unitInst = $this->isolateRequire($file);
if ($unitInst instanceof Unit) {
$unitInst->inheritConfigs(self::$unitary);
self::$unitary = $unitInst;
}
$ok = self::$unitary->execute();
if (!$ok && $verbose) {
trigger_error(
"\n\nCould not find any tests inside the test file:\n$file\n\nPossible causes:\n" .
" • There are no test in test group/case.\n" .
" • Unitary could not locate the Unit instance.\n" .
" • You did not use the `group()` function.\n" .
" • You created a new Unit in the test file but did not return it at the end.\n\n",
E_USER_WARNING
);
}
}
/**
* Isolate the required file and keep $this out of scope
*
* @param $file
* @return mixed
*/
private function isolateRequire($file): mixed
{
$tes = new \Illuminate\Container\Container();
print_r($tes);
var_dump("src/Discovery/TestDiscovery.php:228");
die;
return (static function (string $f) {
return require $f;
})($file);
}
/**
* Will Scan and find all unitary test files
*
* @param string $path
* @param string|false $rootDir
* @return array
*/
private function findFiles(string $path, string|bool $rootDir = false): array
{
$files = [];
$realDir = realpath($path);
if ($realDir === false) {
throw new RuntimeException("Directory \"$path\" does not exist. Try using a absolut path!");
}
if (is_file($path) && str_starts_with(basename($path), "unitary-")) {
$files[] = $path;
} else {
if (is_file($path)) {
$path = dirname($path) . "/";
}
if (is_dir($path)) {
$files += $this->getFileIterateReclusive($path);
}
}
// If smart search flag then step back if no test files have been found and try again
if ($rootDir !== false && count($files) <= 0 && $this->smartSearch) {
$path = (string)realpath($path . "/..") . "/";
return $this->findFiles($path, $rootDir);
}
return $files;
}
/**
* Get exclude parameter
*
* @return array
*/
private function exclude(): array
{
$excl = [];
if ($this->exclude !== null && $this->exclude !== []) {
foreach ($this->exclude as $file) {
$file = str_replace(['"', "'"], "", $file);
$new = trim($file);
$lastChar = substr($new, -1);
if ($lastChar === DIRECTORY_SEPARATOR) {
$new .= "*";
}
$excl[] = trim($new);
}
}
return $excl;
}
/**
* Validate an exclude path
*
* @param array $exclArr
* @param string $relativeDir
* @param string $file
* @return bool
*/
private function findExcluded(array $exclArr, string $relativeDir, string $file): bool
{
$file = $this->getNaturalPath($file);
foreach ($exclArr as $excl) {
$relativeExclPath = $this->getNaturalPath($relativeDir . DIRECTORY_SEPARATOR . (string)$excl);
if (fnmatch($relativeExclPath, $file)) {
return true;
}
}
return false;
}
/**
* Iterate files that match the expected patterns
*
* @param string $path
* @return array
*/
private function getFileIterateReclusive(string $path): array
{
$files = [];
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
/** @var string $pattern */
foreach ($iterator as $file) {
if (($file instanceof SplFileInfo) && fnmatch($this->pattern, $file->getPathname()) &&
($this->exclude !== null || !str_contains($file->getPathname(), DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR))) {
if (!$this->findExcluded($this->exclude(), $path, $file->getPathname())) {
$files[] = $file->getPathname();
}
}
}
return $files;
}
/**
* Get a path as a natural path
*
* @param string $path
* @return string
*/
private function getNaturalPath(string $path): string
{
return str_replace("\\", "/", $path);
}
/**
* Initialize Blunder error handler
*
* @return void
*/
protected function runBlunder(): void
{
$run = new Run(new CliHandler());
$run->severity()
->excludeSeverityLevels([E_USER_WARNING, E_NOTICE, E_USER_NOTICE, E_DEPRECATED, E_USER_DEPRECATED])
->redirectTo(function () {
// Let PHP’s default error handler process excluded severities
return false;
});
$run->setExitCode(1);
$run->load();
}
/**
* Get instance of Unit class
*
* This is primary used to access the main test Unit instance that is
* pre-initialized for each test file. Is used by shortcut function like `group()`
*
* @return Unit|null
*/
public static function getUnitaryInst(): ?Unit
{
return self::$unitary;
}
}