-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessNetteTester.module
484 lines (394 loc) · 15.5 KB
/
ProcessNetteTester.module
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
<?php namespace ProcessWire;
use Tester\Assert;
use Tester\AssertException;
use Tester\Dumper;
use Tester\Environment;
require_once __DIR__ . '/IProcessNetteTester.php';
/**
* Run Nette Tester tests within ProcessWire admin.
* by Roland Toth (tpr)
*
* ProcessWire 3.x
* Copyright (C) 2011 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://www.processwire.com
* http://www.ryancramer.com
*
* FileCompiler=0
*/
/**
* Class ProcessNetteTester
*
* @package ProcessWire
*/
class ProcessNetteTester extends Process implements \IProcessNetteTester
{
const TEST_DIR_FIELD = 'tester_tests_directory';
const EMPTY_VALUE = '';
const TIMEOUT = 60;
private $testDirName;
private $testDirPath;
private $testFiles;
private $texts;
private $totalTestCount = 0;
private $subsetTestCount = 0;
/**
* Basic information about module.
*
* @return array
*/
public static function getModuleInfo()
{
return array(
'title' => 'ProcessNetteTester',
'summary' => __('Run Nette Tester tests within ProcessWire admin', __FILE__),
'href' => '',
'author' => 'Roland Toth',
'version' => '0.1.3',
'icon' => 'circle-o-notch',
'requires' => 'PHP>=5.6.0, ProcessWire>=3.0.0',
'autoload' => 'process=ProcessNetteTester',
'singular' => true,
);
}
public function execute()
{
$this->texts = $this->getTexts();
if ($this->wire('config')->ajax) {
return $this->getAjaxResponse();
}
$this->testDirName = $this->getTestDirName();
$this->testDirPath = $this->getTestDirPath();
$this->testFiles = $this->getTestFiles();
return $this->renderMarkup();
}
public function formatTime($microtime, $decimals = 4)
{
return number_format($microtime, $decimals, '.', '');
}
public function getLineInfo($line = null)
{
$lineInfo = '';
if (is_int($line)) {
$lineInfo = sprintf($this->texts['lineNum'], $line);
}
return '<em class="line-info">' . $lineInfo . '</em>';
}
public function getModifiedDumperMessage($exception)
{
Dumper::$maxLength = 800; // default is 70
$origMessage = $exception->origMessage;
$msg = strtr($origMessage, [
'%1 ' => '<span class="actual">%1</span><span>',
'%2 ' => '</span><span class="expected">%2</span><span>',
]);
$msg .= '</span>';
$actual = Dumper::toLine($exception->actual);
$expected = Dumper::toLine($exception->expected);
$msg = strtr($msg, array(
'%1' => htmlentities($actual),
'%2' => htmlentities($expected),
));
return $msg;
}
public function getTestDirName()
{
return rtrim($this->wire('page')->{self::TEST_DIR_FIELD}, '/');
}
public function getTestDirPath()
{
return $this->wire('config')->paths->root . ltrim($this->testDirName, '/') . '/';
}
public function getTestFiles()
{
$includes = !empty($_GET['include']) ? explode(',', $_GET['include']) : false;
$excludes = !empty($_GET['exclude']) ? explode(',', $_GET['exclude']) : false;
$allFiles = $this->rglob($this->testDirPath . '*Test.php');
$subset = array_filter($allFiles, function ($v) use ($includes, $excludes) {
$name = strtolower(basename($v, '.php'));
$nameWithoutSuffix = substr($name, 0, -4);
if ($includes) {
return \in_array($name, $includes, true) || \in_array($nameWithoutSuffix, $includes, true);
}
if ($excludes) {
return !\in_array($name, $excludes, true) && !\in_array($nameWithoutSuffix, $excludes, true);
}
return true;
});
$this->totalTestCount = \count($allFiles);
$this->subsetTestCount = \count($subset);
return $subset;
}
public function install()
{
if ($this->fields->get(self::TEST_DIR_FIELD) === null) {
$field = new Field();
$field->type = $this->modules->get('FieldtypeText');
$field->name = self::TEST_DIR_FIELD;
$field->label = $this->_('Tests directory');
$field->description = $this->_('Directory path where test files are located (relative to site root)');
$field->notes = $this->_('Eg. `/site/tests/`');
$field->showIf = 'process=ProcessNetteTester';
$field->required = 1;
$field->requiredIf = 'process=ProcessNetteTester';
$field->save();
// Add field to admin template
$adminTemplate = $this->templates->get('admin');
$adminTemplate->fields->add($field);
$adminTemplate->fields->save();
$this->message($this->_("Added field '" . self::TEST_DIR_FIELD . "' to admin template."));
}
}
public function uninstall()
{
// Remove tester_tests_directory field from admin template
$adminTemplate = $this->templates->get('admin');
if ($adminTemplate->fields->get(self::TEST_DIR_FIELD)) {
$adminTemplate->fields->remove($adminTemplate->fields->get(self::TEST_DIR_FIELD));
$adminTemplate->fields->save();
}
// Delete tester_tests_directory field
$field = $this->fields->get(self::TEST_DIR_FIELD);
if ($field) {
$this->fields->delete($field);
}
}
public function rglob($pattern, $flags = 0)
{
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
$files = array_merge($files, $this->rglob($dir . '/' . basename($pattern), $flags));
}
return $files;
}
public function renderControls()
{
$wrapper = new InputfieldWrapper();
/** @var InputfieldCheckboxes $f */
$f = $this->wire('modules')->get('InputfieldCheckboxes');
$f->name = 'controls';
$f->label = '';
$f->optionColumns = 1;
$f->skipLabel = true;
$f->themeBorder = 'none';
$f->wrapAttr('data-no-checkall-checkboxes', '1'); // aos
$f->collapsed = Inputfield::collapsedNever;
$f->addOption('testerStopOnFail',
$this->_('Stop on fail'),
array(
'title' => $this->_('Stop bulk run if a test fails or times out'),
));
$f->addOption('testerHidePassed',
$this->_('Hide passed'),
array(
'title' => $this->_('Hide passed tests from the list'),
));
$f->addOption('testerCountFailed',
$this->_('Count failed'),
array(
'title' => $this->_('Count failed test on the main display'),
));
$f->addOption('testerRetryFailed',
$this->_('Retry failed only'),
array(
'title' => $this->_('Skip passed test on restarting a bulk run'),
));
$f->addOption('testerAutoScroll',
$this->_('Autoscroll'),
array(
'title' => $this->_('Keep currently running tests within the viewport (bulk run only)'),
));
$f->addOption('testerShowBreadcrumbs',
$this->_('Show breadcrumbs'),
array(
'title' => $this->_('Show parent directories above test names'),
));
$wrapper->add($f);
return $wrapper->render();
}
public function renderMarkup()
{
$texts = $this->texts;
$total = $this->totalTestCount;
if ($total === 0) {
return sprintf($texts['noTestsFound'], $this->testDirName);
}
$jsonTexts = json_encode($texts, ENT_QUOTES | HTML_ENTITIES);
$maxTimeout = self::TIMEOUT * 1000;
$controls = $this->renderControls();
$tableMarkup = $this->renderTable();
if ($this->subsetTestCount < $this->totalTestCount) {
$introText = sprintf($texts['introSubset'], $this->subsetTestCount, '<a href="' . wire('page')->url . '">' . $total . '</a>');
} else {
$introText = $texts['intro'];
}
$display = <<< HTML
<div id="display" data-texts='$jsonTexts' data-max-timeout="$maxTimeout">
<h3><span class="counter">0</span></em><span class="total">{$this->subsetTestCount}</span><span id="main-launcher"><em>{$texts['run']}</em><em>{$texts['stop']}</em></span></h3>
</div>
HTML;
return <<< HTML
<div id="ProcessNetteTester-wrap">
$display
<div class="tester-data-container">
<div class="settings">
<p>{$introText} <i>{$this->testDirName}</i><br>
<small>{$texts['help']}</small>
</p>
<div id="controls">$controls</div>
</div>
$tableMarkup
</div>
</div>
HTML;
}
public function getAjaxResponse()
{
ini_set('max_execution_time', '120');
require_once __DIR__ . '/tester/src/bootstrap.php';
Environment::setup();
$isSuccess = true;
$testMethodCount = 0;
$msg = $this->texts['passed'];
$file = filter_input(INPUT_GET, 'testfile');
$time_pre = microtime(true);
try {
include $file;
} catch (\Error $error) {
$isSuccess = false;
$msg = $error->getMessage() . $this->getLineInfo($error->getLine());
} catch (\Exception $exception) {
$isSuccess = false;
$errorMsg = $exception->getMessage();
$line = $exception->getLine();
if ($exception instanceof AssertException) {
$errorMsg = $this->getModifiedDumperMessage($exception);
}
// get line number from trace
$trace = $exception->getTrace();
foreach ($trace as $info) {
// trace file name contains test basename
if (strpos($info['file'], basename($file)) !== false) {
$line = $info['line'];
break;
}
}
$msg = $errorMsg . $this->getLineInfo($line);
} finally {
$testInfo = '';
if ($isSuccess) {
$assertionsCount = Assert::$counter;
$testMethodCount = $this->countTestMethods($file);
$methodsText = $this->getTexts($testMethodCount === 1 ? 'test' : 'tests');
$assertionsText = $this->getTexts($assertionsCount === 1 ? 'assertion' : 'assertions');
$testInfo = "<i class='test-info'>$testMethodCount $methodsText · $assertionsCount $assertionsText</i>";
}
$data = array(
'result' => $msg . $testInfo,
'time' => $this->formatTime($exec_time = microtime(true) - $time_pre),
);
echo json_encode(array(
'success' => $isSuccess,
'data' => $data,
));
exit;
}
}
public function countTestMethods($file) {
$namespace = $this->extractNamespace($file);
if($namespace === null) {
return 0;
}
$methods = get_class_methods('\\' . trim($namespace, '\\') . '\\' . basename($file, '.php'));
if(!\is_array($methods)) {
return 0;
}
$methods = array_filter($methods, function($name) {
return substr($name, 0, 4) === 'test';
});
return count($methods);
}
public function renderTable()
{
$isTracyInstalled = $this->wire('modules')->isInstalled('TracyDebugger');
/** @var MarkupAdminDataTable $table */
$table = $this->wire('modules')->get('MarkupAdminDataTable');
$table->id = 'pnt-table';
$table->setEncodeEntities(false);
$table->addClass('ProcessNetteTester uk-table-striped');
$table->headerRow(array(
$this->texts['name'],
$this->texts['run'],
$this->texts['result'],
$this->texts['time'],
));
foreach ($this->testFiles as $file) {
$attributes = array('data-testfile' => $file);
$testPath = $this->testDirName . '/' . basename($file);
$editorAttr = !$isTracyInstalled ? '' : ' data-editor-url="' . ltrim($testPath, '\/') . '"';
$breadcrumb = str_replace($this->testDirPath, '', $file);
$tooltipText = $this->testDirName . '/' . $breadcrumb;
$breadcrumb = str_replace(basename($file), '', $breadcrumb);
if($breadcrumb !== '') {
$breadcrumb = '<span class="breadcrumb">' . $breadcrumb . '</span>';
}
$testName = '<i class="fa status-icon"></i><span title="' . $tooltipText . '"' . $editorAttr . '>' . $breadcrumb . basename($file, 'Test.php') . '</span>';
$table->row(array(
$testName,
$this->getAjaxButton($file),
self::EMPTY_VALUE,
self::EMPTY_VALUE,
), $attributes);
}
return $table->render();
}
public function getAjaxButton($file)
{
return '<a href="#" class="run-single ui-button ui-priority-primary" data-url="?testfile=' . $file . '"><i class="fa"></i></a>';
}
public function getTexts($key = null)
{
$texts = array(
'test' => $this->_('test'),
'tests' => $this->_('tests'),
'assertion' => $this->_('assertion'),
'assertions' => $this->_('assertions'),
'run' => $this->_('Start'),
'stop' => $this->_('Stop'),
'passed' => $this->_('Passed'),
'aborted' => $this->_('Aborted'),
'restart' => $this->_('Restart'),
'retryFailed' => $this->_('Retry failed'),
'timedout' => $this->_('Timed out'),
'total' => $this->_('Total: %f'),
'intro' => $this->_('All tests loaded from'),
'introSubset' => $this->_('%d of %s tests loaded from'),
'help' => $this->_('Click on the main counter to bulk run tests (spacebar). Ctrl+click to reset. Use the checkboxes to control behaviour.'),
'noTestsFound' => $this->_('No test files found in "%s".'),
'name' => $this->_('Name'),
'result' => $this->_('Result'),
'time' => $this->_('Time'),
'emptyValue' => self::EMPTY_VALUE,
'lineNum' => $this->_('on line %s'),
);
return $key === null ? $texts : $texts[$key];
}
protected function extractNamespace($file) {
$ns = null;
$handle = fopen($file, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$line = str_replace('<?php', '', $line);
$line = trim($line, " \t\r\n\0");
if (strpos($line, 'namespace') === 0) {
$parts = explode(' ', $line);
$ns = rtrim(trim($parts[1]), ';');
break;
}
}
fclose($handle);
}
return $ns;
}
}