Version 10, last updated by gsantini at November 19, 2009 22:51 UTC
How to plug and test examples for your sniffers
Sniffer unit tests follow strict conventions to allow rapid "plug and test" feature.
On the other side you must know the conventions to have your tests work correctly.
Remember sniffs come in standards and are organised in folders (Classes, Commenting, ...).
For what follows, suppose your standard is "MyStandard", your folder is "MyFolder" and your sniffer is "MySniffer".
Use case 1: you want to test one sniff that contains various events.
This is the easiest one. Proceed as follows:
- Add one dummy test file for each event to test:
- in folder CodeSniffer/Standards/MyStandard/Tests/MyFolder/Files/
- name it according to event codes: MyStandard.MY_FIRST_EVENTCODE.inc, MyStandard.MY_SECOND_EVENTCODE.inc
- Add a php class that will test all events (i.e. parse all files):
- name it MyStandard_Tests_MyFolder_MySnifferUnitTest
- make it extends AbstractTaggedSniffUnitTest
- name the file MySnifferUnitTest.php
- put it in folder CodeSniffer/Standards/MyStandard/Tests/MyFolder
- fill the $_expectedEvents property with an array whose keys are the expected events codes and whose values are arrays of kind array($line, $column) where $line and $column are positive numbers representing where events are expected.
{
protected$_expectedEvents=array(
'MY_FIRST_EVENTCODE' =>array(2,1),
'MY_SECOND_EVENTCODE'=>array(9, 1)
);
}
That's it: you've added your test!
Use case 2: more test files for one event type
Proceed like before, but:
- at 1.2, name your files MyStandard.MY_FIRST_EVENTCODE.1.inc, MyStandard.MY_FIRST_EVENTCODE.2.inc, ...
- at 2.5, make values an array of arrays : if you expect event at line 2 column 1 in first file and line 3 column 1 in second, simply put
'MY_FIRST_EVENTCODE'=>array(
array(2, 1),
array(3, 1)
)
);
Use case 3: more test files that must be parsed in a specific order
Proceed like before, but:
- at 1.2, name your files MyStandard.MY_FIRST_EVENTCODE.1.inc, MyStandard.MY_FIRST_EVENTCODE.2.inc, in the meant order: in this case numbers will be considered as file identifiers
- at 2.5, add your files identifiers as keys for the expecetd events array: if you expect events at line 2 column 1 and at line 3 column 1 in first file and at line 5 column 1 in second file, put
'MY_FIRST_EVENTCODE'=>array(
'1' =>array(array(2, 1),array(3,1)),
'2'=> array(5, 1)
)
);