/
Assert.php
601 lines (506 loc) 路 17.6 KB
/
Assert.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
<?php
/**
* This file is part of the Nette Tester.
* Copyright (c) 2009 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Tester;
/**
* Assertion test helpers.
*/
class Assert
{
/** used by equal() for comparing floats */
private const EPSILON = 1e-10;
/** used by match(); in values, each $ followed by number is backreference */
public static $patterns = [
'%%' => '%', // one % character
'%a%' => '[^\r\n]+', // one or more of anything except the end of line characters
'%a\?%' => '[^\r\n]*', // zero or more of anything except the end of line characters
'%A%' => '.+', // one or more of anything including the end of line characters
'%A\?%' => '.*', // zero or more of anything including the end of line characters
'%s%' => '[\t ]+', // one or more white space characters except the end of line characters
'%s\?%' => '[\t ]*', // zero or more white space characters except the end of line characters
'%S%' => '\S+', // one or more of characters except the white space
'%S\?%' => '\S*', // zero or more of characters except the white space
'%c%' => '[^\r\n]', // a single character of any sort (except the end of line)
'%d%' => '[0-9]+', // one or more digits
'%d\?%' => '[0-9]*', // zero or more digits
'%i%' => '[+-]?[0-9]+', // signed integer value
'%f%' => '[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?', // floating point number
'%h%' => '[0-9a-fA-F]+', // one or more HEX digits
'%w%' => '[0-9a-zA-Z_]+', //one or more alphanumeric characters
'%ds%' => '[\\\\/]', // directory separator
'%(\[.+\][+*?{},\d]*)%' => '$1', // range
];
/** @var callable function (AssertException $exception): void */
public static $onFailure;
/** @var int the count of assertions */
public static $counter = 0;
/**
* Checks assertion. Values must be exactly the same.
*/
public static function same($expected, $actual, string $description = null): void
{
self::$counter++;
if ($actual !== $expected) {
self::fail(self::describe('%1 should be %2', $description), $actual, $expected);
}
}
/**
* Checks assertion. Values must not be exactly the same.
*/
public static function notSame($expected, $actual, string $description = null): void
{
self::$counter++;
if ($actual === $expected) {
self::fail(self::describe('%1 should not be %2', $description), $actual, $expected);
}
}
/**
* Checks assertion. The identity of objects and the order of keys in the arrays are ignored.
*/
public static function equal($expected, $actual, string $description = null): void
{
self::$counter++;
if (!self::isEqual($expected, $actual)) {
self::fail(self::describe('%1 should be equal to %2', $description), $actual, $expected);
}
}
/**
* Checks assertion. The identity of objects and the order of keys in the arrays are ignored.
*/
public static function notEqual($expected, $actual, string $description = null): void
{
self::$counter++;
if (self::isEqual($expected, $actual)) {
self::fail(self::describe('%1 should not be equal to %2', $description), $actual, $expected);
}
}
/**
* Checks assertion. Values must contains expected needle.
*/
public static function contains($needle, $actual, string $description = null): void
{
self::$counter++;
if (is_array($actual)) {
if (!in_array($needle, $actual, true)) {
self::fail(self::describe('%1 should contain %2', $description), $actual, $needle);
}
} elseif (is_string($actual)) {
if ($needle !== '' && strpos($actual, $needle) === false) {
self::fail(self::describe('%1 should contain %2', $description), $actual, $needle);
}
} else {
self::fail(self::describe('%1 should be string or array', $description), $actual);
}
}
/**
* Checks assertion. Values must not contains expected needle.
*/
public static function notContains($needle, $actual, string $description = null): void
{
self::$counter++;
if (is_array($actual)) {
if (in_array($needle, $actual, true)) {
self::fail(self::describe('%1 should not contain %2', $description), $actual, $needle);
}
} elseif (is_string($actual)) {
if ($needle === '' || strpos($actual, $needle) !== false) {
self::fail(self::describe('%1 should not contain %2', $description), $actual, $needle);
}
} else {
self::fail(self::describe('%1 should be string or array', $description), $actual);
}
}
/**
* Checks TRUE assertion.
* @param mixed $actual
*/
public static function true($actual, string $description = null): void
{
self::$counter++;
if ($actual !== true) {
self::fail(self::describe('%1 should be TRUE', $description), $actual);
}
}
/**
* Checks FALSE assertion.
* @param mixed $actual
*/
public static function false($actual, string $description = null): void
{
self::$counter++;
if ($actual !== false) {
self::fail(self::describe('%1 should be FALSE', $description), $actual);
}
}
/**
* Checks NULL assertion.
* @param mixed $actual
*/
public static function null($actual, string $description = null): void
{
self::$counter++;
if ($actual !== null) {
self::fail(self::describe('%1 should be NULL', $description), $actual);
}
}
/**
* Checks Not a Number assertion.
* @param mixed $actual
*/
public static function nan($actual, string $description = null): void
{
self::$counter++;
if (!is_float($actual) || !is_nan($actual)) {
self::fail(self::describe('%1 should be NAN', $description), $actual);
}
}
/**
* Checks truthy assertion.
* @param mixed $actual
*/
public static function truthy($actual, string $description = null): void
{
self::$counter++;
if (!$actual) {
self::fail(self::describe('%1 should be truthy', $description), $actual);
}
}
/**
* Checks falsey (empty) assertion.
* @param mixed $actual
*/
public static function falsey($actual, string $description = null): void
{
self::$counter++;
if ($actual) {
self::fail(self::describe('%1 should be falsey', $description), $actual);
}
}
/**
* Checks if subject has expected count.
* @param mixed $value
*/
public static function count(int $count, $value, string $description = null): void
{
self::$counter++;
if (!$value instanceof \Countable && !is_array($value)) {
self::fail(self::describe('%1 should be array or countable object', $description), $value);
} elseif (count($value) !== $count) {
self::fail(self::describe('Count %1 should be %2', $description), count($value), $count);
}
}
/**
* Checks assertion.
* @param string|object $type
* @param mixed $value
*/
public static function type($type, $value, string $description = null): void
{
self::$counter++;
if (!is_object($type) && !is_string($type)) {
throw new \Exception('Type must be a object or a string.');
} elseif ($type === 'list') {
if (!is_array($value) || ($value && array_keys($value) !== range(0, count($value) - 1))) {
self::fail(self::describe("%1 should be $type", $description), $value);
}
} elseif (in_array($type, ['array', 'bool', 'callable', 'float',
'int', 'integer', 'null', 'object', 'resource', 'scalar', 'string', ], true)
) {
if (!("is_$type")($value)) {
self::fail(self::describe(gettype($value) . " should be $type", $description));
}
} elseif (!$value instanceof $type) {
$actual = is_object($value) ? get_class($value) : gettype($value);
self::fail(self::describe("$actual should be instance of $type", $description));
}
}
/**
* Checks if the function throws exception.
*/
public static function exception(callable $function, string $class, string $message = null, $code = null): ?\Throwable
{
self::$counter++;
$e = null;
try {
$function();
} catch (\Throwable $e) {
}
if ($e === null) {
self::fail("$class was expected, but none was thrown");
} elseif (!$e instanceof $class) {
self::fail("$class was expected but got " . get_class($e) . ($e->getMessage() ? " ({$e->getMessage()})" : ''), null, null, $e);
} elseif ($message && !self::isMatching($message, $e->getMessage())) {
self::fail("$class with a message matching %2 was expected but got %1", $e->getMessage(), $message);
} elseif ($code !== null && $e->getCode() !== $code) {
self::fail("$class with a code %2 was expected but got %1", $e->getCode(), $code);
}
return $e;
}
/**
* Checks if the function throws exception, alias for exception().
*/
public static function throws(callable $function, string $class, string $message = null, $code = null): ?\Throwable
{
return self::exception($function, $class, $message, $code);
}
/**
* Checks if the function generates PHP error or throws exception.
* @param int|string|array $expectedType
* @param string $expectedMessage message
* @throws \Exception
* @throws \Exception
*/
public static function error(callable $function, $expectedType, string $expectedMessage = null): ?\Throwable
{
if (is_string($expectedType) && !preg_match('#^E_[A-Z_]+\z#', $expectedType)) {
return static::exception($function, $expectedType, $expectedMessage);
}
self::$counter++;
$expected = is_array($expectedType) ? $expectedType : [[$expectedType, $expectedMessage]];
foreach ($expected as &$item) {
$item = ((array) $item) + [null, null];
$expectedType = $item[0];
if (is_int($expectedType)) {
$item[2] = Helpers::errorTypeToString($expectedType);
} elseif (is_string($expectedType)) {
$item[0] = constant($item[2] = $expectedType);
} else {
throw new \Exception('Error type must be E_* constant.');
}
}
set_error_handler(function (int $severity, string $message, string $file, int $line) use (&$expected) {
if (($severity & error_reporting()) !== $severity) {
return;
}
$errorStr = Helpers::errorTypeToString($severity) . ($message ? " ($message)" : '');
[$expectedType, $expectedMessage, $expectedTypeStr] = array_shift($expected);
if ($expectedType === null) {
self::fail("Generated more errors than expected: $errorStr was generated in file $file on line $line");
} elseif ($severity !== $expectedType) {
self::fail("$expectedTypeStr was expected, but $errorStr was generated in file $file on line $line");
} elseif ($expectedMessage && !self::isMatching($expectedMessage, $message)) {
self::fail("$expectedTypeStr with a message matching %2 was expected but got %1", $message, $expectedMessage);
}
});
reset($expected);
try {
$function();
restore_error_handler();
} catch (\Exception $e) {
restore_error_handler();
throw $e;
}
if ($expected) {
self::fail('Error was expected, but was not generated');
}
return null;
}
/**
* Checks that the function does not generate PHP error and does not throw exception.
*/
public static function noError(callable $function): void
{
if (($count = func_num_args()) > 1) {
throw new \Exception(__METHOD__ . "() expects 1 parameter, $count given.");
}
self::error($function, []);
}
/**
* Compares result using regular expression or mask:
* %a% one or more of anything except the end of line characters
* %a?% zero or more of anything except the end of line characters
* %A% one or more of anything including the end of line characters
* %A?% zero or more of anything including the end of line characters
* %s% one or more white space characters except the end of line characters
* %s?% zero or more white space characters except the end of line characters
* %S% one or more of characters except the white space
* %S?% zero or more of characters except the white space
* %c% a single character of any sort (except the end of line)
* %d% one or more digits
* %d?% zero or more digits
* %i% signed integer value
* %f% floating point number
* %h% one or more HEX digits
* @param string $pattern mask|regexp; only delimiters ~ and # are supported for regexp
*/
public static function match(string $pattern, $actual, string $description = null): void
{
self::$counter++;
if (!is_scalar($actual)) {
self::fail(self::describe('%1 should match %2', $description), $actual, $pattern);
} elseif (!self::isMatching($pattern, $actual)) {
[$pattern, $actual] = self::expandMatchingPatterns($pattern, $actual);
self::fail(self::describe('%1 should match %2', $description), $actual, $pattern);
}
}
/**
* Compares results using mask sorted in file.
*/
public static function matchFile(string $file, $actual, string $description = null): void
{
self::$counter++;
$pattern = @file_get_contents($file); // @ is escalated to exception
if ($pattern === false) {
throw new \Exception("Unable to read file '$file'.");
} elseif (!is_scalar($actual)) {
self::fail(self::describe('%1 should match %2', $description), $actual, $pattern);
} elseif (!self::isMatching($pattern, $actual)) {
[$pattern, $actual] = self::expandMatchingPatterns($pattern, $actual);
self::fail(self::describe('%1 should match %2', $description), $actual, $pattern);
}
}
/**
* Failed assertion
*/
public static function fail(string $message, $actual = null, $expected = null, \Throwable $previous = null): void
{
$e = new AssertException($message, $expected, $actual, $previous);
if (self::$onFailure) {
(self::$onFailure)($e);
} else {
throw $e;
}
}
private static function describe(string $reason, string $description = null): string
{
return ($description ? $description . ': ' : '') . $reason;
}
public static function with($obj, \Closure $closure)
{
return $closure->call($obj);
}
/********************* helpers ****************d*g**/
/**
* Compares using mask.
* @internal
*/
public static function isMatching(string $pattern, $actual, bool $strict = false): bool
{
if (!is_scalar($actual)) {
throw new \Exception('Value must be strings.');
}
$old = ini_set('pcre.backtrack_limit', '10000000');
if (!self::isPcre($pattern)) {
$utf8 = preg_match('#\x80-\x{10FFFF}]#u', $pattern) ? 'u' : '';
$suffix = ($strict ? '\z#sU' : '\s*$#sU') . $utf8;
$patterns = static::$patterns + [
'[.\\\\+*?[^$(){|\#]' => '\$0', // preg quoting
'\x00' => '\x00',
'[\t ]*\r?\n' => '[\t ]*\r?\n', // right trim
];
$pattern = '#^' . preg_replace_callback('#' . implode('|', array_keys($patterns)) . '#U' . $utf8, function ($m) use ($patterns) {
foreach ($patterns as $re => $replacement) {
$s = preg_replace("#^$re\\z#", str_replace('\\', '\\\\', $replacement), $m[0], 1, $count);
if ($count) {
return $s;
}
}
}, rtrim($pattern, " \t\n\r")) . $suffix;
}
$res = preg_match($pattern, (string) $actual);
ini_set('pcre.backtrack_limit', $old);
if ($res === false || preg_last_error()) {
throw new \Exception('Error while executing regular expression. (PREG Error Code ' . preg_last_error() . ')');
}
return (bool) $res;
}
/**
* @internal
*/
public static function expandMatchingPatterns(string $pattern, $actual): array
{
if (self::isPcre($pattern)) {
return [$pattern, $actual];
}
$parts = preg_split('#(%)#', $pattern, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = count($parts); $i >= 0; $i--) {
$patternX = implode(array_slice($parts, 0, $i));
$patternY = "$patternX%A?%";
if (self::isMatching($patternY, $actual)) {
$patternZ = implode(array_slice($parts, $i));
break;
}
}
foreach (['%A%', '%A?%'] as $greedyPattern) {
if (substr($patternX, -strlen($greedyPattern)) === $greedyPattern) {
$patternX = substr($patternX, 0, -strlen($greedyPattern));
$patternY = "$patternX%A?%";
$patternZ = $greedyPattern . $patternZ;
break;
}
}
$low = 0;
$high = strlen($actual);
while ($low <= $high) {
$mid = ($low + $high) >> 1;
if (self::isMatching($patternY, substr($actual, 0, $mid))) {
$high = $mid - 1;
} else {
$low = $mid + 1;
}
}
$low = $high + 2;
$high = strlen($actual);
while ($low <= $high) {
$mid = ($low + $high) >> 1;
if (!self::isMatching($patternX, substr($actual, 0, $mid), true)) {
$high = $mid - 1;
} else {
$low = $mid + 1;
}
}
$actualX = substr($actual, 0, $high);
$actualZ = substr($actual, $high);
return [
$actualX . rtrim(preg_replace('#[\t ]*\r?\n#', "\n", $patternZ)),
$actualX . rtrim(preg_replace('#[\t ]*\r?\n#', "\n", $actualZ)),
];
}
/**
* Compares two structures. Ignores the identity of objects and the order of keys in the arrays.
*/
private static function isEqual($expected, $actual, int $level = 0, $objects = null): bool
{
if ($level > 10) {
throw new \Exception('Nesting level too deep or recursive dependency.');
}
if (is_float($expected) && is_float($actual) && is_finite($expected) && is_finite($actual)) {
$diff = abs($expected - $actual);
return ($diff < self::EPSILON) || ($diff / max(abs($expected), abs($actual)) < self::EPSILON);
}
if (is_object($expected) && is_object($actual) && get_class($expected) === get_class($actual)) {
$objects = $objects ? clone $objects : new \SplObjectStorage;
if (isset($objects[$expected])) {
return $objects[$expected] === $actual;
} elseif ($expected === $actual) {
return true;
}
$objects[$expected] = $actual;
$objects[$actual] = $expected;
$expected = (array) $expected;
$actual = (array) $actual;
}
if (is_array($expected) && is_array($actual)) {
ksort($expected, SORT_STRING);
ksort($actual, SORT_STRING);
if (array_keys($expected) !== array_keys($actual)) {
return false;
}
foreach ($expected as $value) {
if (!self::isEqual($value, current($actual), $level + 1, $objects)) {
return false;
}
next($actual);
}
return true;
}
return $expected === $actual;
}
private static function isPcre(string $pattern): bool
{
return (bool) preg_match('/^([~#]).+(\1)[imsxUu]*\z/s', $pattern);
}
}