/
AbstractTest.php
580 lines (517 loc) · 16.9 KB
/
AbstractTest.php
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
<?php
/**
* This file is part of PHP_PMD.
*
* PHP Version 5
*
* Copyright (c) 2009-2011, Manuel Pichler <mapi@phpmd.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Manuel Pichler nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @category PHP
* @package PHP_PMD
* @author Manuel Pichler <mapi@phpmd.org>
* @copyright 2009-2011 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version SVN: $Id$
* @link http://phpmd.org
*/
require_once 'PHPUnit/Framework/TestCase.php';
/**
* Abstract base class for PHP_PMD test cases.
*
* @category PHP
* @package PHP_PMD
* @author Manuel Pichler <mapi@phpmd.org>
* @copyright 2009-2011 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: @package_version@
* @link http://phpmd.org
*/
abstract class PHP_PMD_AbstractTest extends PHPUnit_Framework_TestCase
{
/**
* Directory with test files.
*
* @var string $_filesDirectory
*/
private static $_filesDirectory = null;
/**
* Original directory is used to reset a changed working directory.
*
* @return void
*/
private static $_originalWorkingDirectory = null;
/**
* Temporary files created by a test.
*
* @var array(string)
*/
private static $_tempFiles = array();
/**
* Resets a changed working directory.
*
* @return void
*/
protected function tearDown()
{
if (self::$_originalWorkingDirectory !== null) {
chdir(self::$_originalWorkingDirectory);
}
self::$_originalWorkingDirectory = null;
foreach (self::$_tempFiles as $tempFile) {
unlink($tempFile);
}
self::$_tempFiles = array();
parent::tearDown();
}
/**
* Returns the first class found in a source file related to the calling
* test method.
*
* @return PHP_PMD_Node_Class
*/
protected function getClass()
{
include_once 'PHP/PMD/Node/Class.php';
return new PHP_PMD_Node_Class(
$this->_getNodeForCallingTestCase(
$this->_parseTestCaseSource()
->getClasses()
)
);
}
/**
* Returns the first interface found in a source file related to the calling
* test method.
*
* @return PHP_PMD_Node_Interface
*/
protected function getInterface()
{
include_once 'PHP/PMD/Node/Interface.php';
return new PHP_PMD_Node_Interface(
$this->_getNodeForCallingTestCase(
$this->_parseTestCaseSource()
->getInterfaces()
)
);
}
/**
* Returns the first method found in a source file related to the calling
* test method.
*
* @return PHP_PMD_Node_Method
*/
protected function getMethod()
{
include_once 'PHP/PMD/Node/Method.php';
return new PHP_PMD_Node_Method(
$this->_getNodeForCallingTestCase(
$this->_parseTestCaseSource()
->getTypes()
->current()
->getMethods()
)
);
}
/**
* Returns the first function found in a source files related to the calling
* test method.
*
* @return PHP_PMD_Node_Function
*/
protected function getFunction()
{
include_once 'PHP/PMD/Node/Function.php';
return new PHP_PMD_Node_Function(
$this->_getNodeForCallingTestCase(
$this->_parseTestCaseSource()
->getFunctions()
)
);
}
/**
* Returns the absolute path for a test resource for the current test.
*
* @return string
* @since 1.1.0
*/
protected function createCodeResourceUriForTest()
{
$frame = $this->_getCallingTestCase();
if (preg_match('(_([^_]+)_[^_]+[a-z]([0-9]+)Test)i', $frame['class'], $match)) {
$localPath = $match[1] . '/' . $match[2];
} else {
$localPath = strtr(substr($frame['class'], 8, -4), '_', '/');
}
return sprintf(
'%s/../../../resources/files/%s/%s.php',
dirname(__FILE__),
$localPath,
$frame['function']
);
}
/**
* Parses the source code for the calling test method and returns the first
* package node found in the parsed file.
*
* @return PHP_Depend_Code_Package
*/
private function _parseTestCaseSource()
{
return $this->_parseSource($this->createCodeResourceUriForTest());
}
/**
* Returns the trace frame of the calling test case.
*
* @return array
*/
private function _getCallingTestCase()
{
foreach (debug_backtrace() as $frame) {
if (strpos($frame['function'], 'test') === 0) {
return $frame;
}
}
throw new ErrorException('Cannot locate calling test case.');
}
/**
* Returns the PHP_Depend node for the calling test case.
*
* @param Iterator $nodes The raw input iterator.
*
* @return PHP_Depend_Code_AbstractItem
*/
private function _getNodeForCallingTestCase(Iterator $nodes)
{
$frame = $this->_getCallingTestCase();
foreach ($nodes as $node) {
if ($node->getName() === $frame['function']) {
return $node;
}
}
throw new ErrorException('Cannot locate node for test case.');
}
/**
* Parses the source of the given file and returns the first package found
* in that file.
*
* @param string $sourceFile Name of the test source file.
*
* @return PHP_Depend_Code_Package
*/
private function _parseSource($sourceFile)
{
if (file_exists($sourceFile) === false) {
throw new ErrorException('Cannot locate source file: ' . $sourceFile);
}
$tokenizer = new PHP_Depend_Tokenizer_Internal();
$tokenizer->setSourceFile($sourceFile);
$builder = new PHP_Depend_Builder_Default();
$parser = new PHP_Depend_Parser_VersionAllParser(
$tokenizer,
$builder,
new PHP_Depend_Util_Cache_Driver_Memory()
);
$parser->parse();
return $builder->getPackages()->current();
}
/**
* Creates a mocked class node instance.
*
* @param string $metric The metric acronym used by PHP_Depend.
* @param mixed $value The expected metric return value.
*
* @return PHP_PMD_Node_Class
*/
protected function getClassMock($metric = null, $value = null)
{
include_once 'PHP/PMD/Node/Class.php';
$class = $this->getMock(
'PHP_PMD_Node_Class',
array(),
array(null),
'',
false
);
if ($metric !== null) {
$class->expects($this->atLeastOnce())
->method('getMetric')
->with($this->equalTo($metric))
->will($this->returnValue($value));
}
return $class;
}
/**
* Creates a mocked method node instance.
*
* @param string $metric The metric acronym used by PHP_Depend.
* @param mixed $value The expected metric return value.
*
* @return PHP_PMD_Node_Method
*/
protected function getMethodMock($metric = null, $value = null)
{
include_once 'PHP/PMD/Node/Method.php';
return $this->initFunctionOrMethod(
$this->getMock('PHP_PMD_Node_Method', array(), array(null), '', false),
$metric,
$value
);
}
/**
* Creates a mocked function node instance.
*
* @param string $metric The metric acronym used by PHP_Depend.
* @param mixed $value The expected metric return value.
*
* @return PHP_PMD_Node_Function
*/
protected function createFunctionMock($metric = null, $value = null)
{
include_once 'PHP/PMD/Node/Function.php';
return $this->initFunctionOrMethod(
$this->getMock('PHP_PMD_Node_Function', array(), array(null), '', false),
$metric,
$value
);
}
/**
* Initializes the getMetric() method of the given function or method node.
*
* @param PHP_PMD_Node_Function|PHP_PMD_Node_Method $mock Mock instance.
* @param string $metric Metric acronym.
* @param mixed $value Expected value.
*
* @return PHP_PMD_Node_Function|PHP_PMD_Node_Method
*/
protected function initFunctionOrMethod($mock, $metric, $value)
{
if ($metric === null) {
return $mock;
}
$mock->expects($this->atLeastOnce())
->method('getMetric')
->with($this->equalTo($metric))
->will($this->returnValue($value));
return $mock;
}
/**
* Creates a mocked report instance.
*
* @param integer $expectedInvokes Number of expected invokes.
*
* @return PHP_PMD_Report
*/
protected function getReportMock($expectedInvokes = -1)
{
include_once 'PHP/PMD/Report.php';
$expects = null;
if ($expectedInvokes < 0) {
$expects = $this->atLeastOnce();
} else if ($expectedInvokes === 0) {
$expects = $this->never();
} else if ($expectedInvokes === 1) {
$expects = $this->once();
} else {
$expects = $this->exactly($expectedInvokes);
}
$report = $this->getMock('PHP_PMD_Report');
$method = $report->expects($expects)
->method('addRuleViolation');
return $report;
}
/**
* Creates a mocked {@link PHP_PMD_AbstractRule} instance.
*
* @return PHP_PMD_AbstractRule
*/
protected function getRuleMock()
{
include_once 'PHP/PMD/AbstractRule.php';
return $this->getMockForAbstractClass('PHP_PMD_AbstractRule');
}
/**
* Creates a mocked rule-set instance.
*
* @param string $expectedClass Optional class name for apply() expected at
* least once.
* @param mixed $count How often should apply() be called?
*
* @return PHP_PMD_RuleSet
*/
protected function getRuleSetMock($expectedClass = null, $count = '*')
{
$ruleSet = $this->getMock('PHP_PMD_RuleSet');
if ($expectedClass === null) {
$ruleSet->expects($this->never())->method('apply');
} else {
$ruleSet->expects(
$count === '*' ? $this->atLeastOnce() : $this->exactly($count)
)
->method('apply')
->with($this->isInstanceOf($expectedClass));
}
return $ruleSet;
}
/**
* Creates a mocked rul violation instance.
*
* @param string $fileName The source code filename.
* @param integer $beginLine The first line where the violation context begins.
* @param integer $endLine The last line where the violation context ends.
* @param object $rule A rule instance to return.
*
* @return PHP_PMD_RuleViolation
*/
protected function getRuleViolationMock(
$fileName = '/foo/bar.php',
$beginLine = 23,
$endLine = 42,
$rule = null
) {
include_once 'PHP/PMD/RuleViolation.php';
$ruleViolation = $this->getMock(
'PHP_PMD_RuleViolation',
array(),
array(null, null, null),
'',
false
);
if ($rule === null) {
include_once self::createFileUri('stubs/RuleStub.php');
$rule = new PHP_PMD_Stubs_RuleStub();
}
$ruleViolation->expects($this->any())
->method('getRule')
->will($this->returnValue($rule));
$ruleViolation->expects($this->any())
->method('getFileName')
->will($this->returnValue($fileName));
$ruleViolation->expects($this->any())
->method('getBeginLine')
->will($this->returnValue($beginLine));
$ruleViolation->expects($this->any())
->method('getEndLine')
->will($this->returnValue($endLine));
$ruleViolation->expects($this->any())
->method('getPackageName')
->will($this->returnValue('TestStubPackage'));
$ruleViolation->expects($this->any())
->method('getDescription')
->will($this->returnValue('Test description'));
return $ruleViolation;
}
/**
* Asserts the actual xml output matches against the expected file.
*
* @param string $actualOutput Generated xml output.
* @param string $expectedFileName File with expected xml result.
*
* @return void
*/
public static function assertXmlEquals($actualOutput, $expectedFileName)
{
$actual = simplexml_load_string($actualOutput);
// Remove dynamic timestamp and duration attribute
if (isset($actual['timestamp'])) {
$actual['timestamp'] = '';
}
if (isset($actual['duration'])) {
$actual['duration'] = '';
}
$expected = file_get_contents(self::createFileUri($expectedFileName));
$expected = str_replace('#{rootDirectory}', self::$_filesDirectory, $expected);
self::assertXmlStringEqualsXmlString($expected, $actual->saveXML());
}
/**
* This method initializes the test environment, it configures the files
* directory and sets the include_path for svn versions.
*
* @return void
*/
public static function init()
{
self::$_filesDirectory = realpath(dirname(__FILE__) . '/../../../resources/files');
// file can contain test rule implementations.
$include = self::$_filesDirectory;
// Check pear installation
if (strpos('@package_version@', '@package_version') === 0) {
$include .= PATH_SEPARATOR .
realpath(dirname(__FILE__) . '/../../../../main/php') .
PATH_SEPARATOR .
realpath(dirname(__FILE__) . '/../../../../../lib/pdepend');
}
// Configure include path
set_include_path($include . PATH_SEPARATOR . get_include_path());
// Init PHP_Depend autoloader
include_once 'PHP/Depend/Autoload.php';
$autoload = new PHP_Depend_Autoload();
$autoload->register();
}
/**
* Changes the working directory for a single test.
*
* @param string $localPath The temporary working directory.
*
* @return void
*/
protected static function changeWorkingDirectory($localPath = '')
{
self::$_originalWorkingDirectory = getcwd();
chdir(self::createFileUri($localPath));
}
/**
* Creates a full filename for a test content in the <em>_files</b> directory.
*
* @param string $localPath The local path within the <em>_files</b> dir.
*
* @return string
*/
protected static function createFileUri($localPath = '')
{
return self::$_filesDirectory . '/' . $localPath;
}
/**
* Creates a file uri for a temporary test file.
*
* @return string
*/
protected static function createTempFileUri()
{
return (self::$_tempFiles[] = tempnam(sys_get_temp_dir(), 'phpmd.'));
}
}
/**
* Init the test environment.
*/
PHP_PMD_AbstractTest::init();