Passed
Branch master (0511c6)
by Caen
03:10
created

MicroTest   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 34
dl 0
loc 75
rs 10
c 0
b 0
f 0
wmc 13
1
<?php
2
3
declare(strict_types=1);
4
5
use JetBrains\PhpStorm\NoReturn;
6
7
const BASE_PATH = __DIR__.'/../../../';
8
9
/**
10
 * @internal
11
 */
12
class MicroTest
13
{
14
    protected static self $instance;
15
16
    protected array $tests = [];
17
    protected array $failedTests = [];
18
    protected float $time;
19
20
    protected function __construct()
21
    {
22
        $this->time = microtime(true);
23
24
        echo 'Running tests...'.PHP_EOL;
25
    }
26
27
    #[NoReturn]
28
    public function __destruct()
29
    {
30
        $exitCode = $this->run();
31
32
        echo 'Tests finished in '.number_format((microtime(true) - $this->time) * 1000, 2).' ms'.PHP_EOL;
33
34
        exit($exitCode);
35
    }
36
37
    public static function getInstance(): self
38
    {
39
        if (! isset(self::$instance)) {
40
            self::$instance = new self();
41
        }
42
43
        return self::$instance;
44
    }
45
46
    public function test(string $name, Closure $callback): void
47
    {
48
        $callback = $callback->bindTo($this);
49
50
        $this->tests[$name] = $callback;
51
    }
52
53
    /** @throws \Exception */
54
    public function assert(bool $condition, string $message = null): void
55
    {
56
        if (! $condition) {
57
            throw new Exception($message ?? 'Assertion failed');
58
        }
59
    }
60
61
    protected function run(): int
62
    {
63
        foreach ($this->tests as $name => $test) {
64
            try {
65
                $test();
66
            } catch (Exception $exception) {
67
                $this->failedTests[$name] = $exception;
68
            } finally {
69
                $status = (isset($exception) ? 'failed' : 'passed');
70
                echo "Test $status: $name".PHP_EOL;
71
                if (isset($exception)) {
72
                    echo " > {$exception->getMessage()}".PHP_EOL;
73
                }
74
                unset($exception);
75
            }
76
        }
77
78
        if (count($this->failedTests) > 0) {
79
            echo 'Some tests failed'.PHP_EOL;
80
81
            return 1;
82
        }
83
84
        echo 'All tests passed'.PHP_EOL;
85
86
        return 0;
87
    }
88
}
89
90
function test(string $name, callable $callback): void
91
{
92
    MicroTest::getInstance()->test($name, $callback);
93
}
94