-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMockFunction.php
More file actions
329 lines (293 loc) · 8.62 KB
/
MockFunction.php
File metadata and controls
329 lines (293 loc) · 8.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
<?php
/**
* Extension for PHPUnit that makes MockObject-style expectations possible for global functions (even PECL functions).
*
* @author zoltan.tothczifra
*/
class PHPUnit_Extensions_MockFunction
{
/**
* Incremental ID of the current object instance to be able to find it.
*
* @see self::$instances
* @var integer
*/
protected $id;
/**
* Flag to tell if the function mocking is active or not (replacement is in place).
*
* @var boolean
*/
protected $active = false;
/**
* Test case from where the mock function is created. Automagically found with call stack.
*
* @var PHPUnit_Framework_TestCase
*/
protected $test_case;
/**
* Standard PHPUnit MockObject used to test invocations of the mocked function.
*
* @var object
*/
protected $mock_object;
/**
* Object to check if the function is called from its scope (supposedly the test object to the test case).
*
* If the mocked function is called outside its scope, the original (unmocked)
* function is executed - if there is.
*
* @var object
*/
protected $scope_object;
/**
* The name of the original function that gets mocked.
*
* @var string
*/
protected $function_name;
/**
* Random temporary name of a funstion there we "save" the original, unmocked function.
*
* If the function did not exist before mocking, it's empty.
*
* @var string
*/
protected $restore_name;
/**
* Value of the incremental ID that next time will be assigned to an instance of this class.
*
* @var integer
*/
protected static $next_id = 1;
/**
* List of active mock object instances (those that are not restored) with their ID as key.
*
* @var PHPUnit_Extensions_MockFunction[]
*/
protected static $instances = array();
/**
* Class name of PHPUnit test cases, used to automatically find them in the call stack.
*/
const TESTCASE_CLASSNAME = 'PHPUnit_Framework_TestCase';
/**
* Number of call stack items between the function call of the test object and self::invoked().
*
* 1. Inocation from test object
* 2. Runkit function
* 3. Call to self::invoked().
*/
const CALL_STACK_DISTANCE = 3;
/**
* Constructor setting up object.
*
* @param string $function_name Name of the function to mock. Doesn't need to exist, might be newly created.
* @param object $scope_object Object specifying the scope where the mocked function is used.
*/
public function __construct( $function_name, $scope_object )
{
if ( !function_exists( 'runkit_function_redefine' ) )
{
trigger_error( 'Runkit is not installed.', E_USER_ERROR );
}
// APC doesn't quite like runkit.
// When they work together, it might result dead process.
if ( function_exists( 'apc_clear_cache' ) )
{
apc_clear_cache();
}
$this->id = self::$next_id;
$this->function_name = $function_name;
$this->scope_object = $scope_object;
$this->test_case = self::findTestCase();
$this->mock_object =
$this->test_case->getMockBuilder(
'Mock_' . str_replace( '::', '__', $this->function_name ) . '_' . $this->id
)
->disableAutoload()
->setMethods(array( 'invoked' ))
->getMock();
++self::$next_id;
self::$instances[$this->id] = $this;
$this->createFunction();
}
/**
* Called when all the referneces to the object are removed (even self::$instances).
*
* Makes sure the replaced functions are finally cleared in case runkit
* "forgets" to remove them in the end of the request.
* It is still highly recommended to call restore() explicitly!
*/
public function __destruct()
{
$this->restore();
}
/**
* Clean-up function.
*
* Removes mocked function and restored the original was there is any.
* Also removes the reference to the object from self::$instances.
*/
public function restore()
{
if ( $this->active )
{
runkit_function_remove( $this->function_name );
if ( isset( $this->restore_name ) )
{
runkit_function_rename( $this->restore_name, $this->function_name );
}
$this->active = false;
}
if ( isset( self::$instances[$this->id] ) )
{
unset( self::$instances[$this->id] );
}
}
/**
* Callback method to be used in runkit function when it is invoked.
*
* It takes the parameters of the function call and passes them to the mock object.
*
* @param type $arguments 0-indexed array of arguments with which the mocked function was called.
* @return mixed
*/
public function invoked( array $arguments )
{
// Original function is called when the invocation is ousides he scope or
// the invocation comes from this object.
$caller_object = self::getCallStackObject( self::CALL_STACK_DISTANCE );
if ( $caller_object === $this || ( isset( $this->scope_object ) && $this->scope_object !== $caller_object ) )
{
if ( isset( $this->restore_name ) )
{
return $this->callOriginal( $arguments );
}
trigger_error( 'Undefined function: ' . $this->function_name, E_USER_ERROR );
}
return call_user_func_array( array( $this->mock_object, __FUNCTION__ ), $arguments );
}
/**
* Calls original function that we temporary renamed. This maintains the oriignal functionality.
*
* @param type $arguments
* @return mixed
*/
protected function callOriginal( array $arguments )
{
return call_user_func_array( $this->restore_name, $arguments );
}
/**
* Proxy to the 'expects' of the mock object.
*
* Also calld method() so after this the mock object can be used to set
* parameter constraints and return values.
*
* @return object
*/
public function expects()
{
$arguments = func_get_args();
return call_user_func_array( array( $this->mock_object, __FUNCTION__ ), $arguments )->method( 'invoked' );
}
/**
* Returns an instance of this class selected by its ID. Used in the runkit function.
*
* @param integer $id
* @return object
*/
public static function findMock( $id )
{
if ( !isset( self::$instances[$id] ) )
{
throw new Exception( 'Mock object not found, might be destroyed already.' );
}
return self::$instances[$id];
}
/**
* Finds the rist object in the call cstack that is instance of a PHPUnit test case.
*
* @see self::TESTCASE_CLASSNAME
* @return PHPUnit_Framework_TestCase
*/
public static function findTestCase()
{
$backtrace = debug_backtrace();
$classname = self::TESTCASE_CLASSNAME;
do
{
$calling_test = array_shift( $backtrace );
} while( isset( $calling_test ) && !( isset( $calling_test['object'] ) && $calling_test['object'] instanceof $classname ) );
if ( !isset( $calling_test ) )
{
trigger_error( 'No calling test found.', E_USER_ERROR );
}
return $calling_test['object'];
}
/**
* Creates runkit function to be used for mocking, taking care of callback to this object.
*
* Also temporary renames the original function if there is.
*/
protected function createFunction()
{
if ( function_exists( $this->function_name ) )
{
$this->restore_name = 'restore_' . $this->function_name . '_' . $this->id . '_' . uniqid();
runkit_function_copy( $this->function_name, $this->restore_name );
runkit_function_redefine( $this->function_name, '', $this->getCallback() );
}
else
{
runkit_function_add( $this->function_name, '', $this->getCallback() );
}
$this->active = true;
}
/**
* Gives back the source code body of the runkit function replacing the original.
*
* The function is quite simple - find the function mock instance (of this class)
* that created it, then calls its invoked() method with the parameters of its invokation.
*
* @return string
*/
protected function getCallback()
{
$class_name = __CLASS__;
return <<<CALLBACK
\$mock = $class_name::findMock( {$this->id} );
\$arguments = func_get_args();
return \$mock->invoked( \$arguments );
CALLBACK;
}
/**
* Returns an object from the call stack at Nth distance if there is, null otherwise.
*
* In theory we should instement the distance by one because when we call this
* method, we don't count it itself to the callstack, but since the stack is
* 0-indexed, we can avoid this step.
*
* Function calls are ignored, the first call after $distance that is made form
* is returned.
*
* @param type $distance The distance in the call stack from the current call and the desired one.
* @return object
*/
protected static function getCallStackObject( $distance )
{
$backtrace = debug_backtrace();
do
{
if ( isset( $backtrace[$distance]['object'] ) )
{
return $backtrace[$distance]['object'];
}
/* If there is no object assiciated to this call, we go further until
* the next one.
* Funcsion calls and functions like "user_call_func" get ignored.
*/
++$distance;
} while ( isset( $backtrace[$distance] ) );
return null;
}
}