Completed
Push — master ( 22cc8a...794792 )
by Kenji
03:19 queued 33s
created

CIPHPUnitTestCase::getStrictRequestErrorCheck()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
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
	 * Detect warnings and notices in a request output
36
	 *
37
	 * @var bool
38
	 */
39
	protected $strictRequestErrorCheck = true;
40
41
	protected $restoreErrorHandler = false;
42
43
	/**
44
	 * @var CI_Controller CodeIgniter instance
45
	 */
46
	protected $CI;
47
48
	protected $class_map = [
49
		'request'    => 'CIPHPUnitTestRequest',
50
		'double'     => 'CIPHPUnitTestDouble',
51
		'reflection' => 'CIPHPUnitTestReflection',
52
	];
53
54
	public function setCI(CI_Controller $CI)
55
	{
56
		$this->CI = $CI;
57
	}
58
59
	public function getStrictRequestErrorCheck()
60
	{
61
		return $this->strictRequestErrorCheck;
62
	}
63
64
	public function __get($name)
65
	{
66
		if (isset($this->class_map[$name]))
67
		{
68
			$this->$name = new $this->class_map[$name]($this);
69
			return $this->$name;
70
		}
71
72
		throw new LogicException('No such property: ' . $name);
73
	}
74
75
	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...
76
	{
77
		// Fix CLI args, because you may set invalid URI characters
78
		// For example, when you run tests on NetBeans
79
		$_SERVER['argv'] = [
80
			'index.php',
81
		];
82
		$_SERVER['argc'] = 1;
83
84
		// Reset current directroy
85
		chdir(FCPATH);
86
	}
87
88
	/**
89
	 * Reset CodeIgniter instance and assign new CodeIgniter instance as $this->CI
90
	 */
91
	public function resetInstance()
92
	{
93
		reset_instance();
94
		CIPHPUnitTest::createCodeIgniterInstance();
95
		$this->CI =& get_instance();
96
	}
97
98
	protected function tearDown()
99
	{
100
		$this->disableStrictErrorCheck();
101
102
		if (class_exists('MonkeyPatch', false))
103
		{
104
			if (MonkeyPatchManager::isEnabled('FunctionPatcher'))
105
			{
106
				try {
107
					MonkeyPatch::verifyFunctionInvocations();
108
				} catch (Exception $e) {
109
					MonkeyPatch::resetFunctions();
110
					throw $e;
111
				}
112
113
				MonkeyPatch::resetFunctions();
114
			}
115
116
			if (MonkeyPatchManager::isEnabled('ConstantPatcher'))
117
			{
118
				MonkeyPatch::resetConstants();
119
			}
120
121
			if (MonkeyPatchManager::isEnabled('MethodPatcher'))
122
			{
123
				try {
124
					MonkeyPatch::verifyMethodInvocations();
125
				} catch (Exception $e) {
126
					MonkeyPatch::resetMethods();
127
					throw $e;
128
				}
129
130
				MonkeyPatch::resetMethods();
131
			}
132
		}
133
	}
134
135
	/**
136
	 * Request to Controller
137
	 *
138
	 * @param string       $http_method HTTP method
139
	 * @param array|string $argv        array of controller,method,arg|uri
140
	 * @param array        $params      POST parameters/Query string
141
	 */
142
	public function request($http_method, $argv, $params = [])
143
	{
144
		return $this->request->request($http_method, $argv, $params);
145
	}
146
147
	/**
148
	 * Disable strict error check
149
	 */
150
	public function disableStrictErrorCheck()
151
	{
152
		if ($this->restoreErrorHandler) {
153
			restore_error_handler();
154
			$this->restoreErrorHandler = false;
155
		}
156
	}
157
158
	/**
159
	 * Enable strict error check
160
	 */
161
	public function enableStrictErrorCheck()
162
	{
163
		if ($this->restoreErrorHandler) {
164
			throw new LogicException('Already strict error check mode');
165
		}
166
167
		set_error_handler(
168
			function ($errno, $errstr, $errfile, $errline) {
169
				throw new RuntimeException($errstr . ' on line ' . $errline . ' in file ' . $errfile);
170
			}
171
		);
172
173
		$this->restoreErrorHandler = true;
174
	}
175
176
	/**
177
	 * Request to Controller using ajax request
178
	 *
179
	 * @param string       $http_method HTTP method
180
	 * @param array|string $argv        array of controller,method,arg|uri
181
	 * @param array        $params      POST parameters/Query string
182
	 */
183
	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...
184
	{
185
		$_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
186
		return $this->request($http_method, $argv, $params);
187
	}
188
189
	/**
190
	 * Get Mock Object
191
	 *
192
	 * $email = $this->getMockBuilder('CI_Email')
193
	 *	->setMethods(['send'])
194
	 *	->getMock();
195
	 * $email->method('send')->willReturn(TRUE);
196
	 *
197
	 *  will be
198
	 *
199
	 * $email = $this->getDouble('CI_Email', ['send' => TRUE]);
200
	 *
201
	 * @param  string $classname
202
	 * @param  array  $params             [method_name => return_value]
203
	 * @param  bool   $enable_constructor enable constructor or not
204
	 * @return object PHPUnit mock object
205
	 */
206
	public function getDouble($classname, $params, $enable_constructor = false)
207
	{
208
		return $this->double->getDouble($classname, $params, $enable_constructor);
209
	}
210
211
	/**
212
	 * Verifies that method was called exactly $times times
213
	 *
214
	 * $loader->expects($this->exactly(2))
215
	 * 	->method('view')
216
	 * 	->withConsecutive(
217
	 *		['shop_confirm', $this->anything(), TRUE],
218
	 * 		['shop_tmpl_checkout', $this->anything()]
219
	 * 	);
220
	 *
221
	 *  will be
222
	 *
223
	 * $this->verifyInvokedMultipleTimes(
224
	 * 	$loader,
225
	 * 	'view',
226
	 * 	2,
227
	 * 	[
228
	 * 		['shop_confirm', $this->anything(), TRUE],
229
	 * 		['shop_tmpl_checkout', $this->anything()]
230
	 * 	]
231
	 * );
232
	 *
233
	 * @param object $mock   PHPUnit mock object
234
	 * @param string $method
235
	 * @param int    $times
236
	 * @param array  $params arguments
237
	 */
238
	public function verifyInvokedMultipleTimes($mock, $method, $times, $params = null)
239
	{
240
		$this->double->verifyInvokedMultipleTimes(
241
			$mock, $method, $times, $params
242
		);
243
	}
244
245
	/**
246
	 * Verifies a method was invoked at least once
247
	 *
248
	 * @param object $mock   PHPUnit mock object
249
	 * @param string $method
250
	 * @param array  $params arguments
251
	 */
252
	public function verifyInvoked($mock, $method, $params = null)
253
	{
254
		$this->double->verifyInvoked($mock, $method, $params);
255
	}
256
257
	/**
258
	 * Verifies that method was invoked only once
259
	 *
260
	 * @param object $mock   PHPUnit mock object
261
	 * @param string $method
262
	 * @param array  $params arguments
263
	 */
264
	public function verifyInvokedOnce($mock, $method, $params = null)
265
	{
266
		$this->double->verifyInvokedOnce($mock, $method, $params);
267
	}
268
269
	/**
270
	 * Verifies that method was not called
271
	 *
272
	 * @param object $mock   PHPUnit mock object
273
	 * @param string $method
274
	 * @param array  $params arguments
275
	 */
276
	public function verifyNeverInvoked($mock, $method, $params = null)
277
	{
278
		$this->double->verifyNeverInvoked($mock, $method, $params);
279
	}
280
281
	public function warningOff()
282
	{
283
		$this->_error_reporting = error_reporting(
284
			E_ALL & ~E_WARNING & ~E_NOTICE
285
		);
286
	}
287
288
	public function warningOn()
289
	{
290
		error_reporting($this->_error_reporting);
291
	}
292
293
	/**
294
	 * Asserts HTTP response code
295
	 *
296
	 * @param int $code
297
	 */
298
	public function assertResponseCode($code)
299
	{
300
		$status = $this->request->getStatus();
301
		$actual = $status['code'];
302
303
		$this->assertSame(
304
			$code,
305
			$actual,
306
			'Status code is not ' . $code . ' but ' . $actual . '.'
307
		);
308
	}
309
310
	/**
311
	 * Asserts HTTP response header
312
	 *
313
	 * @param string $name  header name
314
	 * @param string $value header value
315
	 */
316
	public function assertResponseHeader($name, $value)
317
	{
318
		$CI =& get_instance();
319
		$actual = $CI->output->get_header($name);
320
321
		if ($actual === null)
322
		{
323
			$this->fail("The '$name' header is not set.\nNote that `assertResponseHeader()` can only assert headers set by `\$this->output->set_header()`");
324
		}
325
326
		$this->assertEquals(
327
			$value,
328
			$actual,
329
			"The '$name' header is not '$value' but '$actual'."
330
		);
331
	}
332
333
	/**
334
	 * Asserts HTTP response cookie
335
	 *
336
	 * @param string       $name            cookie name
337
	 * @param string|array $value           cookie value|array of cookie params
338
	 * @param bool         $allow_duplicate whether to allow duplicated cookies
339
	 */
340
	public function assertResponseCookie($name, $value, $allow_duplicate = false)
341
	{
342
		$CI =& get_instance();
343
		$cookies = isset($CI->output->_cookies[$name])
344
			? $CI->output->_cookies[$name] : null;
345
346
		if ($cookies === null)
347
		{
348
			$this->fail("The cookie '$name' is not set.\nNote that `assertResponseCookie()` can only assert cookies set by `\$this->input->set_cookie()`");
349
		}
350
351
		$count = count($cookies);
352
		if ($count > 1 && ! $allow_duplicate)
353
		{
354
			$values = [];
355
			foreach ($cookies as $key => $val)
356
			{
357
				$values[] = "'{$val['value']}'";
358
			}
359
			$values = implode(' and ', $values);
360
			$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()`");
361
		}
362
363
		// Get the last cookie
364
		$cookie = $cookies[$count - 1];
365
		if (is_string($value))
366
		{
367
			$this->assertEquals(
368
				$value,
369
				$cookie['value'],
370
				"The cookie '$name' value is not '$value' but '{$cookie['value']}'."
371
			);
372
			return;
373
		}
374
375
		// 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...
376
		if (
377
			$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...
378
			|| $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...
379
		)
380
		{
381
			$this->assertTrue(true);
382
			return;
383
		}
384
385
		foreach ($value as $key => $val)
386
		{
387
			$this->assertEquals(
388
				$value[$key],
389
				$cookie[$key],
390
				"The cookie '$name' $key is not '{$value[$key]}' but '{$cookie[$key]}'."
391
			);
392
		}
393
	}
394
395
	/**
396
	 * Asserts Redirect
397
	 *
398
	 * @param string $uri  URI to redirect
399
	 * @param int    $code response code
400
	 */
401
	public function assertRedirect($uri, $code = null)
402
	{
403
		$status = $this->request->getStatus();
404
405
		if ($status['redirect'] === null)
406
		{
407
			$this->fail('redirect() is not called.');
408
		}
409
410
		if (! function_exists('site_url'))
411
		{
412
			$CI =& get_instance();
413
			$CI->load->helper('url');
414
		}
415
416
		if (! preg_match('#^(\w+:)?//#i', $uri))
417
		{
418
			$uri = site_url($uri);
419
		}
420
		$absolute_url = $uri;
421
		$expected = 'Redirect to ' . $absolute_url;
422
423
		$this->assertSame(
424
			$expected,
425
			$status['redirect'],
426
			'URL to redirect is not ' . $expected . ' but ' . $status['redirect'] . '.'
427
		);
428
429
		if ($code !== null)
430
		{
431
			$this->assertSame(
432
				$code,
433
				$status['code'],
434
				'Status code is not ' . $code . ' but ' . $status['code'] . '.'
435
			);
436
		}
437
	}
438
}
439