2018-11-11 11:45:34 +00:00
|
|
|
import
|
|
|
|
strutils, options, unittest,
|
2018-12-17 23:01:06 +00:00
|
|
|
serialization/testing/generic_suite,
|
2019-01-10 22:20:37 +00:00
|
|
|
../json_serialization, ./utils
|
2018-11-11 11:45:34 +00:00
|
|
|
|
|
|
|
type
|
2019-03-13 21:20:58 +00:00
|
|
|
Meter = distinct int
|
|
|
|
Mile = distinct int
|
|
|
|
|
2018-11-11 11:45:34 +00:00
|
|
|
Simple = object
|
|
|
|
x: int
|
|
|
|
y: string
|
2019-03-13 21:20:58 +00:00
|
|
|
distance: Meter
|
2018-11-11 11:45:34 +00:00
|
|
|
|
|
|
|
Foo = object
|
|
|
|
i: int
|
|
|
|
b: Bar
|
|
|
|
s: string
|
|
|
|
|
|
|
|
Bar = object
|
|
|
|
sf: seq[Foo]
|
|
|
|
z: ref Simple
|
|
|
|
# o: Option[Simple]
|
|
|
|
|
2019-03-13 21:20:58 +00:00
|
|
|
Invalid = object
|
|
|
|
distance: Mile
|
|
|
|
|
|
|
|
template reject(code) =
|
|
|
|
static: assert(not compiles(code))
|
|
|
|
|
|
|
|
borrowSerialization(Meter, int)
|
|
|
|
|
2018-12-17 23:01:06 +00:00
|
|
|
executeReaderWriterTests Json
|
2018-11-11 11:45:34 +00:00
|
|
|
|
2019-03-13 21:20:58 +00:00
|
|
|
when false:
|
|
|
|
# The compiler cannot handle this check at the moment
|
|
|
|
# {.fatal.} seems fatal even in `compiles` context
|
|
|
|
var invalid = Invalid(distance: Mile(100))
|
|
|
|
reject invalid.toJson
|
|
|
|
|
2018-12-17 23:01:06 +00:00
|
|
|
suite "toJson tests":
|
2018-11-11 11:45:34 +00:00
|
|
|
test "encode primitives":
|
|
|
|
check:
|
|
|
|
1.toJson == "1"
|
|
|
|
"".toJson == "\"\""
|
|
|
|
"abc".toJson == "\"abc\""
|
|
|
|
|
|
|
|
test "simple objects":
|
2019-03-13 21:20:58 +00:00
|
|
|
var s = Simple(x: 10, y: "test", distance: Meter(20))
|
2018-11-11 11:45:34 +00:00
|
|
|
|
|
|
|
check:
|
2019-03-13 21:20:58 +00:00
|
|
|
s.toJson == """{"x":10,"y":"test","distance":20}"""
|
|
|
|
s.toJson(typeAnnotations = true) == """{"$type":"Simple","x":10,"y":"test","distance":20}"""
|
2018-11-11 11:45:34 +00:00
|
|
|
s.toJson(pretty = true) == dedent"""
|
|
|
|
{
|
|
|
|
"x": 10,
|
2019-03-13 21:20:58 +00:00
|
|
|
"y": "test",
|
|
|
|
"distance": 20
|
2018-11-11 11:45:34 +00:00
|
|
|
}
|
|
|
|
"""
|
|
|
|
|
2019-01-21 17:40:14 +00:00
|
|
|
test "max unsigned value":
|
|
|
|
var uintVal = not uint64(0)
|
|
|
|
let jsonValue = Json.encode(uintVal)
|
|
|
|
check:
|
|
|
|
jsonValue == "18446744073709551615"
|
|
|
|
Json.decode(jsonValue, uint64) == uintVal
|
|
|
|
|
|
|
|
expect JsonReaderError:
|
|
|
|
discard Json.decode(jsonValue, uint64, mode = Portable)
|
|
|
|
|