-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingle-file-unit-test.php
More file actions
455 lines (396 loc) · 14.9 KB
/
Copy pathsingle-file-unit-test.php
File metadata and controls
455 lines (396 loc) · 14.9 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
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
<?php
/**
* single-file-unit-test
*
* A zero-dependency, single-file unit testing framework for PHP 5.6 and above.
* Just require 'single-file-unit-test.php' and you're ready to start testing, with a design that facilitates migration to PHPUnit.
*
* https://github.com/smeghead/single-file-unit-test
*/
// PHP5.6互換性のためのErrorクラス定義(グローバルnamespace)
namespace {
if (!class_exists('Error', false)) {
/**
* PHP5.6互換用のErrorクラス
* PHP7のErrorクラスと同様のインターフェースを提供
* 注意: PHP5.6では実際のFATALエラーは捕捉できません
*/
class Error extends Exception {
public function __construct($message = "", $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
}
}
}
namespace Smeghead\SingleFileUnitTest {
const VERSION = 'v0.2.1';
// 警告表示のための設定
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'stderr');
ini_set('html_errors', 0);
/**
* assert処理が失敗した場合の例外クラス
*/
class AssertionFailedException extends \Exception
{
}
/**
* 期待した例外が発生しなかった場合の例外クラス
* ユーザーが期待する例外と区別するために使用
*/
class ExpectationFailedException extends AssertionFailedException
{
}
class ColorSupport
{
/**
* ターミナルが色をサポートしているかどうかを判定する
* @return bool 色をサポートしている場合はtrue
*/
public function isSupported()
{
// NO_COLOR環境変数が設定されている場合は色を無効にする
if (getenv('NO_COLOR') !== false) {
return false;
}
// TTYでない場合(リダイレクトやパイプされている場合)は色を無効にする
if (function_exists('posix_isatty') && !posix_isatty(STDOUT)) {
return false;
}
// TERM環境変数をチェック
$term = getenv('TERM');
if ($term === false || $term === 'dumb') {
return false;
}
// 色をサポートすることが知られているTERM値
$colorTerms = array(
'xterm', 'xterm-color', 'xterm-256color',
'screen', 'screen-256color',
'tmux', 'tmux-256color',
'rxvt', 'rxvt-unicode', 'rxvt-256color',
'linux', 'cygwin',
'ansi', 'vt100', 'vt220'
);
foreach ($colorTerms as $colorTerm) {
if (strpos($term, $colorTerm) === 0) {
return true;
}
}
// COLORTERM環境変数が設定されている場合
if (getenv('COLORTERM') !== false) {
return true;
}
// デフォルトでは色をサポートしないと仮定
return false;
}
}
final class TerminalString
{
private $colorSupport;
private static $fgColors = [
'black' => '30',
'red' => '31',
'green' => '32',
'yellow' => '33',
'blue' => '34',
'magenta' => '35',
'cyan' => '36',
'white' => '97',
];
private static $bgColors = [
'black' => '40',
'red' => '41',
'green' => '42',
'yellow' => '43',
'blue' => '44',
'magenta' => '45',
'cyan' => '46',
'white' => '107',
];
public function __construct(ColorSupport $colorSupport)
{
$this->colorSupport = $colorSupport;
}
public function text($text, $fg = null, $bg = null)
{
if (PHP_SAPI === 'cli' && $this->colorSupport->isSupported() && ($fg || $bg)) {
$codes = [];
if ($fg && isset(self::$fgColors[$fg])) {
$codes[] = self::$fgColors[$fg];
}
if ($bg && isset(self::$bgColors[$bg])) {
$codes[] = self::$bgColors[$bg];
}
if ($codes) {
$lines = [];
foreach (preg_split('/\r?\n/', $text) as $line) {
$lines[] = "\033[" . implode(';', $codes) . "m" . $line . "\033[0m";
}
return implode("\n", $lines);
}
}
return $text;
}
}
final class ResultAccumulator
{
private $testCount = 0;
private $failCount = 0;
private $assertionCount = 0;
private $failedTests = [];
public function incrementTestCount()
{
$this->testCount++;
}
public function incrementFailCount()
{
$this->failCount++;
}
public function incrementAssertionCount()
{
$this->assertionCount++;
}
public function addFailedTest($testName)
{
$this->failedTests[] = $testName;
}
public function getFailedTests()
{
return $this->failedTests;
}
public function hasFailures()
{
return $this->failCount > 0;
}
public function getSummaryMessage()
{
if (!$this->hasFailures()) {
return "OK ({$this->testCount} tests, {$this->assertionCount} assertions)";
} else {
return "FAILURES!\nTests: {$this->testCount} Assertions: {$this->assertionCount} Failures: {$this->failCount}.";
}
}
}
class TestCase
{
protected function setUp() {}
protected function tearDown() {}
private $expectedExceptionMessage = null;
private static $resultAccumulator = null;
private $colorSupport;
private $terminalString;
public function __construct()
{
$this->colorSupport = new ColorSupport();
$this->terminalString = new TerminalString($this->colorSupport);
}
private static function ensureResultAccumulator()
{
if (self::$resultAccumulator === null) {
self::$resultAccumulator = new ResultAccumulator();
}
}
public static function showResults()
{
self::ensureResultAccumulator();
$colorSupport = new ColorSupport();
$terminalString = new TerminalString($colorSupport);
echo "\n"; // 空行を追加
if (!self::$resultAccumulator->hasFailures()) {
echo $terminalString->text(self::$resultAccumulator->getSummaryMessage(), 'black', 'green') . "\n";
} else {
echo $terminalString->text(self::$resultAccumulator->getSummaryMessage(), 'white', 'red') . "\n";
foreach (self::$resultAccumulator->getFailedTests() as $failTest) {
echo " - $failTest\n";
}
}
}
public function expectExceptionMessage($message)
{
$this->expectedExceptionMessage = $message;
}
public function assertSame($expected, $actual, $message = '')
{
self::ensureResultAccumulator();
self::$resultAccumulator->incrementAssertionCount();
if ($expected !== $actual) {
throw new AssertionFailedException(
$message . "\nExpected: " . var_export($expected, true) .
"\nActual : " . var_export($actual, true)
);
}
}
/**
* 一つのテストを行ないます。
* expectedExceptionMessage の動作についても、期待通りなら成功メッセージを返却します。
* @param string $class
* @param string $method
* @return string
*/
protected function runTest($class, $method) {
try {
$this->setUp();
ob_start();
$this->$method();
ob_end_clean();
if ($this->expectedExceptionMessage !== null) {
throw new ExpectationFailedException("Failed asserting that exception message [{$this->expectedExceptionMessage}] was thrown.");
}
return "✔ $class::$method";
} catch (ExpectationFailedException $e) {
throw $e;
} catch (\Exception $e) {
if (
$this->expectedExceptionMessage !== null &&
strpos($e->getMessage(), $this->expectedExceptionMessage) !== false
) {
return "✔ $class::$method (expected exception caught)";
}
throw $e;
} finally {
$this->tearDown();
}
}
public function runTests()
{
self::ensureResultAccumulator();
$class = get_class($this);
$methods = get_class_methods($this);
foreach ($methods as $method) {
if (strpos($method, 'test') !== 0) continue;
self::$resultAccumulator->incrementTestCount();
$this->expectedExceptionMessage = null;
try {
$this->out($this->runTest($class, $method), 'green');
} catch (\Error $e) {
// PHP7以降のFATALエラーを捕捉
self::$resultAccumulator->incrementFailCount();
self::$resultAccumulator->addFailedTest("$class::$method");
$this->out("✘ $class::$method", 'red');
$this->out(" Fatal Error: " . $e->getMessage(), 'yellow');
} catch (\Exception $e) {
self::$resultAccumulator->incrementFailCount();
self::$resultAccumulator->addFailedTest("$class::$method");
$this->out("✘ $class::$method", 'red');
$this->out(" " . $e->getMessage(), 'yellow');
}
}
}
private function out($text, $color = null)
{
echo $this->terminalString->text($text, $color) . "\n";
}
public static function runAll()
{
self::$resultAccumulator = new ResultAccumulator();
foreach (get_declared_classes() as $class) {
if (is_subclass_of($class, __CLASS__)) {
$instance = new $class();
$instance->runTests();
}
}
// Summary output
self::showResults();
exit(self::$resultAccumulator->hasFailures() ? 1 : 0);
}
}
// ---- CLI entry point ----
if (php_sapi_name() === 'cli' && basename(__FILE__) === basename($_SERVER['argv'][0])) {
function showHelpTo($output) {
$helpText = "Single File Unit Test " . VERSION . "\n" .
"\n" .
"Usage:\n" .
" php single-file-unit-test.php <test_dir_or_file> [...more]\n" .
" php single-file-unit-test.php -h|--help\n" .
" php single-file-unit-test.php -v|--version\n" .
" php single-file-unit-test.php --generate-test-class[=ClassName]\n" .
"\n" .
"Options:\n" .
" -h, --help Show this help message\n" .
" -v, --version Show version information\n" .
" --generate-test-class=ClassName Generate a test class template\n" .
"\n" .
"Arguments:\n" .
" test_dir_or_file Path to test directory or test file\n";
fwrite($output, $helpText);
}
function loadTestFiles($path) {
if (is_dir($path)) {
$rii = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
foreach ($rii as $file) {
if ($file->isFile() && preg_match('/Test\.php$/', $file->getFilename())) {
require $file->getPathname();
}
}
} elseif (is_file($path)) {
require $path;
} else {
fwrite(STDERR, "Invalid path: $path\n");
exit(2);
}
}
$args = array_slice($_SERVER['argv'], 1);
// ヘルプ表示の処理
if (!empty($args) && (in_array('-h', $args) || in_array('--help', $args))) {
showHelpTo(STDOUT);
exit(0);
}
// バージョン表示の処理
if (!empty($args) && (in_array('-v', $args) || in_array('--version', $args))) {
echo "Single File Unit Test " . VERSION . "\n";
exit(0);
}
// テストクラス生成の処理
$className = parseGenerateTestClassOption($args);
if ($className !== null) {
echo generateTestClass($className);
exit(0);
}
if (empty($args)) {
showHelpTo(STDERR);
exit(2);
}
foreach ($args as $arg) {
loadTestFiles($arg);
}
TestCase::runAll();
}
/**
* テストクラスのテンプレートを生成する
* @param string $className クラス名(省略時は'Example')
* @return string 生成されたテストクラスのコード
*/
function generateTestClass($className = 'Example') {
$testClassName = $className . 'Test';
$template = <<<PHP
<?php
use Smeghead\SingleFileUnitTest\TestCase;
class $testClassName extends TestCase {
public function test_1plus2_is_3() {
\$this->assertSame(3, (new Some())->add(1, 2));
}
public function test_it_must_throw_exception() {
\$this->expectExceptionMessage("Error occurred");
(new Some())->error();
}
}
PHP;
return $template . "\n";
}
/**
* CLI引数から--generate-test-classオプションを解析する
* @param array $args CLI引数の配列
* @return string|null クラス名または null
*/
function parseGenerateTestClassOption($args) {
foreach ($args as $arg) {
if ($arg === '--generate-test-class') {
return 'Example';
}
if (strpos($arg, '--generate-test-class=') === 0) {
return substr($arg, strlen('--generate-test-class='));
}
}
return null;
}
}