package scanner; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import org.junit.Test; import scanner.Token.Type; import testutils.TestUtilities; public class LispScannerTypeTester { @Test public void givenEmptyFile_returnsCorrectTokenTypes() throws IOException { String input = ""; Token.Type[] expectedTypes = {}; assertTokenTypesMatch(input, expectedTypes); } @Test public void givenNil_returnsCorrectTokenTypes() throws IOException { String input = "()"; Token.Type[] expectedTypes = { Type.LEFT_PAREN, Type.RIGHT_PAREN }; assertTokenTypesMatch(input, expectedTypes); } @Test public void givenListOfNumbers_returnsCorrectTokenTypes() throws IOException { String input = "(1 2)"; Token.Type[] expectedTypes = { Type.LEFT_PAREN, Type.NUMBER, Type.NUMBER, Type.RIGHT_PAREN }; assertTokenTypesMatch(input, expectedTypes); } @Test public void givenString_returnsCorrectTokenTypes() throws IOException { String input = "\"string\""; Token.Type[] expectedTypes = { Type.STRING }; assertTokenTypesMatch(input, expectedTypes); } @Test public void givenStringWithEscapedDoubleQuote_returnsCorrectTokenTypes() throws IOException { String input = "\"string \n hi \\\" bye\""; Token.Type[] expectedTypes = { Type.STRING }; assertTokenTypesMatch(input, expectedTypes); } @Test public void givenStringWithEscapedDoubleQuoteAndComment_returnsCorrectTokenTypes() throws IOException { String input = "\"string \n hi \\\" ; bye\""; Token.Type[] expectedTypes = { Type.STRING }; assertTokenTypesMatch(input, expectedTypes); } @Test public void givenIdentifier_returnsCorrectTokenTypes() throws IOException { String input = "abcdefgHIJKLMNOP1234"; Token.Type[] expectedTypes = { Type.IDENTIFIER }; assertTokenTypesMatch(input, expectedTypes); } @Test public void givenQuote_returnsCorrectTokenTypes() throws IOException { String input = "'"; Token.Type[] expectedTypes = { Type.QUOTE_MARK }; assertTokenTypesMatch(input, expectedTypes); } @Test public void givenFunctionCall_returnsCorrectTokenTypes() throws IOException { String input = "(defun myFunction (x)\n (print x))"; Token.Type[] expectedTypes = { Type.LEFT_PAREN, Type.IDENTIFIER, Type.IDENTIFIER, Type.LEFT_PAREN, Type.IDENTIFIER, Type.RIGHT_PAREN, Type.LEFT_PAREN, Type.IDENTIFIER, Type.IDENTIFIER, Type.RIGHT_PAREN, Type.RIGHT_PAREN }; assertTokenTypesMatch(input, expectedTypes); } private void assertTokenTypesMatch(String input, Token.Type[] expectedTypeList) throws IOException { InputStream stringInputStream = TestUtilities.createInputStreamFromString(input); LispScanner lispScanner = new LispScanner(stringInputStream, "stringInputStream"); for (Token.Type expectedType : expectedTypeList) assertEquals(expectedType, lispScanner.nextToken().getType()); assertEquals(Token.Type.EOF, lispScanner.nextToken().getType()); } }