summaryrefslogtreecommitdiff
path: root/test_tools/simpletest/mock_objects.php
blob: d39eb84e2a55f8f7131347afaee3d0bc3f67706a (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
<?php
    /**
     *	base include file for SimpleTest
     *	@package	SimpleTest
     *	@subpackage	MockObjects
     *	@version	$Id: mock_objects.php,v 1.61 2005/02/13 01:09:25 lastcraft Exp $
     */

    /**#@+
     * include SimpleTest files
     */
    require_once(dirname(__FILE__) . '/expectation.php');
    require_once(dirname(__FILE__) . '/options.php');
    require_once(dirname(__FILE__) . '/dumper.php');
    /**#@-*/
    
    /**
     * Default character simpletest will substitute for any value
     */
    define('MOCK_WILDCARD', '*');
    
    /**
     *    A wildcard expectation always matches.
	 *    @package SimpleTest
	 *    @subpackage MockObjects
     */
    class WildcardExpectation extends SimpleExpectation {
        
        /**
         *    Chains constructor only.
         *    @access public
         */
        function WildcardExpectation() {
            $this->SimpleExpectation();
        }
        
        /**
         *    Tests the expectation. Always true.
         *    @param mixed $compare  Ignored.
         *    @return boolean        True.
         *    @access public
         */
        function test($compare) {
            return true;
        }
        
        /**
         *    Returns a human readable test message.
         *    @param mixed $compare      Comparison value.
         *    @return string             Description of success
         *                               or failure.
         *    @access public
         */
        function testMessage($compare) {
            $dumper = $this->_getDumper();
            return 'Wildcard always matches [' . $dumper->describeValue($compare) . ']';
        }
    }
    
    /**
     *    Parameter comparison assertion.
	 *    @package SimpleTest
	 *    @subpackage MockObjects
     */
    class ParametersExpectation extends SimpleExpectation {
        protected $_expected;
        
        /**
         *    Sets the expected parameter list.
         *    @param array $parameters  Array of parameters including
         *                              those that are wildcarded.
         *                              If the value is not an array
         *                              then it is considered to match any.
         *    @param mixed $wildcard    Any parameter matching this
         *                              will always match.
         *    @param string $message    Customised message on failure.
         *    @access public
         */
        function ParametersExpectation($expected = false, $message = '%s') {
            $this->SimpleExpectation($message);
            $this->_expected = $expected;
        }
        
        /**
         *    Tests the assertion. True if correct.
         *    @param array $parameters     Comparison values.
         *    @return boolean              True if correct.
         *    @access public
         */
        function test($parameters) {
            if (! is_array($this->_expected)) {
                return true;
            }
            if (count($this->_expected) != count($parameters)) {
                return false;
            }
            for ($i = 0; $i < count($this->_expected); $i++) {
                if (! $this->_testParameter($parameters[$i], $this->_expected[$i])) {
                    return false;
                }
            }
            return true;
        }
        
        /**
         *    Tests an individual parameter.
         *    @param mixed $parameter    Value to test.
         *    @param mixed $expected     Comparison value.
         *    @return boolean            True if expectation
         *                               fulfilled.
         *    @access private
         */
        function _testParameter($parameter, $expected) {
            $comparison = $this->_coerceToExpectation($expected);
            return $comparison->test($parameter);
        }
        
        /**
         *    Returns a human readable test message.
         *    @param array $comparison   Incoming parameter list.
         *    @return string             Description of success
         *                               or failure.
         *    @access public
         */
        function testMessage($parameters) {
            if ($this->test($parameters)) {
                return "Expectation of " . count($this->_expected) .
                        " arguments of [" . $this->_renderArguments($this->_expected) .
                        "] is correct";
            } else {
                return $this->_describeDifference($this->_expected, $parameters);
            }
        }
        
        /**
         *    Message to display if expectation differs from
         *    the parameters actually received.
         *    @param array $expected      Expected parameters as list.
         *    @param array $parameters    Actual parameters received.
         *    @return string              Description of difference.
         *    @access private
         */
        function _describeDifference($expected, $parameters) {
            if (count($expected) != count($parameters)) {
                return "Expected " . count($expected) .
                        " arguments of [" . $this->_renderArguments($expected) .
                        "] but got " . count($parameters) .
                        " arguments of [" . $this->_renderArguments($parameters) . "]";
            }
            $messages = array();
            for ($i = 0; $i < count($expected); $i++) {
                $comparison = $this->_coerceToExpectation($expected[$i]);
                if (! $comparison->test($parameters[$i])) {
                    $messages[] = "parameter " . ($i + 1) . " with [" .
                            $comparison->overlayMessage($parameters[$i]) . "]";
                }
            }
            return "Parameter expectation differs at " . implode(" and ", $messages);
        }
        
        /**
         *    Creates an identical expectation if the
         *    object/value is not already some type
         *    of expectation.
         *    @param mixed $expected      Expected value.
         *    @return SimpleExpectation   Expectation object.
         *    @access private
         */
        function _coerceToExpectation($expected) {
            if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) {
                return $expected;
            }
            return new IdenticalExpectation($expected);
        }
        
        /**
         *    Renders the argument list as a string for
         *    messages.
         *    @param array $args    Incoming arguments.
         *    @return string        Simple description of type and value.
         *    @access private
         */
        function _renderArguments($args) {
            $descriptions = array();
            if (is_array($args)) {
                foreach ($args as $arg) {
                    $dumper = new SimpleDumper();
                    $descriptions[] = $dumper->describeValue($arg);
                }
            }
            return implode(', ', $descriptions);
        }
    }
    
    /**
     *    Confirms that the number of calls on a method is as expected.
     */
    class CallCountExpectation extends SimpleExpectation {
        protected $_method;
        protected $_count;
        
        /**
         *    Stashes the method and expected count for later
         *    reporting.
         *    @param string $method    Name of method to confirm against.
         *    @param integer $count    Expected number of calls.
         *    @param string $message   Custom error message.
         */
        function CallCountExpectation($method, $count, $message = '%s') {
            $this->_method = $method;
            $this->_count = $count;
            $this->SimpleExpectation($message);
        }
        
        /**
         *    Tests the assertion. True if correct.
         *    @param integer $compare     Measured call count.
         *    @return boolean             True if expected.
         *    @access public
         */
        function test($compare) {
            return ($this->_count == $compare);
        }
        
        /**
         *    Reports the comparison.
         *    @param integer $compare     Measured call count.
         *    @return string              Message to show.
         *    @access public
         */
        function testMessage($compare) {
            return 'Expected call count for [' . $this->_method .
                    '] was [' . $this->_count .
                    '] got [' . $compare . ']';
        }
    }
      
    /**
     *    Confirms that the number of calls on a method is as expected.
     */
    class MinimumCallCountExpectation extends SimpleExpectation {
        protected $_method;
        protected $_count;
        
        /**
         *    Stashes the method and expected count for later
         *    reporting.
         *    @param string $method    Name of method to confirm against.
         *    @param integer $count    Minimum number of calls.
         *    @param string $message   Custom error message.
         */
        function MinimumCallCountExpectation($method, $count, $message = '%s') {
            $this->_method = $method;
            $this->_count = $count;
            $this->SimpleExpectation($message);
        }
        
        /**
         *    Tests the assertion. True if correct.
         *    @param integer $compare     Measured call count.
         *    @return boolean             True if enough.
         *    @access public
         */
        function test($compare) {
            return ($this->_count <= $compare);
        }
        
        /**
         *    Reports the comparison.
         *    @param integer $compare     Measured call count.
         *    @return string              Message to show.
         *    @access public
         */
        function testMessage($compare) {
            return 'Minimum call count for [' . $this->_method .
                    '] was [' . $this->_count .
                    '] got [' . $compare . ']';
        }
    }
        
    /**
     *    Confirms that the number of calls on a method is as expected.
     */
    class MaximumCallCountExpectation extends SimpleExpectation {
        protected $_method;
        protected $_count;
        
        /**
         *    Stashes the method and expected count for later
         *    reporting.
         *    @param string $method    Name of method to confirm against.
         *    @param integer $count    Minimum number of calls.
         *    @param string $message   Custom error message.
         */
        function MaximumCallCountExpectation($method, $count, $message = '%s') {
            $this->_method = $method;
            $this->_count = $count;
            $this->SimpleExpectation($message);
        }
        
        /**
         *    Tests the assertion. True if correct.
         *    @param integer $compare     Measured call count.
         *    @return boolean             True if not over.
         *    @access public
         */
        function test($compare) {
            return ($this->_count >= $compare);
        }
        
        /**
         *    Reports the comparison.
         *    @param integer $compare     Measured call count.
         *    @return string              Message to show.
         *    @access public
         */
        function testMessage($compare) {
            return 'Maximum call count for [' . $this->_method .
                    '] was [' . $this->_count .
                    '] got [' . $compare . ']';
        }
    }

    /**
     *    Retrieves values and references by searching the
     *    parameter lists until a match is found.
	 *    @package SimpleTest
	 *    @subpackage MockObjects
     */
    class CallMap {
        protected $_map;
        
        /**
         *    Creates an empty call map.
         *    @access public
         */
        function CallMap() {
            $this->_map = array();
        }
        
        /**
         *    Stashes a value against a method call.
         *    @param array $parameters    Arguments including wildcards.
         *    @param mixed $value         Value copied into the map.
         *    @access public
         */
        function addValue($parameters, $value) {
            $this->addReference($parameters, $value);
        }
        
        /**
         *    Stashes a reference against a method call.
         *    @param array $parameters    Array of arguments (including wildcards).
         *    @param mixed $reference     Array reference placed in the map.
         *    @access public
         */
        function addReference($parameters, $reference) {
            $place = count($this->_map);
            $this->_map[$place] = array();
            $this->_map[$place]["params"] = new ParametersExpectation($parameters);
            $this->_map[$place]["content"] = $reference;
        }
        
        /**
         *    Searches the call list for a matching parameter
         *    set. Returned by reference.
         *    @param array $parameters    Parameters to search by
         *                                without wildcards.
         *    @return object              Object held in the first matching
         *                                slot, otherwise null.
         *    @access public
         */
        function findFirstMatch($parameters) {
            $slot = $this->_findFirstSlot($parameters);
            if (!isset($slot)) {
                return null;
            }
            return $slot["content"];
        }
        
        /**
         *    Searches the call list for a matching parameter
         *    set. True if successful.
         *    @param array $parameters    Parameters to search by
         *                                without wildcards.
         *    @return boolean             True if a match is present.
         *    @access public
         */
        function isMatch($parameters) {
            return ($this->_findFirstSlot($parameters) != null);
        }
        
        /**
         *    Searches the map for a matching item.
         *    @param array $parameters    Parameters to search by
         *                                without wildcards.
         *    @return array               Reference to slot or null.
         *    @access private
         */
        function _findFirstSlot($parameters) {
            $count = count($this->_map);
            for ($i = 0; $i < $count; $i++) {
                if ($this->_map[$i]["params"]->test($parameters)) {
                    return $this->_map[$i];
                }
            }
            return null;
        }
    }
    
    /**
     *    An empty collection of methods that can have their
     *    return values set. Used for prototyping.
	 *    @package SimpleTest
	 *    @subpackage MockObjects
     */
    class SimpleStub {
        protected $_wildcard;
        protected $_is_strict;
        protected $_returns;
        protected $_return_sequence;
        protected $_call_counts;
        
        /**
         *    Sets up the wildcard and everything else empty.
         *    @param mixed $wildcard      Parameter matching wildcard.
         *    @param boolean $is_strict   Enables method name checks.
         *    @access public
         */
        function SimpleStub($wildcard, $is_strict = true) {
            $this->_wildcard = $wildcard;
            $this->_is_strict = $is_strict;
            $this->_returns = array();
            $this->_return_sequence = array();
            $this->_call_counts = array();
        }
        
        /**
         *    Replaces wildcard matches with wildcard
         *    expectations in the argument list.
         *    @param array $args      Raw argument list.
         *    @return array           Argument list with
         *                            expectations.
         *    @access private
         */
        function _replaceWildcards($args) {
            if ($args === false) {
                return false;
            }
            for ($i = 0; $i < count($args); $i++) {
                if ($args[$i] === $this->_wildcard) {
                    $args[$i] = new WildcardExpectation();
                }
            }
            return $args;
        }
        
        /**
         *    Returns the expected value for the method name.
         *    @param string $method       Name of method to simulate.
         *    @param array $args          Arguments as an array.
         *    @return mixed               Stored return.
         *    @access private
         */
        function _invoke($method, $args) {
            $method = strtolower($method);
            $step = $this->getCallCount($method);
            $this->_addCall($method, $args);
            return $this->_getReturn($method, $args, $step);
        }
        
        /**
         *    Triggers a PHP error if the method is not part
         *    of this object.
         *    @param string $method        Name of method.
         *    @param string $task          Description of task attempt.
         *    @access protected
         */
        function _dieOnNoMethod($method, $task) {
            if ($this->_is_strict && !method_exists($this, $method)) {
                trigger_error(
                        "Cannot $task as no ${method}() in class " . get_class($this),
                        E_USER_ERROR);
            }
        }
        
        /**
         *    Adds one to the call count of a method.
         *    @param string $method        Method called.
         *    @param array $args           Arguments as an array.
         *    @access protected
         */
        function _addCall($method, $args) {
            if (!isset($this->_call_counts[$method])) {
                $this->_call_counts[$method] = 0;
            }
            $this->_call_counts[$method]++;
        }
        
        /**
         *    Fetches the call count of a method so far.
         *    @param string $method        Method name called.
         *    @return                      Number of calls so far.
         *    @access public
         */
        function getCallCount($method) {
            $this->_dieOnNoMethod($method, "get call count");
            $method = strtolower($method);
            if (! isset($this->_call_counts[$method])) {
                return 0;
            }
            return $this->_call_counts[$method];
        }
        
        /**
         *    Sets a return for a parameter list that will
         *    be passed by value for all calls to this method.
         *    @param string $method       Method name.
         *    @param mixed $value         Result of call passed by value.
         *    @param array $args          List of parameters to match
         *                                including wildcards.
         *    @access public
         */
        function setReturnValue($method, $value, $args = false) {
            $this->_dieOnNoMethod($method, "set return value");
            $args = $this->_replaceWildcards($args);
            $method = strtolower($method);
            if (! isset($this->_returns[$method])) {
                $this->_returns[$method] = new CallMap();
            }
            $this->_returns[$method]->addValue($args, $value);
        }
                
        /**
         *    Sets a return for a parameter list that will
         *    be passed by value only when the required call count
         *    is reached.
         *    @param integer $timing   Number of calls in the future
         *                             to which the result applies. If
         *                             not set then all calls will return
         *                             the value.
         *    @param string $method    Method name.
         *    @param mixed $value      Result of call passed by value.
         *    @param array $args       List of parameters to match
         *                             including wildcards.
         *    @access public
         */
        function setReturnValueAt($timing, $method, $value, $args = false) {
            $this->_dieOnNoMethod($method, "set return value sequence");
            $args = $this->_replaceWildcards($args);
            $method = strtolower($method);
            if (! isset($this->_return_sequence[$method])) {
                $this->_return_sequence[$method] = array();
            }
            if (! isset($this->_return_sequence[$method][$timing])) {
                $this->_return_sequence[$method][$timing] = new CallMap();
            }
            $this->_return_sequence[$method][$timing]->addValue($args, $value);
        }
         
        /**
         *    Sets a return for a parameter list that will
         *    be passed by reference for all calls.
         *    @param string $method       Method name.
         *    @param mixed $reference     Result of the call will be this object.
         *    @param array $args          List of parameters to match
         *                                including wildcards.
         *    @access public
         */
        function setReturnReference($method, $reference, $args = false) {
            $this->_dieOnNoMethod($method, "set return reference");
            $args = $this->_replaceWildcards($args);
            $method = strtolower($method);
            if (! isset($this->_returns[$method])) {
                $this->_returns[$method] = new CallMap();
            }
            $this->_returns[$method]->addReference($args, $reference);
        }
        
        /**
         *    Sets a return for a parameter list that will
         *    be passed by value only when the required call count
         *    is reached.
         *    @param integer $timing    Number of calls in the future
         *                              to which the result applies. If
         *                              not set then all calls will return
         *                              the value.
         *    @param string $method     Method name.
         *    @param mixed $reference   Result of the call will be this object.
         *    @param array $args        List of parameters to match
         *                              including wildcards.
         *    @access public
         */
        function setReturnReferenceAt($timing, $method, $reference, $args = false) {
            $this->_dieOnNoMethod($method, "set return reference sequence");
            $args = $this->_replaceWildcards($args);
            $method = strtolower($method);
            if (! isset($this->_return_sequence[$method])) {
                $this->_return_sequence[$method] = array();
            }
            if (! isset($this->_return_sequence[$method][$timing])) {
                $this->_return_sequence[$method][$timing] = new CallMap();
            }
            $this->_return_sequence[$method][$timing]->addReference($args, $reference);
        }
        
        /**
         *    Finds the return value matching the incoming
         *    arguments. If there is no matching value found
         *    then an error is triggered.
         *    @param string $method      Method name.
         *    @param array $args         Calling arguments.
         *    @param integer $step       Current position in the
         *                               call history.
         *    @return mixed              Stored return.
         *    @access protected
         */
        function _getReturn($method, $args, $step) {
            if (isset($this->_return_sequence[$method][$step])) {
                if ($this->_return_sequence[$method][$step]->isMatch($args)) {
                    return $this->_return_sequence[$method][$step]->findFirstMatch($args);
                }
            }
            if (isset($this->_returns[$method])) {
                return $this->_returns[$method]->findFirstMatch($args);
            }
            return null;
        }
    }
    
    /**
     *    An empty collection of methods that can have their
     *    return values set and expectations made of the
     *    calls upon them. The mock will assert the
     *    expectations against it's attached test case in
     *    addition to the server stub behaviour.
	 *    @package SimpleTest
	 *    @subpackage MockObjects
     */
    class SimpleMock extends SimpleStub {
        protected $_test;
        protected $_expected_counts;
        protected $_max_counts;
        protected $_expected_args;
        protected $_expected_args_at;
        
        /**
         *    Creates an empty return list and expectation list.
         *    All call counts are set to zero.
         *    @param SimpleTestCase $test    Test case to test expectations in.
         *    @param mixed $wildcard         Parameter matching wildcard.
         *    @param boolean $is_strict      Enables method name checks on
         *                                   expectations.
         *    @access public
         */
        function SimpleMock($test, $wildcard, $is_strict = true) {
            $this->SimpleStub($wildcard, $is_strict);
            if (! $test) {
                trigger_error('No unit tester for mock object', E_USER_ERROR);
                return;
            }
            $this->_test = SimpleMock::registerTest($test);
            $this->_expected_counts = array();
            $this->_max_counts = array();
            $this->_expected_args = array();
            $this->_expected_args_at = array();
        }
        
        /**
         *    Accessor for attached unit test so that when
         *    subclassed, new expectations can be added easily.
         *    @return SimpleTestCase      Unit test passed in constructor.
         *    @access public
         */
        function getTest() {
            return $this->_test;
        }
        
        /**
         *    Die if bad arguments array is passed
         *    @param mixed $args     The arguments value to be checked.
         *    @param string $task    Description of task attempt.
         *    @return boolean        Valid arguments
         *    @access private
         */
        function _checkArgumentsIsArray($args, $task) {
        	if (! is_array($args)) {
        		trigger_error(
        			"Cannot $task as \$args parameter is not an array",
        			E_USER_ERROR);
        	}
        }
        
        /**
         *    Sets up an expected call with a set of
         *    expected parameters in that call. All
         *    calls will be compared to these expectations
         *    regardless of when the call is made.
         *    @param string $method        Method call to test.
         *    @param array $args           Expected parameters for the call
         *                                 including wildcards.
         *    @param string $message       Overridden message.
         *    @access public
         */
        function expectArguments($method, $args, $message = '%s') {
            $this->_dieOnNoMethod($method, 'set expected arguments');
            $this->_checkArgumentsIsArray($args, 'set expected arguments');
            $args = $this->_replaceWildcards($args);
            $message .= Mock::getExpectationLine(' at line [%d]');
            $this->_expected_args[strtolower($method)] =
                    new ParametersExpectation($args, $message);
        }
        
        /**
         *    Sets up an expected call with a set of
         *    expected parameters in that call. The
         *    expected call count will be adjusted if it
         *    is set too low to reach this call.
         *    @param integer $timing    Number of calls in the future at
         *                              which to test. Next call is 0.
         *    @param string $method     Method call to test.
         *    @param array $args        Expected parameters for the call
         *                              including wildcards.
         *    @param string $message    Overridden message.
         *    @access public
         */
        function expectArgumentsAt($timing, $method, $args, $message = '%s') {
            $this->_dieOnNoMethod($method, 'set expected arguments at time');
            $this->_checkArgumentsIsArray($args, 'set expected arguments at time');
            $args = $this->_replaceWildcards($args);
            if (! isset($this->_expected_args_at[$timing])) {
                $this->_expected_args_at[$timing] = array();
            }
            $method = strtolower($method);
            $message .= Mock::getExpectationLine(' at line [%d]');
            $this->_expected_args_at[$timing][$method] =
                    new ParametersExpectation($args, $message);
        }
        
        /**
         *    Sets an expectation for the number of times
         *    a method will be called. The tally method
         *    is used to check this.
         *    @param string $method        Method call to test.
         *    @param integer $count        Number of times it should
         *                                 have been called at tally.
         *    @param string $message       Overridden message.
         *    @access public
         */
        function expectCallCount($method, $count, $message = '%s') {
            $this->_dieOnNoMethod($method, 'set expected call count');
            $message .= Mock::getExpectationLine(' at line [%d]');
            $this->_expected_counts[strtolower($method)] =
                    new CallCountExpectation($method, $count, $message);
        }
        
        /**
         *    Sets the number of times a method may be called
         *    before a test failure is triggered.
         *    @param string $method        Method call to test.
         *    @param integer $count        Most number of times it should
         *                                 have been called.
         *    @param string $message       Overridden message.
         *    @access public
         */
        function expectMaximumCallCount($method, $count, $message = '%s') {
            $this->_dieOnNoMethod($method, 'set maximum call count');
            $message .= Mock::getExpectationLine(' at line [%d]');
            $this->_max_counts[strtolower($method)] = 
                    new MaximumCallCountExpectation($method, $count, $message);
        }
        
        /**
         *    Sets the number of times to call a method to prevent
         *    a failure on the tally.
         *    @param string $method      Method call to test.
         *    @param integer $count      Least number of times it should
         *                               have been called.
         *    @param string $message     Overridden message.
         *    @access public
         */
        function expectMinimumCallCount($method, $count, $message = '%s') {
            $this->_dieOnNoMethod($method, 'set minimum call count');
            $message .= Mock::getExpectationLine(' at line [%d]');
            $this->_expected_counts[strtolower($method)] =
                    new MinimumCallCountExpectation($method, $count, $message);
        }
        
        /**
         *    Convenience method for barring a method
         *    call.
         *    @param string $method        Method call to ban.
         *    @param string $message       Overridden message.
         *    @access public
         */
        function expectNever($method, $message = '%s') {
            $this->expectMaximumCallCount($method, 0, $message);
        }
        
        /**
         *    Convenience method for a single method
         *    call.
         *    @param string $method     Method call to track.
         *    @param array $args        Expected argument list or
         *                              false for any arguments.
         *    @param string $message    Overridden message.
         *    @access public
         */
        function expectOnce($method, $args = false, $message = '%s') {
            $this->expectCallCount($method, 1, $message);
            if ($args !== false) {
                $this->expectArguments($method, $args, $message);
            }
        }
        
        /**
         *    Convenience method for requiring a method
         *    call.
         *    @param string $method       Method call to track.
         *    @param array $args          Expected argument list or
         *                                false for any arguments.
         *    @param string $message      Overridden message.
         *    @access public
         */
        function expectAtLeastOnce($method, $args = false, $message = '%s') {
            $this->expectMinimumCallCount($method, 1, $message);
            if ($args !== false) {
                $this->expectArguments($method, $args, $message);
            }
        }
        
        /**
         *    Totals up the call counts and triggers a test
         *    assertion if a test is present for expected
         *    call counts.
         *    This method must be called explicitly for the call
         *    count assertions to be triggered.
         *    @access public
         */
        function tally() {
            foreach ($this->_expected_counts as $method => $expectation) {
                $this->_assertTrue(
                        $expectation->test($this->getCallCount($method)),
                        $expectation->overlayMessage($this->getCallCount($method)));
            }
            foreach ($this->_max_counts as $method => $expectation) {
                if ($expectation->test($this->getCallCount($method))) {
                    $this->_assertTrue(
                            true,
                            $expectation->overlayMessage($this->getCallCount($method)));
                }
            }
        }

        /**
         *    Returns the expected value for the method name
         *    and checks expectations. Will generate any
         *    test assertions as a result of expectations
         *    if there is a test present.
         *    @param string $method       Name of method to simulate.
         *    @param array $args          Arguments as an array.
         *    @return mixed               Stored return.
         *    @access private
         */
        function _invoke($method, $args) {
            $method = strtolower($method);
            $step = $this->getCallCount($method);
            $this->_addCall($method, $args);
            $this->_checkExpectations($method, $args, $step);
            return $this->_getReturn($method, $args, $step);
        }
        
        /**
         *    Tests the arguments against expectations.
         *    @param string $method        Method to check.
         *    @param array $args           Argument list to match.
         *    @param integer $timing       The position of this call
         *                                 in the call history.
         *    @access private
         */
        function _checkExpectations($method, $args, $timing) {
            if (isset($this->_max_counts[$method])) {
                if (! $this->_max_counts[$method]->test($timing + 1)) {
                    $this->_assertTrue(
                            false,
                            $this->_max_counts[$method]->overlayMessage($timing + 1));
                }
            }
            if (isset($this->_expected_args_at[$timing][$method])) {
                $this->_assertTrue(
                        $this->_expected_args_at[$timing][$method]->test($args),
                        "Mock method [$method] at [$timing] -> " .
                                $this->_expected_args_at[$timing][$method]->overlayMessage($args));
            } elseif (isset($this->_expected_args[$method])) {
                $this->_assertTrue(
                        $this->_expected_args[$method]->test($args),
                        "Mock method [$method] -> " . $this->_expected_args[$method]->overlayMessage($args));
            }
        }
        
        /**
         *    Triggers an assertion on the held test case.
         *    Should be overridden when using another test
         *    framework other than the SimpleTest one if the
         *    assertion method has a different name.
         *    @param boolean $assertion     True will pass.
         *    @param string $message        Message that will go with
         *                                  the test event.
         *    @access protected
         */
        function _assertTrue($assertion, $message) {
            $test =SimpleMock::injectTest($this->_test);
            $test->assertTrue($assertion, $message);
        }
        
        /**
         *    Stashes the test case for later recovery.
         *    @param SimpleTestCase $test    Test case.
         *    @return string                 Key to find it again.
         *    @access public
         *    @static
         */
        function registerTest($test) {
            $registry =SimpleMock::_getRegistry();
            $registry[$class = get_class($test)] = $test;
            return $class;
        }
        
        /**
         *    Resolves the dependency on the test case.
         *    @param string $class      Key to look up test case in.
         *    @return SimpleTestCase    Test case to send results to.
         *    @access public
         *    @static
         */
        function injectTest($key) {
            $registry =SimpleMock::_getRegistry();
            return $registry[$key];
        }
        
        /**
         *    Registry for test cases. The reason for this is
         *    to break the reference between the test cases and
         *    the mocks. It was leading to a fatal error due to
         *    recursive dependencies during comparisons. See
         *    http://bugs.php.net/bug.php?id=31449 for the PHP
         *    bug.
         *    @return array        List of references.
         *    @access private
         *    @static
         */
        function _getRegistry() {
            static $registry;
            if (! isset($registry)) {
                $registry = array();
            }
            return $registry;
        }
    }
    
    /**
     *    Static methods only service class for code generation of
     *    server stubs.
	 *    @package SimpleTest
	 *    @subpackage MockObjects
     */
    class Stub {
        
        /**
         *    Factory for server stub classes.
         */
        function Stub() {
            trigger_error('Stub factory methods are class only.');
        }
        
        /**
         *    Clones a class' interface and creates a stub version
         *    that can have return values set.
         *    @param string $class        Class to clone.
         *    @param string $stub_class   New class name. Default is
         *                                the old name with "Stub"
         *                                prepended.
         *    @param array $methods       Additional methods to add beyond
         *                                those in the cloned class. Use this
         *                                to emulate the dynamic addition of
         *                                methods in the cloned class or when
         *                                the class hasn't been written yet.
         *    @static
         *    @access public
         */
        function generate($class, $stub_class = false, $methods = false) {
            if (! SimpleTestCompatibility::classExists($class)) {
                return false;
            }
            if (! $stub_class) {
                $stub_class = "Stub" . $class;
            }
            if (SimpleTestCompatibility::classExists($stub_class)) {
                return false;
            }
            return eval(Stub::_createClassCode(
                    $class,
                    $stub_class,
                    $methods ? $methods : array()) . " return true;");
        }
        
        /**
         *    The new server stub class code in string form.
         *    @param string $class           Class to clone.
         *    @param string $mock_class      New class name.
         *    @param array $methods          Additional methods.
         *    @static
         *    @access private
         */
        function _createClassCode($class, $stub_class, $methods) {
            $stub_base = SimpleTestOptions::getStubBaseClass();
            $code = "class $stub_class extends $stub_base {\n";
            $code .= "    function $stub_class(\$wildcard = MOCK_WILDCARD) {\n";
            $code .= "        \$this->$stub_base(\$wildcard);\n";
            $code .= "    }\n";
            $code .= Stub::_createHandlerCode($class, $stub_base, $methods);
            $code .= "}\n";
            return $code;
        }
        
        /**
         *    Creates code within a class to generate replaced
         *    methods. All methods call the _invoke() handler
         *    with the method name and the arguments in an
         *    array.
         *    @param string $class     Class to clone.
         *    @param string $base      Base mock/stub class with methods that
         *                             cannot be cloned. Otherwise you
         *                             would be stubbing the accessors used
         *                             to set the stubs.
         *    @param array $methods    Additional methods.
         *    @static
         *    @access private
         */
        function _createHandlerCode($class, $base, $methods) {
            $code = "";
            $methods = array_merge($methods, get_class_methods($class));
            foreach ($methods as $method) {
                if (Stub::_isSpecialMethod($method)) {
                    continue;
                }
                if (in_array($method, get_class_methods($base))) {
                    continue;
                }
                $code .= "    function $method() {\n";
                $code .= "        \$args = func_get_args();\n";
                $code .= "        return \$this->_invoke(\"$method\", \$args);\n";
                $code .= "    }\n";
            }
            return $code;
        }
        
        /**
         *    Tests to see if a special PHP method is about to
         *    be stubbed by mistake.
         *    @param string $method    Method name.
         *    @return boolean          True if special.
         *    @access private
         *    @static
         */
        function _isSpecialMethod($method) {
            return in_array(
                    strtolower($method),
                    array('__construct', '__clone', '__get', '__set', '__call'));
        }
    }
    
    /**
     *    Static methods only service class for code generation of
     *    mock objects.
	 *    @package SimpleTest
	 *    @subpackage MockObjects
     */
    class Mock {
        
        /**
         *    Factory for mock object classes.
         *    @access public
         */
        function Mock() {
            trigger_error("Mock factory methods are class only.");
        }
        
        /**
         *    Clones a class' interface and creates a mock version
         *    that can have return values and expectations set.
         *    @param string $class         Class to clone.
         *    @param string $mock_class    New class name. Default is
         *                                 the old name with "Mock"
         *                                 prepended.
         *    @param array $methods        Additional methods to add beyond
         *                                 those in th cloned class. Use this
         *                                 to emulate the dynamic addition of
         *                                 methods in the cloned class or when
         *                                 the class hasn't been written yet.
         *    @static
         *    @access public
         */
        function generate($class, $mock_class = false, $methods = false) {
            if (! SimpleTestCompatibility::classExists($class)) {
                return false;
            }
            if (! $mock_class) {
                $mock_class = "Mock" . $class;
            }
            if (SimpleTestCompatibility::classExists($mock_class)) {
                return false;
            }
            return eval(Mock::_createClassCode(
                    $class,
                    $mock_class,
                    $methods ? $methods : array()) . " return true;");
        }
        
        /**
         *    Generates a version of a class with selected
         *    methods mocked only. Inherits the old class
         *    and chains the mock methods of an aggregated
         *    mock object.
         *    @param string $class            Class to clone.
         *    @param string $mock_class       New class name.
         *    @param array $methods           Methods to be overridden
         *                                    with mock versions.
         *    @static
         *    @access public
         */
        function generatePartial($class, $mock_class, $methods) {
            if (! SimpleTestCompatibility::classExists($class)) {
                return false;
            }
            if (SimpleTestCompatibility::classExists($mock_class)) {
                trigger_error("Partial mock class [$mock_class] already exists");
                return false;
            }
            return eval(Mock::_extendClassCode($class, $mock_class, $methods));
        }

        /**
         *    The new mock class code as a string.
         *    @param string $class           Class to clone.
         *    @param string $mock_class      New class name.
         *    @param array $methods          Additional methods.
         *    @return string                 Code for new mock class.
         *    @static
         *    @access private
         */
        function _createClassCode($class, $mock_class, $methods) {
            $mock_base = SimpleTestOptions::getMockBaseClass();
            $code = "class $mock_class extends $mock_base {\n";
            $code .= "    function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
            $code .= "        \$this->$mock_base(\$test, \$wildcard);\n";
            $code .= "    }\n";
            $code .= Stub::_createHandlerCode($class, $mock_base, $methods);
            $code .= "}\n";
            return $code;
        }

        /**
         *    The extension class code as a string. The class
         *    composites a mock object and chains mocked methods
         *    to it.
         *    @param string $class         Class to extend.
         *    @param string $mock_class    New class name.
         *    @param array  $methods       Mocked methods.
         *    @return string               Code for a new class.
         *    @static
         *    @access private
         */
        function _extendClassCode($class, $mock_class, $methods) {
            $mock_base = SimpleTestOptions::getMockBaseClass();
            $code  = "class $mock_class extends $class {\n";
            $code .= "    var \$_mock;\n";
            $code .= Mock::_addMethodList($methods);
            $code .= "\n";
            $code .= "    function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
            $code .= "        \$this->_mock = new $mock_base(\$test, \$wildcard, false);\n";
            $code .= "    }\n";
            $code .= Mock::_chainMockReturns();
            $code .= Mock::_chainMockExpectations();
            $code .= Mock::_overrideMethods($methods);
            $code .= SimpleTestOptions::getPartialMockCode();
            $code .= "}\n";
            return $code;
        }
        
        /**
         *    Creates a list of mocked methods for error checking.
         *    @param array $methods       Mocked methods.
         *    @return string              Code for a method list.
         *    @access private
         */
        function _addMethodList($methods) {
            return "    var \$_mocked_methods = array('" . implode("', '", $methods) . "');\n";
        }
        
        /**
         *    Creates code to abandon the expectation if not mocked.
         *    @param string $alias       Parameter name of method name.
         *    @return string             Code for bail out.
         *    @access private
         */
        function _bailOutIfNotMocked($alias) {
            $code  = "        if (! in_array($alias, \$this->_mocked_methods)) {\n";
            $code .= "            trigger_error(\"Method [$alias] is not mocked\");\n";
            $code .= "            return;\n";
            $code .= "        }\n";
            return $code;
        }
        
        /**
         *    Creates source code for chaining to the composited
         *    mock object.
         *    @return string           Code for mock set up.
         *    @access private
         */
        function _chainMockReturns() {
            $code  = "    function setReturnValue(\$method, \$value, \$args = false) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->setReturnValue(\$method, \$value, \$args);\n";
            $code .= "    }\n";
            $code .= "    function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n";
            $code .= "    }\n";
            $code .= "    function setReturnReference(\$method, &\$ref, \$args = false) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->setReturnReference(\$method, \$ref, \$args);\n";
            $code .= "    }\n";
            $code .= "    function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n";
            $code .= "    }\n";
            return $code;
        }
        
        /**
         *    Creates source code for chaining to an aggregated
         *    mock object.
         *    @return string                 Code for expectations.
         *    @access private
         */
        function _chainMockExpectations() {
            $code = "    function expectArguments(\$method, \$args = false) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->expectArguments(\$method, \$args);\n";
            $code .= "    }\n";
            $code .= "    function expectArgumentsAt(\$timing, \$method, \$args = false) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args);\n";
            $code .= "    }\n";
            $code .= "    function expectCallCount(\$method, \$count) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->expectCallCount(\$method, \$count);\n";
            $code .= "    }\n";
            $code .= "    function expectMaximumCallCount(\$method, \$count) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->expectMaximumCallCount(\$method, \$count);\n";
            $code .= "    }\n";
            $code .= "    function expectMinimumCallCount(\$method, \$count) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->expectMinimumCallCount(\$method, \$count);\n";
            $code .= "    }\n";
            $code .= "    function expectNever(\$method) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->expectNever(\$method);\n";
            $code .= "    }\n";
            $code .= "    function expectOnce(\$method, \$args = false) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->expectOnce(\$method, \$args);\n";
            $code .= "    }\n";
            $code .= "    function expectAtLeastOnce(\$method, \$args = false) {\n";
            $code .= Mock::_bailOutIfNotMocked("\$method");
            $code .= "        \$this->_mock->expectAtLeastOnce(\$method, \$args);\n";
            $code .= "    }\n";
            $code .= "    function tally() {\n";
            $code .= "        \$this->_mock->tally();\n";
            $code .= "    }\n";
            return $code;
        }
        
        /**
         *    Creates source code to override a list of methods
         *    with mock versions.
         *    @param array $methods    Methods to be overridden
         *                             with mock versions.
         *    @return string           Code for overridden chains.
         *    @access private
         */
        function _overrideMethods($methods) {
            $code = "";
            foreach ($methods as $method) {
                $code .= "    function $method() {\n";
                $code .= "        \$args = func_get_args();\n";
                $code .= "        return \$this->_mock->_invoke(\"$method\", \$args);\n";
                $code .= "    }\n";
            }
            return $code;
        }
        
        /**
         *    Uses a stack trace to find the line of an assertion.
         *    @param string $format    String formatting.
         *    @param array $stack      Stack frames top most first. Only
         *                             needed if not using the PHP
         *                             backtrace function.
         *    @return string           Line number of first expect*
         *                             method embedded in format string.
         *    @access public
         *    @static
         */
        function getExpectationLine($format = '%d', $stack = false) {
            if ($stack === false) {
                $stack = SimpleTestCompatibility::getStackTrace();
            }
            return SimpleDumper::getFormattedAssertionLine($stack, $format, 'expect');
        }
    }
?>