2018-12-17 23:01:06 +00:00
|
|
|
import
|
|
|
|
unittest,
|
2019-01-10 22:20:37 +00:00
|
|
|
../json_serialization/lexer, ./utils
|
2018-12-17 23:01:06 +00:00
|
|
|
|
2020-03-25 13:48:17 +00:00
|
|
|
template expectedToken(token: TokKind, additionalCheck = true) {.dirty.} =
|
2018-12-17 23:01:06 +00:00
|
|
|
lexer.next()
|
|
|
|
check:
|
|
|
|
lexer.tok == token
|
2020-03-25 13:48:17 +00:00
|
|
|
bool(additionalCheck)
|
2018-12-17 23:01:06 +00:00
|
|
|
|
|
|
|
template lexerTest(name, input: string, expectations) {.dirty.} =
|
|
|
|
test name:
|
|
|
|
var stream = memoryStream(dedent(input))
|
|
|
|
var lexer = JsonLexer.init stream
|
|
|
|
expectations
|
|
|
|
|
|
|
|
template `=~`(lhs, rhs: float): bool =
|
|
|
|
abs(lhs - rhs) < 0.01
|
|
|
|
|
|
|
|
suite "lexer tests":
|
|
|
|
lexerTest "object with simple fields", """
|
|
|
|
{
|
|
|
|
"x": 10,
|
|
|
|
"y": "test"
|
|
|
|
}
|
|
|
|
""":
|
|
|
|
expectedToken tkCurlyLe
|
|
|
|
expectedToken tkString, lexer.strVal == "x"
|
|
|
|
expectedToken tkColon
|
2020-03-25 13:48:17 +00:00
|
|
|
expectedToken tkInt, lexer.absIntVal == 10
|
2018-12-17 23:01:06 +00:00
|
|
|
expectedToken tkComma
|
|
|
|
expectedToken tkString, lexer.strVal == "y"
|
|
|
|
expectedToken tkColon
|
|
|
|
expectedToken tkString, lexer.strVal == "test"
|
|
|
|
expectedToken tkCurlyRi
|
|
|
|
expectedToken tkEof
|
|
|
|
expectedToken tkEof # check that reading past the end is benign
|
|
|
|
|
|
|
|
lexerTest "int literal", "190":
|
2020-03-25 13:48:17 +00:00
|
|
|
expectedToken tkInt, lexer.absIntVal == 190
|
2018-12-17 23:01:06 +00:00
|
|
|
expectedToken tkEof
|
|
|
|
|
2019-08-14 11:34:59 +00:00
|
|
|
lexerTest "int64 literal", "3568257348920230622":
|
2020-03-25 13:48:17 +00:00
|
|
|
expectedToken tkInt, lexer.absIntVal == 3568257348920230622'u64
|
2019-08-14 11:34:59 +00:00
|
|
|
expectedToken tkEof
|
|
|
|
|
2018-12-17 23:01:06 +00:00
|
|
|
lexerTest "float literal", ".340":
|
|
|
|
expectedToken tkFloat, lexer.floatVal =~ 0.340
|
|
|
|
expectedToken tkEof
|
|
|
|
|
|
|
|
lexerTest "string literal", "\"hello\"":
|
|
|
|
expectedToken tkString, lexer.strVal == "hello"
|
|
|
|
expectedToken tkEof
|
|
|
|
|
|
|
|
lexerTest "mixed array", "[1, 2.0, \"test\", {}, [],]":
|
|
|
|
expectedToken tkBracketLe
|
2020-03-25 13:48:17 +00:00
|
|
|
expectedToken tkInt, lexer.absIntVal == 1
|
2018-12-17 23:01:06 +00:00
|
|
|
expectedToken tkComma
|
|
|
|
expectedToken tkFloat, lexer.floatVal =~ 2.0
|
|
|
|
expectedToken tkComma
|
|
|
|
expectedToken tkString, lexer.strVal == "test"
|
|
|
|
expectedToken tkComma
|
|
|
|
expectedToken tkCurlyLe
|
|
|
|
expectedToken tkCurlyRi
|
|
|
|
expectedToken tkComma
|
|
|
|
expectedToken tkBracketLe
|
|
|
|
expectedToken tkBracketRi
|
|
|
|
expectedToken tkComma
|
|
|
|
expectedToken tkBracketRi
|
|
|
|
expectedToken tkEof
|
|
|
|
|