Completed
Pull Request — master (#235)
by Kenji
02:51
created

CIPHPUnitTestCase::set_error_handler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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