-
Notifications
You must be signed in to change notification settings - Fork 0
/
Unit.php
executable file
·383 lines (344 loc) · 10.9 KB
/
Unit.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
378
379
380
381
382
383
<?php
declare(strict_types=1);
namespace MaplePHP\Unitary;
use Closure;
use ErrorException;
use Exception;
use RuntimeException;
use MaplePHP\Unitary\Handlers\HandlerInterface;
use MaplePHP\Http\Interfaces\StreamInterface;
use MaplePHP\Prompts\Command;
use Throwable;
class Unit
{
private ?HandlerInterface $handler = null;
private Command $command;
private string $output = "";
private int $index = 0;
private array $cases = [];
private bool $skip = false;
private bool $executed = false;
private static array $headers = [];
private static ?Unit $current;
private static array $manual = [];
public static int $totalPassedTests = 0;
public static int $totalTests = 0;
public function __construct(HandlerInterface|StreamInterface|null $handler = null)
{
if($handler instanceof HandlerInterface) {
$this->handler = $handler;
$this->command = $this->handler->getCommand();
} else {
$this->command = new Command($handler);
}
self::$current = $this;
}
/**
* Skip you can add this if you want to turn of validation of a unit case
* @param bool $skip
* @return $this
*/
public function skip(bool $skip): self
{
$this->skip = $skip;
return $this;
}
/**
* Make script manually callable
* @param string $key
* @return $this
*/
public function manual(string $key): self
{
if(isset(self::$manual[$key])) {
$file = (string)(self::$headers['file'] ?? "none");
throw new RuntimeException("The manual key \"$key\" already exists.
Please set a unique key in the " . $file. " file.");
}
self::$manual[$key] = self::$headers['checksum'];
return $this->skip(true);
}
/**
* Access command instance
* @return Command
*/
public function getCommand(): Command
{
return $this->command;
}
/**
* Access command instance
* @return StreamInterface
*/
public function getStream(): StreamInterface
{
return $this->command->getStream();
}
/**
* Disable ANSI
* @param bool $disableAnsi
* @return self
*/
public function disableAnsi(bool $disableAnsi): self
{
$this->command->getAnsi()->disableAnsi($disableAnsi);
return $this;
}
/**
* Print message
* @param string $message
* @return false|string
*/
public function message(string $message): false|string
{
return $this->command->message($message);
}
/**
* confirm for execute
* @param string $message
* @return bool
*/
public function confirm(string $message = "Do you wish to continue?"): bool
{
return $this->command->confirm($message);
}
/**
* DEPRECATED: Name has been changed to case
* @param string $message
* @param Closure $callback
* @return void
*/
public function add(string $message, Closure $callback): void
{
// Might be trigger in future
//trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
$this->case($message, $callback);
}
/**
* Add a test unit/group
* @param string $message
* @param Closure $callback
* @return void
*/
public function case(string $message, Closure $callback): void
{
$testCase = new TestCase($message);
$testCase->bind($callback);
$this->cases[$this->index] = $testCase;
$this->index++;
}
/**
* Execute tests suite
* @return bool
* @throws ErrorException
*/
public function execute(): bool
{
if($this->executed || !$this->validate()) {
return false;
}
// LOOP through each case
ob_start();
foreach($this->cases as $row) {
if(!($row instanceof TestCase)) {
throw new RuntimeException("The @cases (object->array) should return a row with instanceof TestCase.");
}
try {
$tests = $row->dispatchTest();
} catch (Throwable $e) {
$file = $this->formatFileTitle((string)(self::$headers['file'] ?? ""), 5, false);
throw new RuntimeException($e->getMessage() . ". Error originated from: ". $file, (int)$e->getCode(), $e);
}
$color = ($row->hasFailed() ? "brightRed" : "brightBlue");
$flag = $this->command->getAnsi()->style(['blueBg', 'brightWhite'], " PASS ");
if($row->hasFailed()) {
$flag = $this->command->getAnsi()->style(['redBg', 'brightWhite'], " FAIL ");
}
$this->command->message("");
$this->command->message(
$flag . " " .
$this->command->getAnsi()->style(["bold"], $this->formatFileTitle((string)(self::$headers['file'] ?? ""))) .
" - " .
$this->command->getAnsi()->style(["bold", $color], (string)$row->getMessage())
);
foreach($tests as $test) {
if(!($test instanceof TestUnit)) {
throw new RuntimeException("The @cases (object->array) should return a row with instanceof TestUnit.");
}
if(!$test->isValid()) {
$msg = (string)$test->getMessage();
$this->command->message("");
$this->command->message($this->command->getAnsi()->style(["bold", "brightRed"], "Error: " . $msg));
/** @var array<string, string> $unit */
foreach($test->getUnits() as $unit) {
$this->command->message(
$this->command->getAnsi()->bold("Validation: ") .
$this->command->getAnsi()->style(
((!$unit['valid']) ? "brightRed" : null),
$unit['validation'] . ((!$unit['valid']) ? " (fail)" : "")
)
);
}
$this->command->message($this->command->getAnsi()->bold("Value: ") . $test->getReadValue());
}
}
self::$totalPassedTests += $row->getCount();
self::$totalTests += $row->getTotal();
$checksum = (string)(self::$headers['checksum'] ?? "");
$this->command->message("");
$this->command->message(
$this->command->getAnsi()->bold("Passed: ") .
$this->command->getAnsi()->style([$color], $row->getCount() . "/" . $row->getTotal()) .
$this->command->getAnsi()->style(["italic", "grey"], " - ". $checksum)
);
}
$this->output .= ob_get_clean();
if($this->output) {
$this->buildNotice("Note:", $this->output, 80);
}
if(!is_null($this->handler)) {
$this->handler->execute();
}
$this->executed = true;
return true;
}
/**
* Will reset the execute and stream if is a seekable stream.
* @return bool
*/
public function resetExecute(): bool
{
if($this->executed) {
if($this->getStream()->isSeekable()) {
$this->getStream()->rewind();
}
$this->executed = false;
return true;
}
return false;
}
/**
* Validate before execute test
* @return bool
*/
private function validate(): bool
{
$args = (array)(self::$headers['args'] ?? []);
$manual = isset($args['show']) ? (string)$args['show'] : "";
if(isset($args['show'])) {
return !((self::$manual[$manual] ?? "") !== self::$headers['checksum'] && $manual !== self::$headers['checksum']);
}
if($this->skip) {
return false;
}
return true;
}
/**
* Build the notification stream
* @param string $title
* @param string $output
* @param int $lineLength
* @return void
*/
public function buildNotice(string $title, string $output, int $lineLength): void
{
$this->output = wordwrap($output, $lineLength);
$line = $this->command->getAnsi()->line($lineLength);
$this->command->message("");
$this->command->message($this->command->getAnsi()->style(["bold"], $title));
$this->command->message($line);
$this->command->message($this->output);
$this->command->message($line);
}
/**
* Make file path into a title
* @param string $file
* @param int $length
* @param bool $removeSuffix
* @return string
*/
private function formatFileTitle(string $file, int $length = 3, bool $removeSuffix = true): string
{
$file = explode("/", $file);
if ($removeSuffix) {
$pop = array_pop($file);
$file[] = substr($pop, (int)strpos($pop, 'unitary') + 8);
}
$file = array_chunk(array_reverse($file), $length);
$file = implode("\\", array_reverse($file[0]));
$exp = explode('.', $file);
$file = reset($exp);
return ".." . $file;
}
/**
* Global header information
* @param array $headers
* @return void
*/
public static function setHeaders(array $headers): void
{
self::$headers = $headers;
}
/**
* Append to global header
* @param string $key
* @param mixed $value
* @return void
*/
public static function appendHeader(string $key, mixed $value): void
{
self::$headers[$key] = $value;
}
/**
* Used to reset current instance
* @return void
*/
public static function resetUnit(): void
{
self::$current = null;
}
/**
* Used to check if instance is set
* @return bool
*/
public static function hasUnit(): bool
{
return !is_null(self::$current);
}
/**
* Used to get instance
* @return ?Unit
* @throws Exception
*/
public static function getUnit(): ?Unit
{
if(is_null(self::hasUnit())) {
throw new Exception("Unit has not been set yet. It needs to be set first.");
}
return self::$current;
}
/**
* This will be called when every test has been run by the FileIterator
* @return void
*/
public static function completed(): void
{
if(!is_null(self::$current) && is_null(self::$current->handler)) {
self::$current->command->message("");
self::$current->command->message(
self::$current->command->getAnsi()->style(
["italic", "grey"],
"Total: " . self::$totalPassedTests . "/" . self::$totalTests
)
);
}
}
/**
* DEPRECATED: Not used anymore
* @return $this
*/
public function addTitle(): self
{
return $this;
}
}