Completed
Pull Request — master (#232)
by
unknown
09:30
created

tests/_ci_phpunit_test/CIPHPUnitTestCase.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Part of ci-phpunit-test
4
 *
5
 * @author     Kenji Suzuki <https://github.com/kenjis>
6
 * @license    MIT License
7
 * @copyright  2015 Kenji Suzuki
8
 * @link       https://github.com/kenjis/ci-phpunit-test
9
 */
10
11
// Support PHPUnit 6.0
12
if (! class_exists('PHPUnit_Framework_TestCase'))
13
{
14
	class_alias('PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase');
15
}
16
17
/**
18
 * @property CIPHPUnitTestRequest    $request
19
 * @property CIPHPUnitTestDouble     $double
20
 * @property CIPHPUnitTestReflection $reflection
21
 */
22
class CIPHPUnitTestCase extends PHPUnit_Framework_TestCase
23
{
24
	protected $_error_reporting = -1;
25
26
	/**
27
	 * If you have a route with closure, PHPUnit can't serialize global variables.
28
	 * You would see `Exception: Serialization of 'Closure' is not allowed`.
29
	 *
30
	 * @var array
31
	 */
32
	protected $backupGlobalsBlacklist = ['RTR'];
33
34
	/**
35
	 * @var CI_Controller CodeIgniter instance
36
	 */
37
	protected $CI;
38
39
	protected $class_map = [
40
		'request'    => 'CIPHPUnitTestRequest',
41
		'double'     => 'CIPHPUnitTestDouble',
42
		'reflection' => 'CIPHPUnitTestReflection',
43
	];
44
45
	public function setCI(CI_Controller $CI)
46
	{
47
		$this->CI = $CI;
48
	}
49
50
	public function __get($name)
51
	{
52
		if (isset($this->class_map[$name]))
53
		{
54
			$this->$name = new $this->class_map[$name]($this);
55
			return $this->$name;
56
		}
57
58
		throw new LogicException('No such property: ' . $name);
59
	}
60
61
	public static function setUpBeforeClass()
62
	{
63
		// Fix CLI args, because you may set invalid URI characters
64
		// For example, when you run tests on NetBeans
65
		$_SERVER['argv'] = [
66
			'index.php',
67
		];
68
		$_SERVER['argc'] = 1;
69
70
		// Reset current directroy
71
		chdir(FCPATH);
72
	}
73
74
	/**
75
	 * Reset CodeIgniter instance and assign new CodeIgniter instance as $this->CI
76
	 */
77
	public function resetInstance()
78
	{
79
		reset_instance();
80
		CIPHPUnitTest::createCodeIgniterInstance();
81
		$this->CI =& get_instance();
82
	}
83
84
	/**
85
	 * Create a controller instance
86
	 *
87
	 * @param string $classname
88
	 * @return CI_Controller
89
	 */
90
	public function newController($classname)
91
	{
92
		reset_instance();
93
		$controller = new $classname;
94
		$this->CI =& get_instance();
95
		return $controller;
96
	}
97
98
	/**
99
	 * Create a model instance
100
	 *
101
	 * @param string $classname
102
	 * @return CI_Model
103
	 */
104
	public function newModel($classname)
105
	{
106
		$this->resetInstance();
107
		$this->CI->load->model($classname);
108
109
		// Is the model in a sub-folder?
110 View Code Duplication
		if (($last_slash = strrpos($classname, '/')) !== FALSE)
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
111
		{
112
			$classname = substr($classname, ++$last_slash);
113
		}
114
115
		return $this->CI->$classname;
116
	}
117
118
	/**
119
	 * Create a library instance
120
	 *
121
	 * @param string $classname
122
	 * @param array  $args
123
	 * @return object
124
	 */
125
	public function newLibrary($classname, $args = null)
126
	{
127
		$this->resetInstance();
128
		$this->CI->load->library($classname, $args);
129
130
		// Is the library in a sub-folder?
131 View Code Duplication
		if (($last_slash = strrpos($classname, '/')) !== FALSE)
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
		{
133
			$classname = substr($classname, ++$last_slash);
134
		}
135
		$classname = strtolower($classname);
136
137
		return $this->CI->$classname;
138
	}
139
140
	protected function tearDown()
141
	{
142
		if (class_exists('MonkeyPatch', false))
143
		{
144
			if (MonkeyPatchManager::isEnabled('FunctionPatcher'))
145
			{
146
				try {
147
					MonkeyPatch::verifyFunctionInvocations();
148
				} catch (Exception $e) {
149
					MonkeyPatch::resetFunctions();
150
					throw $e;
151
				}
152
153
				MonkeyPatch::resetFunctions();
154
			}
155
156
			if (MonkeyPatchManager::isEnabled('ConstantPatcher'))
157
			{
158
				MonkeyPatch::resetConstants();
159
			}
160
161
			if (MonkeyPatchManager::isEnabled('MethodPatcher'))
162
			{
163
				try {
164
					MonkeyPatch::verifyMethodInvocations();
165
				} catch (Exception $e) {
166
					MonkeyPatch::resetMethods();
167
					throw $e;
168
				}
169
170
				MonkeyPatch::resetMethods();
171
			}
172
		}
173
	}
174
175
	/**
176
	 * Request to Controller
177
	 *
178
	 * @param string       $http_method HTTP method
179
	 * @param array|string $argv        array of controller,method,arg|uri
180
	 * @param array        $params      POST parameters/Query string
181
	 */
182
	public function request($http_method, $argv, $params = [])
183
	{
184
		return $this->request->request($http_method, $argv, $params);
185
	}
186
187
	/**
188
	 * Request to Controller using ajax request
189
	 *
190
	 * @param string       $http_method HTTP method
191
	 * @param array|string $argv        array of controller,method,arg|uri
192
	 * @param array        $params      POST parameters/Query string
193
	 */
194
	public function ajaxRequest($http_method, $argv, $params = [])
195
	{
196
		$_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
197
		return $this->request($http_method, $argv, $params);
198
	}
199
200
	/**
201
	 * Get Mock Object
202
	 *
203
	 * $email = $this->getMockBuilder('CI_Email')
204
	 *	->setMethods(['send'])
205
	 *	->getMock();
206
	 * $email->method('send')->willReturn(TRUE);
207
	 *
208
	 *  will be
209
	 *
210
	 * $email = $this->getDouble('CI_Email', ['send' => TRUE]);
211
	 *
212
	 * @param  string $classname
213
	 * @param  array  $params             [method_name => return_value]
214
	 * @param  bool   $enable_constructor enable constructor or not
215
	 * @return object PHPUnit mock object
216
	 */
217
	public function getDouble($classname, $params, $enable_constructor = false)
218
	{
219
		return $this->double->getDouble($classname, $params, $enable_constructor);
220
	}
221
222
	/**
223
	 * Verifies that method was called exactly $times times
224
	 *
225
	 * $loader->expects($this->exactly(2))
226
	 * 	->method('view')
227
	 * 	->withConsecutive(
228
	 *		['shop_confirm', $this->anything(), TRUE],
229
	 * 		['shop_tmpl_checkout', $this->anything()]
230
	 * 	);
231
	 *
232
	 *  will be
233
	 *
234
	 * $this->verifyInvokedMultipleTimes(
235
	 * 	$loader,
236
	 * 	'view',
237
	 * 	2,
238
	 * 	[
239
	 * 		['shop_confirm', $this->anything(), TRUE],
240
	 * 		['shop_tmpl_checkout', $this->anything()]
241
	 * 	]
242
	 * );
243
	 *
244
	 * @param object $mock   PHPUnit mock object
245
	 * @param string $method
246
	 * @param int    $times
247
	 * @param array  $params arguments
248
	 */
249
	public function verifyInvokedMultipleTimes($mock, $method, $times, $params = null)
250
	{
251
		$this->double->verifyInvokedMultipleTimes(
252
			$mock, $method, $times, $params
253
		);
254
	}
255
256
	/**
257
	 * Verifies a method was invoked at least once
258
	 *
259
	 * @param object $mock   PHPUnit mock object
260
	 * @param string $method
261
	 * @param array  $params arguments
262
	 */
263
	public function verifyInvoked($mock, $method, $params = null)
264
	{
265
		$this->double->verifyInvoked($mock, $method, $params);
266
	}
267
268
	/**
269
	 * Verifies that method was invoked only once
270
	 *
271
	 * @param object $mock   PHPUnit mock object
272
	 * @param string $method
273
	 * @param array  $params arguments
274
	 */
275
	public function verifyInvokedOnce($mock, $method, $params = null)
276
	{
277
		$this->double->verifyInvokedOnce($mock, $method, $params);
278
	}
279
280
	/**
281
	 * Verifies that method was not called
282
	 *
283
	 * @param object $mock   PHPUnit mock object
284
	 * @param string $method
285
	 * @param array  $params arguments
286
	 */
287
	public function verifyNeverInvoked($mock, $method, $params = null)
288
	{
289
		$this->double->verifyNeverInvoked($mock, $method, $params);
290
	}
291
292
	public function warningOff()
293
	{
294
		$this->_error_reporting = error_reporting(
295
			E_ALL & ~E_WARNING & ~E_NOTICE
296
		);
297
	}
298
299
	public function warningOn()
300
	{
301
		error_reporting($this->_error_reporting);
302
	}
303
304
	/**
305
	 * Asserts HTTP response code
306
	 *
307
	 * @param int $code
308
	 */
309
	public function assertResponseCode($code)
310
	{
311
		$status = $this->request->getStatus();
312
		$actual = $status['code'];
313
314
		$this->assertSame(
315
			$code,
316
			$actual,
317
			'Status code is not ' . $code . ' but ' . $actual . '.'
318
		);
319
	}
320
321
	/**
322
	 * Asserts HTTP response header
323
	 *
324
	 * @param string $name  header name
325
	 * @param string $value header value
326
	 */
327
	public function assertResponseHeader($name, $value)
328
	{
329
		$CI =& get_instance();
330
		$actual = $CI->output->get_header($name);
331
332
		if ($actual === null)
333
		{
334
			$this->fail("The '$name' header is not set.\nNote that `assertResponseHeader()` can only assert headers set by `\$this->output->set_header()`");
335
		}
336
337
		$this->assertEquals(
338
			$value,
339
			$actual,
340
			"The '$name' header is not '$value' but '$actual'."
341
		);
342
	}
343
344
	/**
345
	 * Asserts HTTP response cookie
346
	 *
347
	 * @param string       $name            cookie name
348
	 * @param string|array $value           cookie value|array of cookie params
349
	 * @param bool         $allow_duplicate whether to allow duplicated cookies
350
	 */
351
	public function assertResponseCookie($name, $value, $allow_duplicate = false)
352
	{
353
		$CI =& get_instance();
354
		$cookies = isset($CI->output->_cookies[$name])
355
			? $CI->output->_cookies[$name] : null;
356
357
		if ($cookies === null)
358
		{
359
			$this->fail("The cookie '$name' is not set.\nNote that `assertResponseCookie()` can only assert cookies set by `\$this->input->set_cookie()`");
360
		}
361
362
		$count = count($cookies);
363
		if ($count > 1 && ! $allow_duplicate)
364
		{
365
			$values = [];
366
			foreach ($cookies as $key => $val)
367
			{
368
				$values[] = "'{$val['value']}'";
369
			}
370
			$values = implode(' and ', $values);
371
			$this->fail("You have more than one cookie '$name'. The values are $values.\nIf it is okay, please set `true` as the 3rd argument of `assertResponseCookie()`");
372
		}
373
374
		// Get the last cookie
375
		$cookie = $cookies[$count - 1];
376
		if (is_string($value))
377
		{
378
			$this->assertEquals(
379
				$value,
380
				$cookie['value'],
381
				"The cookie '$name' value is not '$value' but '{$cookie['value']}'."
382
			);
383
			return;
384
		}
385
386
		// In case of $this->anything()
387
		if (
388
			$value instanceof PHPUnit_Framework_Constraint_IsAnything
389
			|| $value instanceof PHPUnit\Framework\Constraint\IsAnything
390
		)
391
		{
392
			$this->assertTrue(true);
393
			return;
394
		}
395
396
		foreach ($value as $key => $val)
397
		{
398
			$this->assertEquals(
399
				$value[$key],
400
				$cookie[$key],
401
				"The cookie '$name' $key is not '{$value[$key]}' but '{$cookie[$key]}'."
402
			);
403
		}
404
	}
405
406
	/**
407
	 * Asserts Redirect
408
	 *
409
	 * @param string $uri  URI to redirect
410
	 * @param int    $code response code
411
	 */
412
	public function assertRedirect($uri, $code = null)
413
	{
414
		$status = $this->request->getStatus();
415
416
		if ($status['redirect'] === null)
417
		{
418
			$this->fail('redirect() is not called.');
419
		}
420
421
		if (! function_exists('site_url'))
422
		{
423
			$CI =& get_instance();
424
			$CI->load->helper('url');
425
		}
426
427
		if (! preg_match('#^(\w+:)?//#i', $uri))
428
		{
429
			$uri = site_url($uri);
430
		}
431
		$absolute_url = $uri;
432
		$expected = 'Redirect to ' . $absolute_url;
433
434
		$this->assertSame(
435
			$expected,
436
			$status['redirect'],
437
			'URL to redirect is not ' . $expected . ' but ' . $status['redirect'] . '.'
438
		);
439
440
		if ($code !== null)
441
		{
442
			$this->assertSame(
443
				$code,
444
				$status['code'],
445
				'Status code is not ' . $code . ' but ' . $status['code'] . '.'
446
			);
447
		}
448
	}
449
}
450