Completed
Pull Request — master (#233)
by Kenji
02:41
created

CIPHPUnitTestCase::newController()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 22 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
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()
0 ignored issues
show
Coding Style introduced by
setUpBeforeClass uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
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
	protected function tearDown()
85
	{
86
		if (class_exists('MonkeyPatch', false))
87
		{
88
			if (MonkeyPatchManager::isEnabled('FunctionPatcher'))
89
			{
90
				try {
91
					MonkeyPatch::verifyFunctionInvocations();
92
				} catch (Exception $e) {
93
					MonkeyPatch::resetFunctions();
94
					throw $e;
95
				}
96
97
				MonkeyPatch::resetFunctions();
98
			}
99
100
			if (MonkeyPatchManager::isEnabled('ConstantPatcher'))
101
			{
102
				MonkeyPatch::resetConstants();
103
			}
104
105
			if (MonkeyPatchManager::isEnabled('MethodPatcher'))
106
			{
107
				try {
108
					MonkeyPatch::verifyMethodInvocations();
109
				} catch (Exception $e) {
110
					MonkeyPatch::resetMethods();
111
					throw $e;
112
				}
113
114
				MonkeyPatch::resetMethods();
115
			}
116
		}
117
	}
118
119
	/**
120
	 * Request to Controller
121
	 *
122
	 * @param string       $http_method HTTP method
123
	 * @param array|string $argv        array of controller,method,arg|uri
124
	 * @param array        $params      POST parameters/Query string
125
	 */
126
	public function request($http_method, $argv, $params = [])
127
	{
128
		return $this->request->request($http_method, $argv, $params);
129
	}
130
131
	/**
132
	 * Request to Controller using ajax request
133
	 *
134
	 * @param string       $http_method HTTP method
135
	 * @param array|string $argv        array of controller,method,arg|uri
136
	 * @param array        $params      POST parameters/Query string
137
	 */
138
	public function ajaxRequest($http_method, $argv, $params = [])
0 ignored issues
show
Coding Style introduced by
ajaxRequest uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
139
	{
140
		$_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
141
		return $this->request($http_method, $argv, $params);
142
	}
143
144
	/**
145
	 * Get Mock Object
146
	 *
147
	 * $email = $this->getMockBuilder('CI_Email')
148
	 *	->setMethods(['send'])
149
	 *	->getMock();
150
	 * $email->method('send')->willReturn(TRUE);
151
	 *
152
	 *  will be
153
	 *
154
	 * $email = $this->getDouble('CI_Email', ['send' => TRUE]);
155
	 *
156
	 * @param  string $classname
157
	 * @param  array  $params             [method_name => return_value]
158
	 * @param  bool   $enable_constructor enable constructor or not
159
	 * @return object PHPUnit mock object
160
	 */
161
	public function getDouble($classname, $params, $enable_constructor = false)
162
	{
163
		return $this->double->getDouble($classname, $params, $enable_constructor);
164
	}
165
166
	/**
167
	 * Verifies that method was called exactly $times times
168
	 *
169
	 * $loader->expects($this->exactly(2))
170
	 * 	->method('view')
171
	 * 	->withConsecutive(
172
	 *		['shop_confirm', $this->anything(), TRUE],
173
	 * 		['shop_tmpl_checkout', $this->anything()]
174
	 * 	);
175
	 *
176
	 *  will be
177
	 *
178
	 * $this->verifyInvokedMultipleTimes(
179
	 * 	$loader,
180
	 * 	'view',
181
	 * 	2,
182
	 * 	[
183
	 * 		['shop_confirm', $this->anything(), TRUE],
184
	 * 		['shop_tmpl_checkout', $this->anything()]
185
	 * 	]
186
	 * );
187
	 *
188
	 * @param object $mock   PHPUnit mock object
189
	 * @param string $method
190
	 * @param int    $times
191
	 * @param array  $params arguments
192
	 */
193
	public function verifyInvokedMultipleTimes($mock, $method, $times, $params = null)
194
	{
195
		$this->double->verifyInvokedMultipleTimes(
196
			$mock, $method, $times, $params
197
		);
198
	}
199
200
	/**
201
	 * Verifies a method was invoked at least once
202
	 *
203
	 * @param object $mock   PHPUnit mock object
204
	 * @param string $method
205
	 * @param array  $params arguments
206
	 */
207
	public function verifyInvoked($mock, $method, $params = null)
208
	{
209
		$this->double->verifyInvoked($mock, $method, $params);
210
	}
211
212
	/**
213
	 * Verifies that method was invoked only once
214
	 *
215
	 * @param object $mock   PHPUnit mock object
216
	 * @param string $method
217
	 * @param array  $params arguments
218
	 */
219
	public function verifyInvokedOnce($mock, $method, $params = null)
220
	{
221
		$this->double->verifyInvokedOnce($mock, $method, $params);
222
	}
223
224
	/**
225
	 * Verifies that method was not called
226
	 *
227
	 * @param object $mock   PHPUnit mock object
228
	 * @param string $method
229
	 * @param array  $params arguments
230
	 */
231
	public function verifyNeverInvoked($mock, $method, $params = null)
232
	{
233
		$this->double->verifyNeverInvoked($mock, $method, $params);
234
	}
235
236
	public function warningOff()
237
	{
238
		$this->_error_reporting = error_reporting(
239
			E_ALL & ~E_WARNING & ~E_NOTICE
240
		);
241
	}
242
243
	public function warningOn()
244
	{
245
		error_reporting($this->_error_reporting);
246
	}
247
248
	/**
249
	 * Asserts HTTP response code
250
	 *
251
	 * @param int $code
252
	 */
253
	public function assertResponseCode($code)
254
	{
255
		$status = $this->request->getStatus();
256
		$actual = $status['code'];
257
258
		$this->assertSame(
259
			$code,
260
			$actual,
261
			'Status code is not ' . $code . ' but ' . $actual . '.'
262
		);
263
	}
264
265
	/**
266
	 * Asserts HTTP response header
267
	 *
268
	 * @param string $name  header name
269
	 * @param string $value header value
270
	 */
271
	public function assertResponseHeader($name, $value)
272
	{
273
		$CI =& get_instance();
274
		$actual = $CI->output->get_header($name);
275
276
		if ($actual === null)
277
		{
278
			$this->fail("The '$name' header is not set.\nNote that `assertResponseHeader()` can only assert headers set by `\$this->output->set_header()`");
279
		}
280
281
		$this->assertEquals(
282
			$value,
283
			$actual,
284
			"The '$name' header is not '$value' but '$actual'."
285
		);
286
	}
287
288
	/**
289
	 * Asserts HTTP response cookie
290
	 *
291
	 * @param string       $name            cookie name
292
	 * @param string|array $value           cookie value|array of cookie params
293
	 * @param bool         $allow_duplicate whether to allow duplicated cookies
294
	 */
295
	public function assertResponseCookie($name, $value, $allow_duplicate = false)
296
	{
297
		$CI =& get_instance();
298
		$cookies = isset($CI->output->_cookies[$name])
299
			? $CI->output->_cookies[$name] : null;
300
301
		if ($cookies === null)
302
		{
303
			$this->fail("The cookie '$name' is not set.\nNote that `assertResponseCookie()` can only assert cookies set by `\$this->input->set_cookie()`");
304
		}
305
306
		$count = count($cookies);
307
		if ($count > 1 && ! $allow_duplicate)
308
		{
309
			$values = [];
310
			foreach ($cookies as $key => $val)
311
			{
312
				$values[] = "'{$val['value']}'";
313
			}
314
			$values = implode(' and ', $values);
315
			$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()`");
316
		}
317
318
		// Get the last cookie
319
		$cookie = $cookies[$count - 1];
320
		if (is_string($value))
321
		{
322
			$this->assertEquals(
323
				$value,
324
				$cookie['value'],
325
				"The cookie '$name' value is not '$value' but '{$cookie['value']}'."
326
			);
327
			return;
328
		}
329
330
		// In case of $this->anything()
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
331
		if (
332
			$value instanceof PHPUnit_Framework_Constraint_IsAnything
0 ignored issues
show
Bug introduced by
The class PHPUnit_Framework_Constraint_IsAnything does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
333
			|| $value instanceof PHPUnit\Framework\Constraint\IsAnything
0 ignored issues
show
Bug introduced by
The class PHPUnit\Framework\Constraint\IsAnything does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
334
		)
335
		{
336
			$this->assertTrue(true);
337
			return;
338
		}
339
340
		foreach ($value as $key => $val)
341
		{
342
			$this->assertEquals(
343
				$value[$key],
344
				$cookie[$key],
345
				"The cookie '$name' $key is not '{$value[$key]}' but '{$cookie[$key]}'."
346
			);
347
		}
348
	}
349
350
	/**
351
	 * Asserts Redirect
352
	 *
353
	 * @param string $uri  URI to redirect
354
	 * @param int    $code response code
355
	 */
356
	public function assertRedirect($uri, $code = null)
357
	{
358
		$status = $this->request->getStatus();
359
360
		if ($status['redirect'] === null)
361
		{
362
			$this->fail('redirect() is not called.');
363
		}
364
365
		if (! function_exists('site_url'))
366
		{
367
			$CI =& get_instance();
368
			$CI->load->helper('url');
369
		}
370
371
		if (! preg_match('#^(\w+:)?//#i', $uri))
372
		{
373
			$uri = site_url($uri);
374
		}
375
		$absolute_url = $uri;
376
		$expected = 'Redirect to ' . $absolute_url;
377
378
		$this->assertSame(
379
			$expected,
380
			$status['redirect'],
381
			'URL to redirect is not ' . $expected . ' but ' . $status['redirect'] . '.'
382
		);
383
384
		if ($code !== null)
385
		{
386
			$this->assertSame(
387
				$code,
388
				$status['code'],
389
				'Status code is not ' . $code . ' but ' . $status['code'] . '.'
390
			);
391
		}
392
	}
393
}
394