Testing Rules
A rule test is a set of fixtures (files with the code before the fix, the code after it and the findings the
rule should report) plus one line that calls RuleTester. Besides the output and the findings, the tester checks that
the rule is idempotent, that comments survive, that suppression works, and that the rule fixes nothing without reporting it.
Fixtures
Each rule is tested on its own directory of fixtures. A fixture is a group of up to three files with the same name:
basic.codeis the code before the fix;basic.expectedis the code after the fix; when the file is missing, the rule must not change the code;basic.violationsholds the expected reports, each on its own line, as a line number and a message:
3: The message of an exception must end with a period.
6: The message of an exception must end with a period.
A fixture is not an example for the documentation: it should be ugly and full of edge cases. A comment in the middle of a construct, a construct on one line and across three, an empty body, an interpolated string, alternative syntax. These are exactly the places where rules break.
You do not have to copy the .expected and .violations files by hand:
RuleTester::collectOutput() and RuleTester::collectViolations() return them in their exact format from
what the rule does on the fixture, so you have them written out and only check the diff (see below).
The fixture must give a value to the decisions the rule enforces; otherwise they are keep and the rule does
nothing, and the tester then insists that the fixture changes nothing and reports nothing. The values for the whole directory go
into a values.neon file next to the fixtures, written the same way as in the configuration:
acme:
debugCalls: forbidden
In comments at its start, a fixture can add: values just for itself, as JSON layered on top of values.neon; the
PHP version it is written for; the maximum line length to check against; the word risky, which also allows the rule
to make fixes that change the behavior of the code; and the word run, with which the tester runs the code before and
after the fix, and both runs must print the same and exit alike:
<?php
// {"mistakes.debugOutputFunctions": ["var_dump", "dump"]}
// php 8.4
// lineLength 80
// risky
A key is written with its full path. For a rule whose decisions are in a single section, the key without the section is
enough, so {"debugCalls": "keep"} means acme.debugCalls. It also works for a key the rule reads but does
not own, like the engine parameter mistakes.debugOutputFunctions here.
When no length is given, lines are measured against 120 characters, as in the standards. When no version is given, the rule is
tested on the version it asked for in requires, or on PHP 8.0 if it asked for none; a version passed to the tester
through the $phpVersion parameter takes precedence over the header. It is never the version of the interpreter
running the tests, because the verdict of a rule should not depend on the computer.
Without risky, a risky occurrence is only reported, and the .expected file must leave it unchanged.
With risky, the rule fixes it, and if an allowed risky fix is left undone after the run, the fixture fails. The
report of a risky fix in the .violations file is followed by an indented line that names what would decide the risk,
plus the reason if the rule gave one, so the tester also checks the cause of the risk:
4: The loop must be written with `array_any()`.
risky TypeUnknown: the loop may go through an object, which `array_any()` does not take
Headers tell what namespaces outside the fixture declare. They are written like the items of a use statement, just
like the keys namespaces and
nameResolution in the configuration:
<?php
// namespacedFunctions App\helper, App\Utils\{format}
// namespacedConstants App\LIMIT
// nameResolution certain
A rule gets the types of the code from the PHPStan installed in the project in which the tests run, computed on the fixture
and on the declarations from the stubs/ subdirectory of the fixture directory. It gets them in two cases:
- a rule with
typesRequiredalways, and the header// types offin its fixture is an error; - a rule that only benefits from types where a
stubs/directory exists and the fixture has no// types offheader. A fixture with this header tests what the rule recognizes without types, only from the declarations it can see.
RuleTester
use DressCode\Testing\RuleTester;
use Tester\Assert;
Assert::noError(fn() => RuleTester::run(ExceptionMessagePeriodRule::class, __DIR__ . '/fixtures/exceptionMessagePeriod'));
The run() method goes through all *.code files in the directory and returns their count; a directory
without them is a failure, not an empty success. A failure is reported as the exception
DressCode\Testing\TestFailure with the name of the fixture and a diff, so every test framework shows it clearly.
Nette Tester wants at least one assertion in every test, which is why the call in the example is wrapped in
Assert::noError(); with PHPUnit, it is a single call in a test method.
For every fixture, the tester checks:
- the output equals the
.expectedfile (or the input, when there is no.expected); - the reports equal the
.violationsfile, line by line and in the same order, and the message of each of them ends with a period; - idempotence: running the rule again on its own output changes nothing;
- comments: the output contains all comments from the input, unless the rule has
modifiesComments; - suppression: with a
dresscode:ignoreFilecomment in the header, the rule reports nothing and changes nothing; - the contract of fixes: no change of the tree without a successful report, no report under a decision the rule did not
declare, no report without
fixable: falsethat is still there after a pass that changed nothing, and no risky violation left in a fixture with// risky, where the fix was allowed; - the rest: what the rule reports in the last pass is exactly what a fresh run reports on the output;
- the tree: every node has the correct parent, which is what a wrong insertion breaks.
If a rule needs something in its constructor, pass a factory fn(array $values): Rule instead of its class. The
factory gets the values from the header of the fixture as they are written in the JSON, or an empty array when there is no header,
and returns the finished rule; with a factory, the tester does not call configure() and does not check the reports
against the values of the decisions. A rule that asks for its plugin's own analysis (here ClockRule asks for the
Clock analysis, which the engine cannot build on its own) gets its factory through the analyses
parameter, in the same shape as the analyses key of the configuration and of the plugin manifest:
RuleTester::run(ClockRule::class, __DIR__ . '/fixtures/clock', analyses: [
Clock::class => fn(FileNode $file, string $path) => new Clock('noon'),
]);
For special cases there are smaller tools: RuleTester::runFixture() runs a single fixture,
RuleTester::check() checks a finished instance of a rule on a string without files (useful for a quick reproduction),
RuleTester::collectViolations() returns the reports for a fixture already in the format of a .violations
file, and collectOutput() returns the output in the format of an .expected file. run(),
runFixture() and both collect*() methods accept $phpVersion and analyses. The
check() method also accepts the whole style used to process the code
(style: new Style(indent: ' ', maxLineLength: 80)) instead of the maximum line length from the header.
Data for Upgrading Libraries
A package that supplies upgrade data instead of rules, or next to
them, tests the data with the Testing\UpgradingTester class: it checks the data files against the installed library
and fixes a sample of code in the old API the way a project would. The page Replacement Maps describes it.
A Test on Real Code
A rule test checks the rule on its own. Only a run on real code shows how it behaves together with the other rules. Running
dresscode check --strict-rules turns every broken contract into an error instead of a warning, and
--jobs 1 keeps everything in a single process, which is easy to debug.
Before you publish a rule, run fix on a large amount of someone else's code, for example on the
vendor/ directory, and go through the diff. The tester checks idempotence and comments, but not taste.