Skip to content

Commit f607f3c

Browse files
authored
Merge pull request #996 from PHPCSStandards/phpcs-4.0/feature/test-code-should-be-in-tests
Ruleset: remove test specific code
2 parents 7bc2ff3 + 25b6b69 commit f607f3c

File tree

9 files changed

+88
-148
lines changed

9 files changed

+88
-148
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@
88
composer.lock
99
phpstan.neon
1010
/node_modules/
11+
/tests/Standards/sniffStnd.xml

src/Ruleset.php

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -201,22 +201,6 @@ public function __construct(Config $config)
201201
Autoload::addSearchPath(dirname($standard), $namespace);
202202
}
203203

204-
if (defined('PHP_CODESNIFFER_IN_TESTS') === true && empty($restrictions) === false) {
205-
// In unit tests, only register the sniffs that the test wants and not the entire standard.
206-
foreach ($restrictions as $restriction) {
207-
$sniffs = array_merge($sniffs, $this->expandRulesetReference($restriction, dirname($standard)));
208-
}
209-
210-
if (empty($sniffs) === true) {
211-
// Sniff reference could not be expanded, which probably means this
212-
// is an installed standard. Let the unit test system take care of
213-
// setting the correct sniff for testing.
214-
return;
215-
}
216-
217-
break;
218-
}
219-
220204
if (PHP_CODESNIFFER_VERBOSITY === 1) {
221205
echo "Registering sniffs in the $standardName standard... ";
222206
if (count($config->standards) > 1 || PHP_CODESNIFFER_VERBOSITY > 2) {

tests/Core/Generators/GeneratorTest.php

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -194,16 +194,6 @@ public function testGetTitleFallbackToFilename()
194194
$config = new ConfigDouble(["--standard=$standard", "--sniffs=$sniffs"]);
195195
$ruleset = new Ruleset($config);
196196

197-
// In tests, the `--sniffs` setting doesn't work out of the box.
198-
$sniffParts = explode('.', $sniffs);
199-
$sniffFile = __DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.$sniffParts[0].DIRECTORY_SEPARATOR;
200-
$sniffFile .= 'Sniffs'.DIRECTORY_SEPARATOR.$sniffParts[1].DIRECTORY_SEPARATOR.$sniffParts[2].'Sniff.php';
201-
202-
$sniffParts = array_map('strtolower', $sniffParts);
203-
$sniffName = $sniffParts[0].'\sniffs\\'.$sniffParts[1].'\\'.$sniffParts[2].'sniff';
204-
$restrictions = [$sniffName => true];
205-
$ruleset->registerSniffs([$sniffFile], $restrictions, []);
206-
207197
// Make the test OS independent.
208198
$this->expectOutputString('Documentation Title PCRE Fallback'.PHP_EOL);
209199

tests/Core/Generators/HTMLTest.php

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -94,16 +94,6 @@ public function testDocSpecifics($sniffs, $pathToExpected)
9494
$config = new ConfigDouble(["--standard=$standard", "--sniffs=$sniffs"]);
9595
$ruleset = new Ruleset($config);
9696

97-
// In tests, the `--sniffs` setting doesn't work out of the box.
98-
$sniffParts = explode('.', $sniffs);
99-
$sniffFile = __DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.$sniffParts[0].DIRECTORY_SEPARATOR;
100-
$sniffFile .= 'Sniffs'.DIRECTORY_SEPARATOR.$sniffParts[1].DIRECTORY_SEPARATOR.$sniffParts[2].'Sniff.php';
101-
102-
$sniffParts = array_map('strtolower', $sniffParts);
103-
$sniffName = $sniffParts[0].'\sniffs\\'.$sniffParts[1].'\\'.$sniffParts[2].'sniff';
104-
$restrictions = [$sniffName => true];
105-
$ruleset->registerSniffs([$sniffFile], $restrictions, []);
106-
10797
$expected = file_get_contents($pathToExpected);
10898
$this->assertNotFalse($expected, 'Output expectation file could not be found');
10999

tests/Core/Generators/MarkdownTest.php

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -94,16 +94,6 @@ public function testDocSpecifics($sniffs, $pathToExpected)
9494
$config = new ConfigDouble(["--standard=$standard", "--sniffs=$sniffs"]);
9595
$ruleset = new Ruleset($config);
9696

97-
// In tests, the `--sniffs` setting doesn't work out of the box.
98-
$sniffParts = explode('.', $sniffs);
99-
$sniffFile = __DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.$sniffParts[0].DIRECTORY_SEPARATOR;
100-
$sniffFile .= 'Sniffs'.DIRECTORY_SEPARATOR.$sniffParts[1].DIRECTORY_SEPARATOR.$sniffParts[2].'Sniff.php';
101-
102-
$sniffParts = array_map('strtolower', $sniffParts);
103-
$sniffName = $sniffParts[0].'\sniffs\\'.$sniffParts[1].'\\'.$sniffParts[2].'sniff';
104-
$restrictions = [$sniffName => true];
105-
$ruleset->registerSniffs([$sniffFile], $restrictions, []);
106-
10797
$expected = file_get_contents($pathToExpected);
10898
$this->assertNotFalse($expected, 'Output expectation file could not be found');
10999

tests/Core/Generators/TextTest.php

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -94,16 +94,6 @@ public function testDocSpecifics($sniffs, $pathToExpected)
9494
$config = new ConfigDouble(["--standard=$standard", "--sniffs=$sniffs"]);
9595
$ruleset = new Ruleset($config);
9696

97-
// In tests, the `--sniffs` setting doesn't work out of the box.
98-
$sniffParts = explode('.', $sniffs);
99-
$sniffFile = __DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.$sniffParts[0].DIRECTORY_SEPARATOR;
100-
$sniffFile .= 'Sniffs'.DIRECTORY_SEPARATOR.$sniffParts[1].DIRECTORY_SEPARATOR.$sniffParts[2].'Sniff.php';
101-
102-
$sniffParts = array_map('strtolower', $sniffParts);
103-
$sniffName = $sniffParts[0].'\sniffs\\'.$sniffParts[1].'\\'.$sniffParts[2].'sniff';
104-
$restrictions = [$sniffName => true];
105-
$ruleset->registerSniffs([$sniffFile], $restrictions, []);
106-
10797
$expected = file_get_contents($pathToExpected);
10898
$this->assertNotFalse($expected, 'Output expectation file could not be found');
10999

tests/Core/Ruleset/RegisterSniffsTest.php

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -140,28 +140,28 @@ public function testRegisteredSniffsShouldBeTheSame()
140140
/**
141141
* Test that if only specific sniffs are requested, only those are registered.
142142
*
143-
* {@internal Can't test this via the CLI arguments due to some code in the Ruleset class
144-
* related to sniff tests.}
145-
*
146143
* @return void
147144
*/
148145
public function testRegisteredSniffsWithRestrictions()
149146
{
150-
$restrictions = [
151-
'psr1\\sniffs\\classes\\classdeclarationsniff' => true,
152-
'psr1\\sniffs\\files\\sideeffectssniff' => true,
153-
'psr1\\sniffs\\methods\\camelcapsmethodnamesniff' => true,
147+
// Set up the ruleset.
148+
$args = [
149+
'--standard=PSR1',
150+
'--sniffs=PSR1.Classes.ClassDeclaration,PSR1.Files.SideEffects,PSR1.Methods.CamelCapsMethodName',
154151
];
152+
$config = new ConfigDouble($args);
153+
$ruleset = new Ruleset($config);
155154

156155
$expected = [
157156
'PHP_CodeSniffer\\Standards\\PSR1\\Sniffs\\Classes\\ClassDeclarationSniff',
158157
'PHP_CodeSniffer\\Standards\\PSR1\\Sniffs\\Files\\SideEffectsSniff',
159158
'PHP_CodeSniffer\\Standards\\PSR1\\Sniffs\\Methods\\CamelCapsMethodNameSniff',
160159
];
161160

162-
self::$ruleset->registerSniffs(self::$psr1SniffAbsolutePaths, $restrictions, []);
161+
$actual = array_keys($ruleset->sniffs);
162+
sort($actual);
163163

164-
$this->assertSame($expected, array_keys(self::$ruleset->sniffs));
164+
$this->assertSame($expected, $actual);
165165

166166
}//end testRegisteredSniffsWithRestrictions()
167167

tests/Core/Ruleset/ShowSniffDeprecationsTest.php

Lines changed: 14 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -169,35 +169,13 @@ public static function dataDeprecatedSniffsListDoesNotShowNeedsCsMode()
169169
public function testDeprecatedSniffsListDoesNotShowWhenSelectedSniffsAreNotDeprecated()
170170
{
171171
$standard = __DIR__.'/ShowSniffDeprecationsTest.xml';
172-
$config = new ConfigDouble(['.', "--standard=$standard"]);
173-
$ruleset = new Ruleset($config);
174-
175-
/*
176-
* Apply sniff restrictions.
177-
* For tests we need to manually trigger this if the standard is "installed", like with the fixtures these tests use.
178-
*/
179-
180-
$restrictions = [];
181-
$sniffs = [
182-
'TestStandard.SetProperty.AllowedAsDeclared',
183-
'TestStandard.SetProperty.AllowedViaStdClass',
172+
$cliArgs = [
173+
'.',
174+
"--standard=$standard",
175+
'--sniffs=TestStandard.SetProperty.AllowedAsDeclared,TestStandard.SetProperty.AllowedViaStdClass',
184176
];
185-
foreach ($sniffs as $sniffCode) {
186-
$parts = explode('.', strtolower($sniffCode));
187-
$sniffName = $parts[0].'\\sniffs\\'.$parts[1].'\\'.$parts[2].'sniff';
188-
$restrictions[strtolower($sniffName)] = true;
189-
}
190-
191-
$sniffFiles = [];
192-
$allSniffs = $ruleset->sniffCodes;
193-
foreach ($allSniffs as $sniffName) {
194-
$sniffFile = str_replace('\\', DIRECTORY_SEPARATOR, $sniffName);
195-
$sniffFile = __DIR__.DIRECTORY_SEPARATOR.$sniffFile.'.php';
196-
$sniffFiles[] = $sniffFile;
197-
}
198-
199-
$ruleset->registerSniffs($sniffFiles, $restrictions, []);
200-
$ruleset->populateTokenListeners();
177+
$config = new ConfigDouble($cliArgs);
178+
$ruleset = new Ruleset($config);
201179

202180
$this->expectOutputString('');
203181

@@ -215,38 +193,20 @@ public function testDeprecatedSniffsListDoesNotShowWhenSelectedSniffsAreNotDepre
215193
public function testDeprecatedSniffsListDoesNotShowWhenAllDeprecatedSniffsAreExcluded()
216194
{
217195
$standard = __DIR__.'/ShowSniffDeprecationsTest.xml';
218-
$config = new ConfigDouble(['.', "--standard=$standard"]);
219-
$ruleset = new Ruleset($config);
220-
221-
/*
222-
* Apply sniff restrictions.
223-
* For tests we need to manually trigger this if the standard is "installed", like with the fixtures these tests use.
224-
*/
225-
226-
$exclusions = [];
227-
$exclude = [
196+
$exclude = [
228197
'TestStandard.Deprecated.WithLongReplacement',
229198
'TestStandard.Deprecated.WithoutReplacement',
230199
'TestStandard.Deprecated.WithReplacement',
231200
'TestStandard.Deprecated.WithReplacementContainingLinuxNewlines',
232201
'TestStandard.Deprecated.WithReplacementContainingNewlines',
233202
];
234-
foreach ($exclude as $sniffCode) {
235-
$parts = explode('.', strtolower($sniffCode));
236-
$sniffName = $parts[0].'\\sniffs\\'.$parts[1].'\\'.$parts[2].'sniff';
237-
$exclusions[strtolower($sniffName)] = true;
238-
}
239-
240-
$sniffFiles = [];
241-
$allSniffs = $ruleset->sniffCodes;
242-
foreach ($allSniffs as $sniffName) {
243-
$sniffFile = str_replace('\\', DIRECTORY_SEPARATOR, $sniffName);
244-
$sniffFile = __DIR__.DIRECTORY_SEPARATOR.$sniffFile.'.php';
245-
$sniffFiles[] = $sniffFile;
246-
}
247-
248-
$ruleset->registerSniffs($sniffFiles, [], $exclusions);
249-
$ruleset->populateTokenListeners();
203+
$cliArgs = [
204+
'.',
205+
"--standard=$standard",
206+
'--exclude='.implode(',', $exclude),
207+
];
208+
$config = new ConfigDouble($cliArgs);
209+
$ruleset = new Ruleset($config);
250210

251211
$this->expectOutputString('');
252212

tests/Standards/AbstractSniffUnitTest.php

Lines changed: 64 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,43 @@ abstract class AbstractSniffUnitTest extends TestCase
2626
{
2727

2828
/**
29-
* Cache for the Config object.
29+
* Ruleset template with placeholders.
3030
*
31-
* @var \PHP_CodeSniffer\Tests\ConfigDouble
31+
* @var string
3232
*/
33-
private static $config;
33+
private const RULESET_TEMPLATE = <<<'TEMPLATE'
34+
<?xml version="1.0"?>
35+
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="[STANDARDNAME]" xsi:noNamespaceSchemaLocation="../../phpcs.xsd">
36+
<description>Temporary ruleset used by the AbstractSniffUnitTest class.</description>
37+
38+
<rule ref="[SNIFFFILEREF]"/>
39+
40+
</ruleset>
41+
TEMPLATE;
42+
43+
/**
44+
* Placeholders used in the ruleset template which need to be replaced.
45+
*
46+
* @var array<string>
47+
*/
48+
private const SEARCH_FOR = [
49+
'[STANDARDNAME]',
50+
'[SNIFFFILEREF]',
51+
];
52+
53+
/**
54+
* Location where the temporary ruleset file will be saved.
55+
*
56+
* @var string
57+
*/
58+
private const RULESET_FILENAME = __DIR__.'/sniffStnd.xml';
3459

3560
/**
36-
* Cache for Ruleset objects.
61+
* Cache for the Config object.
3762
*
38-
* @var array<string, \PHP_CodeSniffer\Ruleset>
63+
* @var \PHP_CodeSniffer\Tests\ConfigDouble
3964
*/
40-
private static $rulesets = [];
65+
private static $config;
4166

4267
/**
4368
* Extensions to disregard when gathering the test files.
@@ -52,6 +77,18 @@ abstract class AbstractSniffUnitTest extends TestCase
5277
];
5378

5479

80+
/**
81+
* Clean up temporary ruleset file.
82+
*
83+
* @return void
84+
*/
85+
public static function tearDownAfterClass(): void
86+
{
87+
@unlink(self::RULESET_FILENAME);
88+
89+
}//end tearDownAfterClass()
90+
91+
5592
/**
5693
* Get a list of all test files to check.
5794
*
@@ -103,7 +140,8 @@ protected function shouldSkipTest()
103140
* Tests the extending classes Sniff class.
104141
*
105142
* @return void
106-
* @throws \PHPUnit\Framework\Exception
143+
*
144+
* @throws \PHP_CodeSniffer\Exceptions\RuntimeException
107145
*/
108146
final public function testSniff()
109147
{
@@ -122,6 +160,23 @@ final public function testSniff()
122160
// Get a list of all test files to check.
123161
$testFiles = $this->getTestFiles($testFileBase);
124162

163+
$sniffFile = preg_replace('`[/\\\\]Tests[/\\\\]`', DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR, $testFileBase);
164+
$sniffFile = str_replace('UnitTest.', 'Sniff.php', $sniffFile);
165+
166+
if (file_exists($sniffFile) === false) {
167+
$this->fail(sprintf('ERROR: Sniff file %s for test %s does not appear to exist', $sniffFile, static::class));
168+
}
169+
170+
$replacements = [
171+
$standardName,
172+
$sniffFile,
173+
];
174+
$rulesetContents = str_replace(self::SEARCH_FOR, $replacements, self::RULESET_TEMPLATE);
175+
176+
if (file_put_contents(self::RULESET_FILENAME, $rulesetContents) === false) {
177+
throw new RuntimeException('Failed to write custom ruleset file');
178+
}
179+
125180
if (isset(self::$config) === true) {
126181
$config = self::$config;
127182
} else {
@@ -130,31 +185,11 @@ final public function testSniff()
130185
self::$config = $config;
131186
}
132187

133-
$config->standards = [$standardName];
188+
$config->standards = [self::RULESET_FILENAME];
134189
$config->sniffs = [$sniffCode];
135190
$config->ignored = [];
136191

137-
if (isset(self::$rulesets[$standardName]) === false) {
138-
$ruleset = new Ruleset($config);
139-
self::$rulesets[$standardName] = $ruleset;
140-
}
141-
142-
$ruleset = self::$rulesets[$standardName];
143-
144-
$sniffFile = preg_replace('`[/\\\\]Tests[/\\\\]`', DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR, $testFileBase);
145-
$sniffFile = str_replace('UnitTest.', 'Sniff.php', $sniffFile);
146-
147-
if (file_exists($sniffFile) === false) {
148-
$this->fail(sprintf('ERROR: Sniff file %s for test %s does not appear to exist', $sniffFile, static::class));
149-
}
150-
151-
$sniffClassName = substr(get_class($this), 0, -8).'Sniff';
152-
$sniffClassName = str_replace('\Tests\\', '\Sniffs\\', $sniffClassName);
153-
$sniffClassName = Common::cleanSniffClass($sniffClassName);
154-
155-
$restrictions = [strtolower($sniffClassName) => true];
156-
$ruleset->registerSniffs([$sniffFile], $restrictions, []);
157-
$ruleset->populateTokenListeners();
192+
$ruleset = new Ruleset($config);
158193

159194
$failureMessages = [];
160195
foreach ($testFiles as $testFile) {

0 commit comments

Comments
 (0)