Skip to content

Instantly share code, notes, and snippets.

@masak
Created March 15, 2012 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masak/2047217 to your computer and use it in GitHub Desktop.
Save masak/2047217 to your computer and use it in GitHub Desktop.
developing a grammar with tests
use Test;
grammar cityTaxData {
regex TOP { ^$ }
}
ok cityTaxData.parse('Agoura Hills* 8.750% Los Angeles');
done;
# Run this. See the test fail.
use Test;
grammar cityTaxData {
regex TOP { ^ (\w+ [\h+ \w+]*) '*'? \h+ (\d+\.\d+\%) \h+ (\w+ [\h+ \w+]*) $ }
}
ok cityTaxData.parse('Agoura Hills* 8.750% Los Angeles');
done;
# Test passes now. Time to refactor into parts.
use Test;
grammar cityTaxData {
regex TOP { ^ <city> \h+ <taxrate> \h+ <county> $ }
regex city { \w+ [\h+ \w+]* '*'? }
regex taxrate { \d+\.\d+\% }
regex county { \w+ [\h+ \w+]* }
}
ok cityTaxData.parse('Agoura Hills* 8.750% Los Angeles');
# Yay, still passes! Time to add another test:
ok cityTaxData.parse('Alberhill (Lake Elsinore*) 7.750% Riverside');
# This fails, of course. Time to extend the grammar to handle it.
done;
use Test;
grammar cityTaxData {
regex TOP { ^ <city> \h+ <taxrate> \h+ <county> $ }
regex city { \w+ [\h+ \w+]* '*'? [\h+ <parens>]? }
regex parens { '(' \w+ [\h+ \w+] '*'? ')' }
regex taxrate { \d+\.\d+\% }
regex county { \w+ [\h+ \w+]* }
}
ok cityTaxData.parse('Agoura Hills* 8.750% Los Angeles');
ok cityTaxData.parse('Alberhill (Lake Elsinore*) 7.750% Riverside');
done;
# Yup, this did it.
# Important take-away: each time I either add a new failing test, or change
# code around and run the tests again. The objective is to make the latest
# added failing test pass without failing any of the other tests. The
# totality of the test suite assures that I don't regress on things the
# grammar could do at some point.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment