/
ProjectCodeTest.php
486 lines (421 loc) · 15.6 KB
/
ProjectCodeTest.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
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Tests\AutoReview;
if (!class_exists(\PHPUnit\Runner\Version::class)) {
class_alias('PHPUnit_Runner_Version', \PHPUnit\Runner\Version::class);
}
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @coversNothing
* @group auto-review
* @group covers-nothing
*/
final class ProjectCodeTest extends TestCase
{
/**
* This structure contains older classes that are not yet covered by tests.
*
* It may only shrink, never add anything to it.
*
* @var string[]
*/
private static $classesWithoutTests = [
\PhpCsFixer\Console\SelfUpdate\GithubClient::class,
\PhpCsFixer\Doctrine\Annotation\Tokens::class,
\PhpCsFixer\Fixer\Operator\AlignDoubleArrowFixerHelper::class,
\PhpCsFixer\Fixer\Operator\AlignEqualsFixerHelper::class,
\PhpCsFixer\Fixer\Whitespace\NoExtraConsecutiveBlankLinesFixer::class,
\PhpCsFixer\Runner\FileCachingLintingIterator::class,
\PhpCsFixer\Runner\FileLintingIterator::class,
\PhpCsFixer\Test\AccessibleObject::class,
];
public function testThatClassesWithoutTestsVarIsProper()
{
$unknownClasses = array_filter(
self::$classesWithoutTests,
static function ($class) { return !class_exists($class) && !trait_exists($class); }
);
$this->assertSame([], $unknownClasses);
}
/**
* @param string $className
*
* @dataProvider provideSrcConcreteClassCases
*/
public function testThatSrcClassHaveTestClass($className)
{
$testClassName = str_replace('PhpCsFixer', 'PhpCsFixer\\Tests', $className).'Test';
if (\in_array($className, self::$classesWithoutTests, true)) {
$this->assertFalse(class_exists($testClassName), sprintf('Class "%s" already has tests, so it should be removed from "%s::$classesWithoutTests".', $className, __CLASS__));
$this->markTestIncomplete(sprintf('Class "%s" has no tests yet, please help and add it.', $className));
}
$this->assertTrue(class_exists($testClassName), sprintf('Expected test class "%s" for "%s" not found.', $testClassName, $className));
$this->assertTrue(is_subclass_of($testClassName, TestCase::class), sprintf('Expected test class "%s" to be a subclass of "\PhpCsFixer\Tests\TestCase".', $testClassName));
}
/**
* @param string $className
*
* @dataProvider provideSrcClassesNotAbuseInterfacesCases
*/
public function testThatSrcClassesNotAbuseInterfaces($className)
{
$rc = new \ReflectionClass($className);
$allowedMethods = array_map(
function (\ReflectionClass $interface) {
return $this->getPublicMethodNames($interface);
},
$rc->getInterfaces()
);
if (\count($allowedMethods)) {
$allowedMethods = array_unique(array_merge(...array_values($allowedMethods)));
}
$allowedMethods[] = '__construct';
$allowedMethods[] = '__destruct';
$allowedMethods[] = '__wakeup';
$exceptionMethods = [
'configure', // due to AbstractFixer::configure
'getConfigurationDefinition', // due to AbstractFixer::getConfigurationDefinition
'getDefaultConfiguration', // due to AbstractFixer::getDefaultConfiguration
'setWhitespacesConfig', // due to AbstractFixer::setWhitespacesConfig
];
// @TODO: 3.0 should be removed
$exceptionMethodsPerClass = [
\PhpCsFixer\Config::class => ['create'],
\PhpCsFixer\Fixer\FunctionNotation\MethodArgumentSpaceFixer::class => ['fixSpace'],
];
$definedMethods = $this->getPublicMethodNames($rc);
$extraMethods = array_diff(
$definedMethods,
$allowedMethods,
$exceptionMethods,
isset($exceptionMethodsPerClass[$className]) ? $exceptionMethodsPerClass[$className] : []
);
sort($extraMethods);
$this->assertEmpty(
$extraMethods,
sprintf(
"Class '%s' should not have public methods that are not part of implemented interfaces.\nViolations:\n%s",
$className,
implode("\n", array_map(static function ($item) {
return " * ${item}";
}, $extraMethods))
)
);
}
/**
* @param string $className
*
* @dataProvider provideSrcClassCases
*/
public function testThatSrcClassesNotExposeProperties($className)
{
$rc = new \ReflectionClass($className);
if (\PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer::class === $className) {
$this->markTestIncomplete(sprintf(
'Public properties of fixer `%s` will be removed on 3.0.',
\PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer::class
));
}
$this->assertEmpty(
$rc->getProperties(\ReflectionProperty::IS_PUBLIC),
sprintf('Class \'%s\' should not have public properties.', $className)
);
if ($rc->isFinal()) {
return;
}
$allowedProps = [];
$definedProps = $rc->getProperties(\ReflectionProperty::IS_PROTECTED);
if (false !== $rc->getParentClass()) {
$allowedProps = $rc->getParentClass()->getProperties(\ReflectionProperty::IS_PROTECTED);
}
$allowedProps = array_map(static function (\ReflectionProperty $item) {
return $item->getName();
}, $allowedProps);
$definedProps = array_map(static function (\ReflectionProperty $item) {
return $item->getName();
}, $definedProps);
$exceptionPropsPerClass = [
\PhpCsFixer\AbstractPhpdocTypesFixer::class => ['tags'],
\PhpCsFixer\AbstractAlignFixerHelper::class => ['deepestLevel'],
\PhpCsFixer\AbstractFixer::class => ['configuration', 'configurationDefinition', 'whitespacesConfig'],
\PhpCsFixer\AbstractProxyFixer::class => ['proxyFixers'],
\PhpCsFixer\Test\AbstractFixerTestCase::class => ['fixer', 'linter'],
\PhpCsFixer\Test\AbstractIntegrationTestCase::class => ['linter'],
];
$extraProps = array_diff(
$definedProps,
$allowedProps,
isset($exceptionPropsPerClass[$className]) ? $exceptionPropsPerClass[$className] : []
);
sort($extraProps);
$this->assertEmpty(
$extraProps,
sprintf(
"Class '%s' should not have protected properties.\nViolations:\n%s",
$className,
implode("\n", array_map(static function ($item) {
return " * ${item}";
}, $extraProps))
)
);
}
/**
* @param string $className
*
* @dataProvider provideTestClassCases
*/
public function testThatTestClassesAreTraitOrAbstractOrFinal($className)
{
$rc = new \ReflectionClass($className);
$this->assertTrue(
$rc->isTrait() || $rc->isAbstract() || $rc->isFinal(),
sprintf('Test class %s should be trait, abstract or final.', $className)
);
}
/**
* @param string $className
*
* @dataProvider provideTestClassCases
*/
public function testThatTestClassesAreInternal($className)
{
$rc = new \ReflectionClass($className);
$doc = new DocBlock($rc->getDocComment());
$this->assertNotEmpty(
$doc->getAnnotationsOfType('internal'),
sprintf('Test class %s should have internal annotation.', $className)
);
}
/**
* @dataProvider provideTestClassCases
*
* @param string $testClassName
*/
public function testThatDataProvidersAreCorrectlyNamed($testClassName)
{
$dataProviderMethodNames = $this->getDataProviderMethodNames($testClassName);
if (empty($dataProviderMethodNames)) {
$this->addToAssertionCount(1); // no data providers to test, all good!
}
foreach ($dataProviderMethodNames as $dataProviderMethodName) {
$this->assertRegExp('/^provide[A-Z]\S+Cases$/', $dataProviderMethodName, sprintf(
'Data provider in "%s" with name "%s" is not correctly named.',
$testClassName,
$dataProviderMethodName
));
}
}
/**
* @dataProvider provideClassesWherePregFunctionsAreForbiddenCases
*
* @param string $className
*/
public function testThereIsNoPregFunctionUsedDirectly($className)
{
$rc = new \ReflectionClass($className);
$tokens = Tokens::fromCode(file_get_contents($rc->getFileName()));
$stringTokens = array_filter(
$tokens->toArray(),
function (Token $token) {
return $token->isGivenKind(T_STRING);
}
);
$strings = array_map(
function (Token $token) {
return $token->getContent();
},
$stringTokens
);
$strings = array_unique($strings);
$message = sprintf('Class %s must not use preg_*, it shall use Preg::* instead.', $className);
$this->assertNotContains('preg_filter', $strings, $message);
$this->assertNotContains('preg_grep', $strings, $message);
$this->assertNotContains('preg_match', $strings, $message);
$this->assertNotContains('preg_match_all', $strings, $message);
$this->assertNotContains('preg_replace', $strings, $message);
$this->assertNotContains('preg_replace_callback', $strings, $message);
$this->assertNotContains('preg_split', $strings, $message);
}
public function provideSrcClassCases()
{
return array_map(
static function ($item) {
return [$item];
},
$this->getSrcClasses()
);
}
public function provideSrcClassesNotAbuseInterfacesCases()
{
return array_map(
static function ($item) {
return [$item];
},
array_filter($this->getSrcClasses(), static function ($className) {
$rc = new \ReflectionClass($className);
$doc = false !== $rc->getDocComment()
? new DocBlock($rc->getDocComment())
: null;
if (
$rc->isInterface()
|| ($doc && \count($doc->getAnnotationsOfType('internal')))
|| 0 === \count($rc->getInterfaces())
|| \in_array($className, [
\PhpCsFixer\Finder::class,
\PhpCsFixer\Test\AbstractFixerTestCase::class,
\PhpCsFixer\Test\AbstractIntegrationTestCase::class,
\PhpCsFixer\Tests\Test\AbstractFixerTestCase::class,
\PhpCsFixer\Tests\Test\AbstractIntegrationTestCase::class,
\PhpCsFixer\Tokenizer\Tokens::class,
], true)
) {
return false;
}
return true;
})
);
}
public function provideSrcConcreteClassCases()
{
return array_map(
static function ($item) { return [$item]; },
array_filter(
$this->getSrcClasses(),
static function ($className) {
$rc = new \ReflectionClass($className);
return !$rc->isAbstract() && !$rc->isInterface();
}
)
);
}
public function provideTestClassCases()
{
return array_map(
static function ($item) {
return [$item];
},
$this->getTestClasses()
);
}
public function provideClassesWherePregFunctionsAreForbiddenCases()
{
return array_map(
function ($item) {
return [$item];
},
array_filter(
$this->getSrcClasses(),
function ($className) {
return 'PhpCsFixer\\Preg' !== $className;
}
)
);
}
private function getDataProviderMethodNames($testClassName)
{
$dataProviderMethodNames = [];
$tokens = Tokens::fromCode(file_get_contents(
str_replace('\\', \DIRECTORY_SEPARATOR, preg_replace('#^PhpCsFixer\\\Tests#', 'tests', $testClassName)).'.php'
));
foreach ($tokens as $token) {
if ($token->isGivenKind(T_DOC_COMMENT)) {
$docBlock = new DocBlock($token->getContent());
$dataProviderAnnotations = $docBlock->getAnnotationsOfType('dataProvider');
foreach ($dataProviderAnnotations as $dataProviderAnnotation) {
if (1 === preg_match('/@dataProvider\s+(?P<methodName>\w+)/', $dataProviderAnnotation->getContent(), $matches)) {
$dataProviderMethodNames[] = $matches['methodName'];
}
}
}
}
return array_unique($dataProviderMethodNames);
}
private function getSrcClasses()
{
static $classes;
if (null !== $classes) {
return $classes;
}
$finder = Finder::create()
->files()
->name('*.php')
->in(__DIR__.'/../../src')
->exclude([
'Resources',
])
;
$classes = array_map(
static function (SplFileInfo $file) {
return sprintf(
'%s\\%s%s%s',
'PhpCsFixer',
strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
$file->getRelativePath() ? '\\' : '',
$file->getBasename('.'.$file->getExtension())
);
},
iterator_to_array($finder, false)
);
sort($classes);
return $classes;
}
private function getTestClasses()
{
static $classes;
if (null !== $classes) {
return $classes;
}
$finder = Finder::create()
->files()
->name('*.php')
->in(__DIR__.'/..')
->exclude([
'Fixtures',
])
;
$classes = array_map(
static function (SplFileInfo $file) {
return sprintf(
'PhpCsFixer\\Tests\\%s%s%s',
strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
$file->getRelativePath() ? '\\' : '',
$file->getBasename('.'.$file->getExtension())
);
},
iterator_to_array($finder, false)
);
sort($classes);
return $classes;
}
/**
* @param \ReflectionClass $rc
*
* @return string[]
*/
private function getPublicMethodNames(\ReflectionClass $rc)
{
return array_map(
static function (\ReflectionMethod $rm) {
return $rm->getName();
},
$rc->getMethods(\ReflectionMethod::IS_PUBLIC)
);
}
}