-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple_unit_test.php
582 lines (580 loc) · 20.2 KB
/
simple_unit_test.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
<?php
/*********************************************************************
* Unit test *
* *
* Version: 1.5 *
* Date: 02-11-2018 *
* Author: Dan Machado *
* Require php 7 or above *
**********************************************************************/
namespace SimpleUnitTest;
ini_set('display_errors', 1);
error_reporting(E_ALL);
abstract class Unit_Test{
private static $url;
private static $source='';
private static $response=array('Errors'=>array());
private static $autoload;
private static $dummies;
private static $spies;
private static $custom_rtn=array();
private static $local_dummies=array();
private static $local_spies=array();
private static $local_custom_rtn=array();
protected static $CURL_OPTIONS=array(
CURLOPT_URL =>'',
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_ENCODING=>"",
CURLOPT_TIMEOUT=>30,
CURLOPT_POST=>1
);
private $source_file='';
private $_dummies=array();
private $_spies=array();
private $_autoload=array();
private $_custom_rtn=array();
private $reset_object;
protected $_meta;
protected $meta;
static private $_JSON_ERRORS=[
'No error has occurred.',
'The maximum stack depth has been exceeded.',
'Occurs with underflow or with the modes mismatch.',
'Control character error, possibly incorrectly encoded.',
'Syntax error.',
'Malformed UTF-8 characters, possibly incorrectly encoded.',
'The object or array passed to json_encode() include recursive references and cannot be encoded. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, NULL will be encoded in the place of the recursive reference.',
'The value passed to json_encode() includes either NAN or INF. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, 0 will be encoded in the place of these special numbers.',
'A value of an unsupported type was given to json_encode(), such as a resource. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, NULL will be encoded in the place of the unsupported value.',
'A key starting with \u0000 character was in the string passed to json_decode() when decoding a JSON object into a PHP object.',
'Single unpaired UTF-16 surrogate in unicode escape contained in the JSON string passed to json_encode().',
];
private static function outPut(){
$response=@ json_encode(self::$response, JSON_PRESERVE_ZERO_FRACTION);
if($jec=json_last_error()){
$response['Errors'][]=array(
'Message'=>self::$_JSON_ERRORS[$jec],
);
$response=json_encode($response);
}
ob_clean();
ob_start();
header('Content-Type: application/json');
header('Content-Length: ' . strlen($response));
print $response;
ob_end_flush();
}
public static function formated_error($error){
$formated_error='';
if($error){
foreach($error as $k=>$v){
$formated_error.=$k.': ' . $v . ' | ';
}
}
return $formated_error;
}
public static function SET_URL($_url=null){
if(!$_url){
die("Please set a URL for this project");
}
self::$url=$_url;
}
private static function set_source($_source=null){
if($_source){
self::$source=$_source;
}
if(self::$source){
include_once self::$source;
}
}
public function source_file($_source){
if(!$_source || !file_exists($_source)){
die("The source file \"{$_source}\" for this project does not exist.");
}
$this->source_file=$_source;
include_once $_source;
}
public static function Uncaught_Exception($exception){
$err=$exception->getMessage();
self::$response['Errors'][]=array(
'ErrorCode'=>4096,
'Message'=>$err,
'File'=>$exception->getFile(),
'Line'=>$exception->getLine(),
'Extra information'=>self::formated_error(error_get_last()),
);
self::outPut();
}
function __destruct(){
self::Fatal_Error();
}
public static function Fatal_Error(){
$error=error_get_last();
if($error!==NULL){
$error_codes=array(
1=>"E_ERROR 1 A fatal run-time error, that can't be recovered from. The execution of the script is stopped immediately.",
2=>"E_WARNING 2 A run-time warning. It is non-fatal and most errors tend to fall into this category. The execution of the script is not stopped.",
4=>"E_PARSE 4 The compile-time parse error. Parse errors should only be generated by the parser.",
8=>"E_NOTICE 8 A run-time notice indicating that the script encountered something that could possibly an error, although the situation could also occur when running a script normally.",
16=>"E_CORE_ERROR 16 A fatal error that occur during the PHP's engine initial startup. This is like an E_ERROR, except it is generated by the core of PHP.",
32=>"E_CORE_WARNING 32 A non-fatal error that occur during the PHP's engine initial startup. This is like an E_WARNING, except it is generated by the core of PHP.",
64=>"E_COMPILE_ERROR 64 A fatal error that occur while the script was being compiled. This is like an E_ERROR, except it is generated by the Zend Scripting Engine.",
128=>"E_COMPILE_WARNING 128 A non-fatal error occur while the script was being compiled. This is like an E_WARNING, except it is generated by the Zend Scripting Engine.",
256=>"E_USER_ERROR 256 A fatal user-generated error message. This is like an E_ERROR, except it is generated by the PHP code using the function trigger_error() rather than the PHP engine.",
512=>"E_USER_WARNING 512 A non-fatal user-generated warning message. This is like an E_WARNING, except it is generated by the PHP code using the function trigger_error() rather than the PHP engine",
1024=>"E_USER_NOTICE 1024 A user-generated notice message. This is like an E_NOTICE, except it is generated by the PHP code using the function trigger_error() rather than the PHP engine.",
2048=>"E_STRICT 2048 Not strictly an error, but triggered whenever PHP encounters code that could lead to problems or forward incompatibilities",
4096=>"E_RECOVERABLE_ERROR 4096 A catchable fatal error. Although the error was fatal, it did not leave the PHP engine in an unstable state. If the error is not caught by a user defined error handler (see set_error_handler()), the application aborts as it was an E_ERROR.",
8192=>"E_DEPRECATED 8192 A run-time notice indicating that the code will not work in future versions of PHP",
16384=>"E_USER_DEPRECATED 16384 A user-generated warning message. This is like an E_DEPRECATED, except it is generated by the PHP code using the function trigger_error() rather than the PHP engine.",
32767=>"E_ALL 32767 All errors and warnings, except of level E_STRICT prior to PHP 5.4.0."
);
if(!headers_sent() && isset($error_codes[$error['type']])) {
self::$response['Errors'][]=array('ErrorCode'=>$error['type'],'Message'=>self::formated_error($error));
}
else{
self::$response['Errors'][]=array('ErrorCode'=>'UNKNOWN ERROR','Message'=>self::formated_error($error));
}
self::outPut();
}
}
private static function curly($post, $f){
$curl_options=self::$CURL_OPTIONS;
$curl_options[CURLOPT_URL]=self::$url;
$curl_options[CURLOPT_POSTFIELDS]=$post;
$ch = curl_init();
curl_setopt_array($ch, $curl_options);
$f($ch);
}
public function test($method, array $test_data, $assertion=null){
$post['method']=$method;
$post['test_data']=$test_data;
$post['assertion']=$assertion;
$post['url']=self::$url;
$post['source']=$this->source_file;
$post['object_instance']=&$this->object_instance;
$post['meta']=$this->_meta;
$post['dummies']=$this->_dummies;
$post['autoload']=$this->_autoload;
$post['spies']=$this->_spies;
$post['custom_rtn']=$this->_custom_rtn;
$post['reset_object']=$this->reset_object;
self::curly(array('unit_test'=>1,'data'=>serialize($post)), function($ch){
$result=array('ResponseCode'=>500,'Message'=>'');
$raw_response=curl_exec($ch);
if(curl_errno($ch)==0 ){
$status_code=curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response=explode("\r\n\r\n", $raw_response);
$n=count($response)-1;
$body=trim($response[$n]);
if(!$result=@ json_decode($body, true)){
$result['ResponseCode']=$status_code;
unset($result['Message']);
}
}
else {
$result['Errors'][]=['ResponseCode'=>curl_errno($ch),'Message'=>curl_error($ch)];
}
curl_close($ch);
if(isset($result['object_instance']) && $this->reset_object==0){
$this->object_instance=$result['object_instance'];
unset($result['object_instance']);
}
$this->result[]=$result;
});
if($n=count($this->result)){
$this->result[$n-1]['Errors']=array_merge($this->result[$n-1]['Errors'], self::$response['Errors']);
self::$response['Errors']=array();
}
}
public function __construct(){
$params=func_get_args();
$this->_meta=[
'Class'=>array_shift($params),
'Parameters'=>$params,
];
$this->meta=$this->_meta;
$this->meta['Parameters']=implode('|',array_map('self::get_type',$this->_meta['Parameters']));
$this->reset_object=0;
$this->_autoload=[false, false];
$this->_dummies=[];
$this->_custom_rtn[$this->_meta['Class']]=array();
$this->object_instance='';
$this->_meta['Parameters']=serialize($this->_meta['Parameters']);
$this->__init();
}
public function autoload($autoload, $prepend=false){
$this->_autoload[0]=$autoload;
$this->_autoload[1]=(bool)$prepend;
}
public function reset_object($reset=0){
if($reset==1 || $reset==2){
$this->reset_object=$reset;
}
}
public function add_dummies($class_name, $methods, $use_namespace=null){
if(!isset($this->_dummies[$class_name])){
$this->_dummies[$class_name]=array('methods'=>array());
}
if($use_namespace){
$this->_dummies[$class_name]['use_namespace']=$use_namespace;
}
foreach($methods as $k=>$v){
if(is_callable($v, false)){
$this->_dummies[$class_name]['methods'][$k]=$v;
}
else{
self::$response['Errors'][]=['ErrorCode'=>4096,'Message'=>"Function: $v not found"];
}
}
}
public function custom_return(){
$args=func_get_args();
$method=array_shift($args);
if(is_callable($args[0], false)){
$this->_custom_rtn[$this->_meta['Class']][$method]=$args;
}
else{
self::$response['Errors'][]=['ErrorCode'=>4096,'Message'=>"Function: {$args[0]} not found"];
}
}
public function add_spy(){
$args=func_get_args();
$class_name=array_shift($args);
if(!isset($this->_spies[$class_name])){
$this->_spies[$class_name]=array();
}
$method=array_shift($args);
$position=array_shift($args);
if($position!='begin'){
$position='end';
}
if(is_callable($args[0], false)){
$token="{$method}:{$position}";
$this->_spies[$class_name][$token]=$args;
}
else{
self::$response['Errors'][]=array('ErrorCode'=>4096,'Message'=>"Function: {$args[0]} not found",);
}
}
private static function evaluation($result, $expected, $assertion=null){
if(!$assertion){
if(is_nan($expected)){
return is_nan($result);
}
if(is_infinite($expected)){
return is_infinite($result);
}
return $result==$expected;
}
else{
if($assertion=='==='){
return $result===$expected;
}
if(is_callable($assertion, false)){
return call_user_func($assertion, $result, $expected);
}
else{
self::$response['Errors'][]=['ErrorCode'=>4096,'Message'=>"Function: $assertion not found"];
}
}
}
private static function get_type(&$result){
if(is_object($result)){
return get_class($result);
}
else{
return var_export($result, true);
}
}
public static function run_test(){
$input=unserialize($_POST['data']);
self::$response['Method']=$input['method'];
self::$response['Tests']=array();
self::$url=$input['url'];
self::$autoload=$input['autoload'][0];
self::$dummies=$input['dummies'];
self::$spies=$input['spies'];
self::$custom_rtn=$input['custom_rtn'];
self::set_source($input['source']);
try{
if($input['autoload'][0]){
if(is_callable($input['autoload'][0], false)){
spl_autoload_register('self::dummy_loader', true, $input['autoload'][1]);
}
else{
self::$response['Errors'][]=['ErrorCode'=>4096,'Message'=>"Function: {$input['autoload'][0]} not found"];
}
}
$reflexion_class= new \ReflectionClass($input['meta']['Class']);
$x_instance_class='';
if(!$input['object_instance']){
$instance_class=$reflexion_class->newInstanceArgs(unserialize($input['meta']['Parameters']));
if($input['reset_object']==2){
$x_instance_class=serialize($instance_class);
}
}
else{
$instance_class=unserialize($input['object_instance']);
}
if($reflexion_class->hasMethod($input['method'])){
$method_test = $reflexion_class->getMethod($input['method']);
if(!$method_test->isPublic()) {
$method_test->setAccessible(true);
}
$etime=0;
$test_id=0;
foreach($input['test_data'] as $data){
$test=array_shift($data);
$expected=array_shift($data);
$mstart = memory_get_usage();
$etime=microtime(true);
$msg='';
$warnings='';
$result='n/a';
try{
if($input['reset_object']==2){
$instance_class=unserialize($x_instance_class);
}
$result=$method_test->invokeArgs($instance_class, $data);
if(self::evaluation($result, $expected, $input['assertion'])){
$status='Passed';
}
else{
$status='Failed';
}
$wrns=error_get_last();
if($wrns){
$warnings=self::formated_error($wrns);
}
}
catch(\Exception $e){
$status='An exception was thrown';
$msg=$e->getMessage();
}
$etime=microtime(true)-$etime;
$mend = memory_get_usage();
$mb=sprintf('%.3f',($mend - $mstart) / 1024 / 1024);
$params=array();
foreach($data as $par){
$params[]=gettype($par) . ': '. var_export($par, true);
}
if(isset(self::$response['Tests'][$test])){
$test.=$test_id;
$test_id++;
}
self::$response['Tests'][$test]=array(
'Status'=>$status,
'Result'=>self::get_type($result),
'Expected Value'=>self::get_type($expected),
'Parameters'=>$params,
'Elapsed Time'=>sprintf('%.6f',$etime),
'Memory Usage'=>$mb,
'Exception'=>$msg,
'Warnings'=>$warnings,
);
}
self::$response['object_instance']=serialize($instance_class);
}
else {
self::$response['Errors'][]=array('ErrorCode'=>4096,'Message'=>"The {$input['method']} does not exist",);
}
}
catch (\Exception $e){
self::$response['Errors'][]=array('ErrorCode'=>4096,'Message'=>'Exception: ' . $e->getMessage(),);
}
self::outPut();
}
public static function dummy_loader($class){
self::set_source();
if(isset(self::$dummies[$class]) || isset(self::$spies[$class]) || count(self::$custom_rtn[$class])){
$result='';
$post=['factory'=>1,'autoload'=>self::$autoload,'class'=>$class, 'source'=>self::$source];
if(isset(self::$dummies[$class])){
$post['dummies']=json_encode(self::$dummies[$class]);
}
if(isset(self::$spies[$class])){
$post['spies']=json_encode(self::$spies[$class]);
}
if(isset(self::$custom_rtn[$class])){
$post['custom_rtn']=json_encode(self::$custom_rtn[$class]);
}
self::curly($post, function($ch) use(&$result){
$raw_response=curl_exec($ch);
if(curl_errno($ch)==0 ){
$status_code=curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response=explode("\r\n\r\n", $raw_response);
$n=count($response)-1;
$result=json_decode(trim($response[$n]), true);
}
curl_close($ch);
});
if(count($result[1])){
self::$response['Errors'][]=$result[1][0];
}
else{
$dummy_class=base64_decode($result[0]);
eval($dummy_class);
}
}
else{
call_user_func(self::$autoload, $class);
}
}
private static function set_custom_rtn($method){
if(isset(self::$local_custom_rtn[$method])){
$ck=array_shift(self::$local_custom_rtn[$method]);
$str='';
foreach(self::$local_custom_rtn[$method] as $arg){
$str.='$'.$arg.',';
}
$str=trim($str, ',');
if($str){
$str=", " . $str;
}
return "return call_user_func('{$ck}'" . $str . ");\n";
}
return '';
}
private static function get_spy($class, $method, $data){
if(isset(self::$local_spies[$data])){
$ck=array_shift(self::$local_spies[$data]);
$str='';
foreach(self::$local_spies[$data] as $arg){
$str.='$'.$arg.',';
}
$str=trim($str, ',');
if($str){
$str=", " . $str;
}
return "Test::spy('{$class}', '{$method}','{$ck}'" . $str . ");\n";
}
return '';
}
public static function spy(){
$args=func_get_args();
$class=array_shift($args);
$method=array_shift($args);
$func=array_shift($args);
if(!isset(self::$response['SpyLog'][$class.'::'.$method][$func])){
self::$response['SpyLog'][$class.'::'.$method][$func]=array();
}
self::$response['SpyLog'][$class.'::'.$method][$func][]=call_user_func_array($func, $args);
}
private static function sustitution($method){
if(isset(self::$local_dummies[$method])){
return '$args=func_get_args();
return call_user_func_array(\''. self::$local_dummies[$method] .'\', $args);' . "\n";
}
return '';
}
public static function factory(){
$post_data=&$_POST;
if(isset($post_data['dummies'])){
$post_data['dummies']=json_decode($post_data['dummies'], true);
self::$local_dummies=$post_data['dummies']['methods'];
}
if(isset($post_data['spies'])){
self::$local_spies=json_decode($post_data['spies'], true);
}
if(isset($post_data['custom_rtn'])){
self::$local_custom_rtn=json_decode($post_data['custom_rtn'], true);
}
self::set_source($post_data['source']);
spl_autoload_register($post_data['autoload']);
$class= new \ReflectionClass($post_data['class']);
$class_name=$class->getName();
$stl=$class->getStartLine()-1;
$enl=$class->getEndLine()-1;
$file=$class->getFileName();
$dummy_class='';
$c = file($file);
for($i=0; $i<$stl; $i++){
if(strpos($c[$i], 'namespace')!==false){
$dummy_class.=$c[$i];
}
elseif(strpos($c[$i], 'use ')!==false){
$dummy_class.=$c[$i];
}
elseif(strpos($c[$i], 'include ')!==false){
$dummy_class.=$c[$i];
}
elseif(strpos($c[$i], 'require ')!==false){
$dummy_class.=$c[$i];
}
}
if(isset($post_data['dummies']['use_namespace'])){
$dummy_class.='use '.$post_data['dummies']['use_namespace'] . ";\n";
}
$dummy_class.="use SimpleUnitTest\Test;\n";
$mm=array();
$mtd_names=array();
$sp_names=array();
foreach($class->getMethods() as $method){
if(isset($post_data['dummies']['methods'][$method->name])){
$mtd_names[$method->getStartLine()-1]=$method->name;
}
$sp_names[$method->getStartLine()-1]=$method->name;
$mm[]=$method->getStartLine()-1;
$mm[]=$method->getEndLine()-1;
}
sort($mm);
$k=0;
for($i=$stl; $i<=$enl; $i++){
if(!isset($mm[$k]) || $i!=$mm[$k]){
$dummy_class.=$c[$i];
}
else{
if(isset($mtd_names[$i])){
$dummy_class.=$c[$i];
if(strpos($c[$i], '{')===false){
$dummy_class.="{\n";
}
$dummy_class.=self::sustitution($mtd_names[$i])."
}\n";
$i=$mm[$k+1];
}
else{
$spm=$sp_names[$mm[$k]];
$a=true;
$j=1;
$dummy_class.=$c[$mm[$k]];
if(strpos($c[$mm[$k]], '{')===false){
$dummy_class.="{\n";
$j++;
}
$dummy_class.=self::get_spy($class_name, $spm, "{$spm}:begin") . "\n";
for($i=$mm[$k]+$j; $i<=$mm[$k+1]; $i++) {
if($a && (strpos(trim($c[$i]), 'return')===0 || $i==$mm[$k+1])){
$a=false;
$dummy_class.=self::set_custom_rtn($spm);
$dummy_class.=self::get_spy($class_name, $spm, "{$spm}:end");
}
$dummy_class.=$c[$i];
}
$i--;
}
$k+=2;
}
}
return $result=json_encode([base64_encode($dummy_class),self::$response['Errors']]);
return $dummy_class;
}
abstract public function print_results();
abstract protected function __init();
}
include __DIR__ . '/extend_simpleunittest.php';
if(count($_POST)){
if(isset($_POST['unit_test'])){
register_shutdown_function('SimpleUnitTest\Test::Fatal_Error', E_ALL);
set_error_handler('SimpleUnitTest\Test::Fatal_Error', E_ALL);
set_exception_handler('SimpleUnitTest\Test::Uncaught_Exception');
Test::run_test();
}
elseif(isset($_POST['factory'])){
echo Test::factory();
}
exit;
}
include __DIR__ . '/header.html';
?>