forked from andrewscofield/parse.com-php-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EnhanceTestFramework.php
1743 lines (1516 loc) · 51.7 KB
/
EnhanceTestFramework.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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Enhance;
ini_set('error_reporting', (string)E_ALL);
ini_set('display_errors', '1');
// Public API
class Core
{
/** @var EnhanceTestFramework $Instance */
private static $Instance;
private static $Language = Language::English;
/** @return Language */
public static function getLanguage()
{
return self::$Language;
}
public static function setLanguage($language)
{
self::$Language = $language;
}
public static function discoverTests($path, $isRecursive = true, $excludeRules = array())
{
self::setInstance();
self::$Instance->discoverTests($path, $isRecursive, $excludeRules);
}
public static function runTests($output = TemplateType::Html)
{
self::setInstance();
self::$Instance->runTests($output);
}
public static function getCodeCoverageWrapper($className, $args = null)
{
self::setInstance();
self::$Instance->registerForCodeCoverage($className);
return new CodeCoverageWrapper($className, $args);
}
public static function log($className, $methodName)
{
self::setInstance();
self::$Instance->log($className, $methodName);
}
public static function getScenario($className, $args = null)
{
return new Scenario($className, $args, self::$Language);
}
public static function setInstance()
{
if (self::$Instance === null) {
self::$Instance = new EnhanceTestFramework(self::$Language);
}
}
}
// Public API
class TestFixture
{
}
// Public API
class MockFactory
{
public static function createMock($typeName)
{
return new Mock($typeName, true, Core::getLanguage());
}
}
// Public API
class StubFactory
{
public static function createStub($typeName)
{
return new Mock($typeName, false, Core::getLanguage());
}
}
// Public API
class Expect
{
const AnyValue = 'ENHANCE_ANY_VALUE_WILL_DO';
public static function method($methodName)
{
$expectation = new Expectation(Core::getLanguage());
return $expectation->method($methodName);
}
public static function getProperty($propertyName)
{
$expectation = new Expectation(Core::getLanguage());
return $expectation->getProperty($propertyName);
}
public static function setProperty($propertyName)
{
$expectation = new Expectation(Core::getLanguage());
return $expectation->setProperty($propertyName);
}
}
// Public API
class Assert
{
/** @var Assertions $EnhanceAssertions */
private static $EnhanceAssertions;
private static function GetEnhanceAssertionsInstance()
{
if(self::$EnhanceAssertions === null) {
self::$EnhanceAssertions = new Assertions(Core::getLanguage());
}
return self::$EnhanceAssertions;
}
public static function areIdentical($expected, $actual)
{
self::GetEnhanceAssertionsInstance()->areIdentical($expected, $actual);
}
public static function areNotIdentical($expected, $actual)
{
self::GetEnhanceAssertionsInstance()->areNotIdentical($expected, $actual);
}
public static function isTrue($actual)
{
self::GetEnhanceAssertionsInstance()->isTrue($actual);
}
public static function isFalse($actual)
{
self::GetEnhanceAssertionsInstance()->isFalse($actual);
}
public static function isNull($actual)
{
self::GetEnhanceAssertionsInstance()->isNull($actual);
}
public static function isNotNull($actual)
{
self::GetEnhanceAssertionsInstance()->isNotNull($actual);
}
public static function isArray($actual)
{
self::GetEnhanceAssertionsInstance()->isArray($actual);
}
public static function isNotArray($actual)
{
self::GetEnhanceAssertionsInstance()->isNotArray($actual);
}
public static function isBool($actual)
{
self::GetEnhanceAssertionsInstance()->isBool($actual);
}
public static function isNotBool($actual)
{
self::GetEnhanceAssertionsInstance()->isNotBool($actual);
}
public static function isFloat($actual)
{
self::GetEnhanceAssertionsInstance()->isFloat($actual);
}
public static function isNotFloat($actual)
{
self::GetEnhanceAssertionsInstance()->isNotFloat($actual);
}
public static function isInt($actual)
{
self::GetEnhanceAssertionsInstance()->isInt($actual);
}
public static function isNotInt($actual)
{
self::GetEnhanceAssertionsInstance()->isNotInt($actual);
}
public static function isNumeric($actual)
{
self::GetEnhanceAssertionsInstance()->isNumeric($actual);
}
public static function isNotNumeric($actual)
{
self::GetEnhanceAssertionsInstance()->isNotNumeric($actual);
}
public static function isObject($actual)
{
self::GetEnhanceAssertionsInstance()->isObject($actual);
}
public static function isNotObject($actual)
{
self::GetEnhanceAssertionsInstance()->isNotObject($actual);
}
public static function isResource($actual)
{
self::GetEnhanceAssertionsInstance()->isResource($actual);
}
public static function isNotResource($actual)
{
self::GetEnhanceAssertionsInstance()->isNotResource($actual);
}
public static function isScalar($actual)
{
self::GetEnhanceAssertionsInstance()->isScalar($actual);
}
public static function isNotScalar($actual)
{
self::GetEnhanceAssertionsInstance()->isNotScalar($actual);
}
public static function isString($actual)
{
self::GetEnhanceAssertionsInstance()->isString($actual);
}
public static function isNotString($actual)
{
self::GetEnhanceAssertionsInstance()->isNotString($actual);
}
public static function contains($expected, $actual)
{
self::GetEnhanceAssertionsInstance()->contains($expected, $actual);
}
public static function notContains($expected, $actual)
{
self::GetEnhanceAssertionsInstance()->notContains($expected, $actual);
}
public static function fail()
{
self::GetEnhanceAssertionsInstance()->fail();
}
public static function inconclusive()
{
self::GetEnhanceAssertionsInstance()->inconclusive();
}
public static function isInstanceOfType($expected, $actual)
{
self::GetEnhanceAssertionsInstance()->isInstanceOfType($expected, $actual);
}
public static function isNotInstanceOfType($expected, $actual)
{
self::GetEnhanceAssertionsInstance()->isNotInstanceOfType($expected, $actual);
}
public static function throws($class, $methodName, $args = null)
{
self::GetEnhanceAssertionsInstance()->throws($class, $methodName, $args);
}
}
// Internal Workings
// You don't need to call any of these bits directly - use the public API above, which will
// use the stuff below to carry out your tests!
class TextFactory
{
public static $Text;
public static function getLanguageText($language)
{
if (self::$Text === null) {
$languageClass = 'Enhance\Text' . $language;
self::$Text = new $languageClass();
}
return self::$Text;
}
}
class TextEn
{
public $FormatForTestRunTook = 'Test run took {0} seconds';
public $FormatForExpectedButWas = 'Expected {0} but was {1}';
public $FormatForExpectedNotButWas = 'Expected NOT {0} but was {1}';
public $FormatForExpectedContainsButWas = 'Expected to contain {0} but was {1}';
public $FormatForExpectedNotContainsButWas = 'Expected NOT to contain {0} but was {1}';
public $EnhanceTestFramework = 'Enhance Test Framework';
public $EnhanceTestFrameworkFull = 'Enhance PHP Unit Testing Framework';
public $TestResults = 'Test Results';
public $Test = 'Test';
public $TestPassed = 'Test Passed';
public $TestFailed = 'Test Failed';
public $Passed = 'Passed';
public $Failed = 'Failed';
public $ExpectationFailed = 'Expectation failed';
public $Expected = 'Expected';
public $Called = 'Called';
public $InconclusiveOrNotImplemented = 'Inconclusive or not implemented';
public $Times = 'Times';
public $MethodCoverage = 'Method Coverage';
public $Copyright = 'Copyright';
public $ExpectedExceptionNotThrown = 'Expected exception was not thrown';
public $CannotCallVerifyOnStub = 'Cannot call VerifyExpectations on a stub';
public $ReturnsOrThrowsNotBoth = 'You must only set a single return value (1 returns() or 1 throws())';
public $ScenarioWithExpectMismatch = 'Scenario must be initialised with the same number of "with" and "expect" calls';
public $LineFile = 'Line {0} in file {1}';
}
class TextDe
{
public $FormatForTestRunTook = 'Fertig nach {0} Sekunden';
public $FormatForExpectedButWas = 'Erwartet {0} aber war {1}';
public $FormatForExpectedNotButWas = 'Erwartet nicht {0} aber war {1}';
public $FormatForExpectedContainsButWas = 'Erwartet {0} zu enthalten, aber war {1}';
public $FormatForExpectedNotContainsButWas = 'Erwartet {0} nicht zu enthalten, aber war {1}';
public $EnhanceTestFramework = 'Enhance Test-Rahmen';
public $EnhanceTestFrameworkFull = 'Maßeinheits-Prüfungs-Rahmen';
public $TestResults = 'Testergebnisse';
public $Test = 'Test';
public $TestPassed = 'Test bestehen';
public $TestFailed = 'Test durchfallen';
public $Passed = 'Bestehen';
public $Failed = 'Durchfallen';
public $ExpectationFailed = 'Erwartung durchfallen';
public $Expected = 'Erwartet';
public $Called = 'Benannt';
public $InconclusiveOrNotImplemented = 'Unbestimmt oder nicht durchgefuert';
public $Times = 'Ereignisse';
public $MethodCoverage = 'Methodenbehandlung';
public $Copyright = 'Copyright';
public $ExpectedExceptionNotThrown = 'Die Ausnahme wird nicht ausgeloest';
public $CannotCallVerifyOnStub = 'Kann VerifyExpectations auf einem Stub nicht aufrufen';
public $ReturnsOrThrowsNotBoth = 'Sie müssen einen einzelnen Return Value nur einstellen';
public $ScenarioWithExpectMismatch = 'Szenarium muss mit der gleichen Zahl von "With" und "Expect" calls initialisiert werden';
public $LineFile = 'Zeile {0} der Datei {1}';
public $TypeOfVar=" Typ: ";
}
class TextPtBr
{
public $FormatForTestRunTook = 'Execução de teste levou {0} segundos';
public $FormatForExpectedButWas = 'Esperado {0} mas foi {1}';
public $FormatForExpectedNotButWas = 'Não era esperado {0} mas foi {1}';
public $FormatForExpectedContainsButWas = 'Era esperado ser {0} mas foi {1}';
public $FormatForExpectedNotContainsButWas = 'Não era esperado seer {0} mas foi {1}';
public $EnhanceTestFramework = 'Framework de teste Enhance';
public $EnhanceTestFrameworkFull = 'Framework de teste unitário com PHP Enhance';
public $TestResults = 'Resultado do teste';
public $Test = 'Teste';
public $TestPassed = 'Teste passou';
public $TestFailed = 'Teste falhou';
public $Passed = 'Passou';
public $Failed = 'Falhou';
public $ExpectationFailed = 'Probabilidade falhou';
public $Expected = 'Probabilidade';
public $Called = 'Chamado';
public $InconclusiveOrNotImplemented = 'Inconclusivo ou não implementado';
public $Times = 'Vezes';
public $MethodCoverage = 'Cobertura de método';
public $Copyright = 'Direitos autorais';
public $ExpectedExceptionNotThrown = 'Exceção esperada não ocorreu';
public $CannotCallVerifyOnStub = 'Não foi possível chamar um esboço de VerifyExpectations';
public $ReturnsOrThrowsNotBoth = 'Você só deve definer um único valor de retorno (1 retorno() ou 1 throw())';
public $ScenarioWithExpectMismatch = 'Cenário deve ser iniciado com o mesmo número de chamadas de "with" e "expect"';
public $LineFile = 'Linha {0} no arquivo {1}';
public $TypeOfVar=" Tipo: ";
}
class TextSp
{
public $FormatForTestRunTook = 'La ejecución de las pruebas tomó {0} segundos';
public $FormatForExpectedButWas = 'Se esperaba {0} pero se obuvo {1}';
public $FormatForExpectedNotButWas = 'Se esperada Negación {0} pero se obtuvo {1}';
public $FormatForExpectedContainsButWas = 'Se esperaba tuviera {0} pero se obtuvo {1}';
public $FormatForExpectedNotContainsButWas = 'Se esperaba NO tuviera {0} pero se obtuvo {1}';
public $EnhanceTestFramework = 'Enhance Test Framework';
public $EnhanceTestFrameworkFull = 'Enhance PHP Unit Herramienta de pruebas';
public $TestResults = 'Resultado de las pruebas';
public $Test = 'Prueba';
public $TestPassed = 'Prueba pasó';
public $TestFailed = 'Prueba Fallo';
public $Passed = 'Pasó';
public $Failed = 'Fallo';
public $ExpectationFailed = 'Fallo en valor esperado';
public $Expected = 'Esperado';
public $Called = 'Llamada';
public $InconclusiveOrNotImplemented = 'Inconcluso o no implementado';
public $Times = 'Veces';
public $MethodCoverage = 'Covertura de Métodos';
public $Copyright = 'Copyright';
public $ExpectedExceptionNotThrown = 'La excepción esperada no fue generada';
public $CannotCallVerifyOnStub = 'No se puede llamar VerifyExpectations en un stub';
public $ReturnsOrThrowsNotBoth = 'Debe proporcionar un solo valor de retorno (1 returns() ó 1 throws())';
public $ScenarioWithExpectMismatch = 'Escenario debe ser inicializado con el mismo número de llamadas "with" y "expect" ';
public $LineFile = 'Linha {0} no arquivo {1}';
public $TypeOfVar=" Tipo: ";
}
class EnhanceTestFramework
{
private $FileSystem;
private $Text;
private $Tests = array();
private $Results = array();
private $Errors = array();
private $Duration;
private $MethodCalls = array();
private $Language;
public function __construct($language)
{
$this->Text = TextFactory::getLanguageText($language);
$this->FileSystem = new FileSystem();
$this->Language = $language;
}
public function discoverTests($path, $isRecursive, $excludeRules)
{
$directory = rtrim($path, '/');
if (is_dir($directory)) {
$phpFiles = $this->FileSystem->getFilesFromDirectory($directory, $isRecursive, $excludeRules);
foreach ($phpFiles as $file) {
/** @noinspection PhpIncludeInspection */
include_once($file);
}
}
}
public function runTests($output)
{
$this->getTestFixturesByParent();
$this->run();
if(PHP_SAPI === 'cli' && $output != TemplateType::Tap) {
$output = TemplateType::Cli;
}
$OutputTemplate = TemplateFactory::createOutputTemplate($output, $this->Language);
echo $OutputTemplate->get(
$this->Errors,
$this->Results,
$this->Text,
$this->Duration,
$this->MethodCalls
);
if (count($this->Errors) > 0) {
exit(1);
} else {
exit(0);
}
}
public function log($className, $methodName)
{
$index = $this->getMethodIndex($className, $methodName);
if (array_key_exists($index ,$this->MethodCalls)) {
$this->MethodCalls[$index] = $this->MethodCalls[$index] + 1;
}
}
public function registerForCodeCoverage($className)
{
$classMethods = get_class_methods($className);
foreach($classMethods as $methodName) {
$index = $this->getMethodIndex($className, $methodName);
if (!array_key_exists($index ,$this->MethodCalls)) {
$this->MethodCalls[$index] = 0;
}
}
}
private function getMethodIndex($className, $methodName)
{
return $className . '#' . $methodName;
}
private function getTestFixturesByParent()
{
$classes = get_declared_classes();
foreach($classes as $className) {
$this->AddClassIfTest($className);
}
}
private function AddClassIfTest($className)
{
$parentClassName = get_parent_class($className);
if ($parentClassName === 'Enhance\TestFixture') {
$instance = new $className();
$this->addFixture($instance);
} else {
$ancestorClassName = get_parent_class($parentClassName);
if ($ancestorClassName === 'Enhance\TestFixture') {
$instance = new $className();
$this->addFixture($instance);
}
}
}
private function addFixture($class)
{
$classMethods = get_class_methods($class);
foreach($classMethods as $method) {
if (strtolower($method) !== 'setup' && strtolower($method) !== 'teardown') {
$reflection = new \ReflectionMethod($class, $method);
if ($reflection->isPublic()) {
$this->addTest($class, $method);
}
}
}
}
private function addTest($class, $method)
{
$testMethod = new Test($class, $method);
$this->Tests[] = $testMethod;
}
private function run()
{
$start = microtime(true);
foreach($this->Tests as /** @var Test $test */ $test) {
$result = $test->run();
if ($result) {
$message = $test->getTestName() . ' - ' . $this->Text->Passed;
$this->Results[] = new TestMessage($message, $test, true);
} else {
$message = '['. str_replace('{0}', $test->getLine(), str_replace('{1}', $test->getFile(), $this->Text->LineFile)) . '] ' .
$test->getTestName() . ' - ' .
$this->Text->Failed . ' - ' . $test->getMessage();
$this->Errors[] = new TestMessage($message, $test, false);
}
}
$this->Duration = microtime(true) - $start;
}
}
class FileSystem
{
public function getFilesFromDirectory($directory, $isRecursive, $excludeRules)
{
$files = array();
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && strpos($file, '.') !== 0) {
if ($this->isFolderExcluded($file, $excludeRules)){
continue;
}
if(is_dir($directory . '/' . $file)) {
if ($isRecursive) {
$dir2 = $directory . '/' . $file;
$files[] = $this->getFilesFromDirectory($dir2, $isRecursive, $excludeRules);
}
} else {
$files[] = $directory . '/' . $file;
}
}
}
closedir($handle);
}
return $this->flattenArray($files);
}
private function isFolderExcluded($folder, $excludeRules)
{
$folder = substr($folder, strrpos($folder, '/'));
foreach ($excludeRules as $excluded){
if ($folder === $excluded){
return true;
}
}
return false;
}
public function flattenArray($array)
{
$merged = array();
foreach($array as $a) {
if(is_array($a)) {
$merged = array_merge($merged, $this->flattenArray($a));
} else {
$merged[] = $a;
}
}
return $merged;
}
}
class TestMessage
{
public $Message;
public $Test;
public $IsPass;
public function __construct($message, $test, $isPass)
{
$this->Message = $message;
$this->Test = $test;
$this->IsPass = $isPass;
}
}
class Test
{
private $ClassName;
private $TestName;
private $TestMethod;
private $SetUpMethod;
private $TearDownMethod;
private $Message;
private $Line;
private $File;
public function __construct($class, $method)
{
$className = get_class($class);
$this->ClassName = $className;
$this->TestMethod = array($className, $method);
$this->SetUpMethod = array($className, 'setUp');
$this->TearDownMethod = array($className, 'tearDown');
$this->TestName = $method;
}
public function getTestName()
{
return $this->TestName;
}
public function getClassName()
{
return $this->ClassName;
}
public function getMessage()
{
return $this->Message;
}
public function getLine()
{
return $this->Line;
}
public function getFile()
{
return $this->File;
}
public function run()
{
/** @var $testClass iTestable */
$testClass = new $this->ClassName();
try {
if (is_callable($this->SetUpMethod)) {
$testClass->setUp();
}
} catch (\Exception $e) { }
try {
$testClass->{$this->TestName}();
$result = true;
} catch (TestException $e) {
$this->Message = $e->getMessage();
$this->Line = $e->getLine();
$this->File = pathinfo($e->getFile(), PATHINFO_BASENAME);
$result = false;
}
try {
if (is_callable($this->TearDownMethod)) {
$testClass->tearDown();
}
} catch (\Exception $e) { }
return $result;
}
}
class CodeCoverageWrapper
{
private $Instance;
private $ClassName;
public function __construct($className, $args)
{
$this->ClassName = $className;
if ($args !== null) {
$rc = new \ReflectionClass($className);
$this->Instance = $rc->newInstanceArgs($args);
} else {
$this->Instance = new $className();
}
Core::log($this->ClassName, $className);
Core::log($this->ClassName, '__construct');
}
public function __call($methodName, $args = null)
{
Core::log($this->ClassName, $methodName);
if ($args !== null) {
/** @noinspection PhpParamsInspection */
return call_user_func_array(array($this->Instance, $methodName), $args);
} else {
return $this->Instance->{$methodName}();
}
}
public function __get($propertyName)
{
return $this->Instance->{$propertyName};
}
public function __set($propertyName, $value)
{
$this->Instance->{$propertyName} = $value;
}
}
class Mock
{
private $IsMock;
private $Text;
private $ClassName;
private $Expectations = array();
public function __construct($className, $isMock, $language)
{
$this->IsMock = $isMock;
$this->ClassName = $className;
$this->Text = TextFactory::getLanguageText($language);
}
public function addExpectation($expectation)
{
$this->Expectations[] = $expectation;
}
public function verifyExpectations()
{
if (!$this->IsMock) {
throw new \Exception(
$this->ClassName . ': ' . $this->Text->CannotCallVerifyOnStub
);
}
foreach ($this->Expectations as /** @var Expectation $expectation */ $expectation) {
if (!$expectation->verify()) {
$Arguments = '';
if (isset($expectation->MethodArguments)) {
foreach($expectation->MethodArguments as $argument) {
if (isset($Arguments[0])) {
$Arguments .= ', ';
}
$Arguments .= $argument;
}
}
throw new \Exception(
$this->Text->ExpectationFailed . ' ' .
$this->ClassName . '->' . $expectation->MethodName . '(' . $Arguments . ') ' .
$this->Text->Expected . ' #' . $expectation->ExpectedCalls . ' ' .
$this->Text->Called . ' #' . $expectation->ActualCalls, 0);
}
}
}
public function __call($methodName, $args)
{
return $this->getReturnValue('method', $methodName, $args);
}
public function __get($propertyName)
{
return $this->getReturnValue('getProperty', $propertyName, array());
}
public function __set($propertyName, $value)
{
$this->getReturnValue('setProperty', $propertyName, array($value));
}
private function getReturnValue($type, $methodName, $args)
{
$Expectation = $this->getMatchingExpectation($type, $methodName, $args);
$Expected = true;
if ($Expectation === null) {
$Expected = false;
}
if ($Expected) {
++$Expectation->ActualCalls;
if ($Expectation->ReturnException) {
throw new \Exception($Expectation->ReturnValue);
}
return $Expectation->ReturnValue;
}
if ($this->IsMock) {
throw new \Exception(
$this->Text->ExpectationFailed . ' ' .
$this->ClassName . '->' . $methodName . '(' . $args . ') ' .
$this->Text->Expected . ' #0 ' .
$this->Text->Called . ' #1', 0);
}
return null;
}
private function getMatchingExpectation($type, $methodName, $arguments)
{
foreach ($this->Expectations as $expectation) {
if ($expectation->Type === $type) {
if ($expectation->MethodName === $methodName) {
$isMatch = true;
if ($expectation->ExpectArguments) {
$isMatch = $this->argumentsMatch(
$expectation->MethodArguments,
$arguments
);
}
if ($isMatch) {
return $expectation;
}
}
}
}
return null;
}
private function argumentsMatch($arguments1, $arguments2)
{
$Count1 = count($arguments1);
$Count2 = count($arguments2);
$isMatch = true;
if ($Count1 === $Count2) {
for ($i = 0; $i < $Count1; ++$i) {
if ($arguments1[$i] === Expect::AnyValue
|| $arguments2[$i] === Expect::AnyValue) {
// No need to match
} else {
if ($arguments1[$i] !== $arguments2[$i]) {
$isMatch = false;
}
}
}
} else {
$isMatch = false;
}
return $isMatch;
}
}
class Scenario
{
private $Text;
private $Class;
private $FunctionName;
private $Inputs = array();
private $Expectations = array();
public function __construct($class, $functionName, $language)
{
$this->Class = $class;
$this->FunctionName = $functionName;
$this->Text = TextFactory::getLanguageText($language);
}
public function with()
{
$this->Inputs[] = func_get_args();
return $this;
}
public function expect()
{
$this->Expectations[] = func_get_args();
return $this;
}
public function verifyExpectations()
{
if (count($this->Inputs) !== count($this->Expectations)) {
throw new \Exception($this->Text->ScenarioWithExpectMismatch);
}
$exceptionText = '';
while(count($this->Inputs) > 0) {
$input = array_shift($this->Inputs);
$expected = array_shift($this->Expectations);
$expected = $expected[0];
$actual = call_user_func_array(array($this->Class, $this->FunctionName), $input);
if (is_float($expected)) {
if ((string)$expected !== (string)$actual) {
$exceptionText .= str_replace('{0}', $expected, str_replace('{1}', $actual, $this->Text->FormatForExpectedButWas));
}
} elseif ($expected != $actual) {
$exceptionText .= str_replace('{0}', $expected, str_replace('{1}', $actual, $this->Text->FormatForExpectedButWas));
}
}
if ($exceptionText !== ''){
throw new \Exception($exceptionText, 0);
}
}
}
class Expectation
{
public $MethodName;
public $MethodArguments;
public $ReturnValue;
public $ReturnException;
public $ExpectedCalls;
public $ActualCalls;
public $ExpectArguments;
public $ExpectTimes;
public $Type;
public $Text;
public function __construct($language)
{
$this->ExpectedCalls = -1;
$this->ActualCalls = 0;
$this->ExpectArguments = false;
$this->ExpectTimes = false;
$this->ReturnException = false;
$this->ReturnValue = null;
$textFactory = new TextFactory();
$this->Text = $textFactory->getLanguageText($language);
}
public function method($methodName)
{
$this->Type = 'method';
$this->MethodName = $methodName;
return $this;
}
public function getProperty($propertyName)
{
$this->Type = 'getProperty';
$this->MethodName = $propertyName;
return $this;
}
public function setProperty($propertyName)
{
$this->Type = 'setProperty';
$this->MethodName = $propertyName;
return $this;
}
public function with()
{
$this->ExpectArguments = true;
$this->MethodArguments = func_get_args();
return $this;
}
public function returns($returnValue)
{
if ($this->ReturnValue !== null) {
throw new \Exception($this->Text->ReturnsOrThrowsNotBoth);
}
$this->ReturnValue = $returnValue;
return $this;
}
public function throws($errorMessage)
{
if ($this->ReturnValue !== null) {
throw new \Exception($this->Text->ReturnsOrThrowsNotBoth);
}
$this->ReturnValue = $errorMessage;
$this->ReturnException = true;