tjsonutils.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. discard """
  2. matrix: "--mm:refc; --mm:orc"
  3. targets: "c cpp js"
  4. """
  5. import std/jsonutils
  6. import std/json
  7. from std/math import isNaN, signbit
  8. from std/fenv import epsilon
  9. from stdtest/testutils import whenRuntimeJs
  10. import std/[assertions, objectdollar]
  11. proc testRoundtrip[T](t: T, expected: string) =
  12. # checks that `T => json => T2 => json2` is such that json2 = json
  13. let j = t.toJson
  14. doAssert $j == expected, "\n" & $j & "\n" & expected
  15. doAssert j.jsonTo(T).toJson == j
  16. var t2: T
  17. t2.fromJson(j)
  18. doAssert t2.toJson == j
  19. proc testRoundtripVal[T](t: T, expected: string) =
  20. # similar to testRoundtrip, but also checks that the `T => json => T2` is such that `T2 == T`
  21. # note that this isn't always possible, e.g. for pointer-like types.
  22. let j = t.toJson
  23. let j2 = $j
  24. doAssert j2 == expected, j2
  25. let j3 = j2.parseJson
  26. let t2 = j3.jsonTo(T)
  27. doAssert t2 == t
  28. doAssert $t2.toJson == j2 # still needed, because -0.0 = 0.0 but their json representation differs
  29. import tables, sets, algorithm, sequtils, options, strtabs
  30. from strutils import contains
  31. type Foo = ref object
  32. id: int
  33. proc `==`(a, b: Foo): bool =
  34. a.id == b.id
  35. type MyEnum = enum me0, me1 = "me1Alt", me2, me3, me4
  36. proc `$`(a: MyEnum): string =
  37. # putting this here pending https://github.com/nim-lang/Nim/issues/13747
  38. if a == me2: "me2Modif"
  39. else: system.`$`(a)
  40. template fn() =
  41. block: # toJson, jsonTo
  42. type Foo = distinct float
  43. testRoundtrip('x', """120""")
  44. when not defined(js):
  45. testRoundtrip(cast[pointer](12345)): """12345"""
  46. when nimvm:
  47. discard
  48. # bugs:
  49. # Error: unhandled exception: 'intVal' is not accessible using discriminant 'kind' of type 'TNode' [
  50. # Error: VM does not support 'cast' from tyNil to tyPointer
  51. else:
  52. testRoundtrip(pointer(nil)): """0"""
  53. testRoundtrip(cast[pointer](nil)): """0"""
  54. # refs bug #9423
  55. testRoundtrip(Foo(1.5)): """1.5"""
  56. block: # OrderedTable
  57. testRoundtrip({"z": "Z", "y": "Y"}.toOrderedTable): """{"z":"Z","y":"Y"}"""
  58. doAssert toJson({"z": 10, "": 11}.newTable).`$`.contains """"":11""" # allows hash to change
  59. testRoundtrip({"z".cstring: 1, "".cstring: 2}.toOrderedTable): """{"z":1,"":2}"""
  60. testRoundtrip({"z": (f1: 'f'), }.toTable): """{"z":{"f1":102}}"""
  61. block: # StringTable
  62. testRoundtrip({"name": "John", "city": "Monaco"}.newStringTable): """{"mode":"modeCaseSensitive","table":{"city":"Monaco","name":"John"}}"""
  63. block: # complex example
  64. let t = {"z": "Z", "y": "Y"}.newStringTable
  65. type A = ref object
  66. a1: string
  67. let a = (1.1, "fo", 'x', @[10,11], [true, false], [t,newStringTable()], [0'i8,3'i8], -4'i16, (foo: 0.5'f32, bar: A(a1: "abc"), bar2: A.default, cstring1: "foo", cstring2: "", cstring3: cstring(nil)))
  68. testRoundtrip(a):
  69. """[1.1,"fo",120,[10,11],[true,false],[{"mode":"modeCaseSensitive","table":{"y":"Y","z":"Z"}},{"mode":"modeCaseSensitive","table":{}}],[0,3],-4,{"foo":0.5,"bar":{"a1":"abc"},"bar2":null,"cstring1":"foo","cstring2":"","cstring3":null}]"""
  70. block:
  71. # edge case when user defined `==` doesn't handle `nil` well, e.g.:
  72. # https://github.com/nim-lang/nimble/blob/63695f490728e3935692c29f3d71944d83bb1e83/src/nimblepkg/version.nim#L105
  73. testRoundtrip(@[Foo(id: 10), nil]): """[{"id":10},null]"""
  74. block: # enum
  75. type Foo = enum f1, f2, f3, f4, f5
  76. type Bar = enum b1, b2, b3, b4
  77. let a = [f2: b2, f3: b3, f4: b4]
  78. doAssert b2.ord == 1 # explains the `1`
  79. testRoundtrip(a): """[1,2,3]"""
  80. block: # JsonNode
  81. let a = ((1, 2.5, "abc").toJson, (3, 4.5, "foo"))
  82. testRoundtripVal(a): """[[1,2.5,"abc"],[3,4.5,"foo"]]"""
  83. block:
  84. template toInt(a): untyped = cast[int](a)
  85. let a = 3.toJson
  86. let b = (a, a)
  87. let c1 = b.toJson
  88. doAssert c1[0].toInt == a.toInt
  89. doAssert c1[1].toInt == a.toInt
  90. let c2 = b.toJson(ToJsonOptions(jsonNodeMode: joptJsonNodeAsCopy))
  91. doAssert c2[0].toInt != a.toInt
  92. doAssert c2[1].toInt != c2[0].toInt
  93. doAssert c2[1] == c2[0]
  94. let c3 = b.toJson(ToJsonOptions(jsonNodeMode: joptJsonNodeAsObject))
  95. doAssert $c3 == """[{"isUnquoted":false,"kind":2,"num":3},{"isUnquoted":false,"kind":2,"num":3}]"""
  96. block: # ToJsonOptions
  97. let a = (me1, me2)
  98. doAssert $a.toJson() == "[1,2]"
  99. doAssert $a.toJson(ToJsonOptions(enumMode: joptEnumSymbol)) == """["me1","me2"]"""
  100. doAssert $a.toJson(ToJsonOptions(enumMode: joptEnumString)) == """["me1Alt","me2Modif"]"""
  101. block: # set
  102. type Foo = enum f1, f2, f3, f4, f5
  103. type Goo = enum g1 = 10, g2 = 15, g3 = 17, g4
  104. let a = ({f1, f3}, {1'u8, 7'u8}, {'0'..'9'}, {123'u16, 456, 789, 1121, 1122, 1542}, {g2, g3})
  105. testRoundtrip(a): """[[0,2],[1,7],[48,49,50,51,52,53,54,55,56,57],[123,456,789,1121,1122,1542],[15,17]]"""
  106. block: # bug #17383
  107. block:
  108. let a = (int32.high, uint32.high)
  109. testRoundtrip(a): "[2147483647,4294967295]"
  110. when int.sizeof > 4:
  111. block:
  112. let a = (int64.high, uint64.high)
  113. testRoundtrip(a): "[9223372036854775807,18446744073709551615]"
  114. block:
  115. let a = (int.high, uint.high)
  116. when int.sizeof == 4:
  117. testRoundtrip(a): "[2147483647,4294967295]"
  118. else:
  119. testRoundtrip(a): "[9223372036854775807,18446744073709551615]"
  120. block: # bug #18007
  121. testRoundtrip((NaN, Inf, -Inf, 0.0, -0.0, 1.0)): """["nan","inf","-inf",0.0,-0.0,1.0]"""
  122. testRoundtrip((float32(NaN), Inf, -Inf, 0.0, -0.0, 1.0)): """["nan","inf","-inf",0.0,-0.0,1.0]"""
  123. testRoundtripVal((Inf, -Inf, 0.0, -0.0, 1.0)): """["inf","-inf",0.0,-0.0,1.0]"""
  124. doAssert ($NaN.toJson).parseJson.jsonTo(float).isNaN
  125. block: # bug #18009; unfixable unless we change parseJson (which would have overhead),
  126. # but at least we can guarantee that the distinction between 0.0 and -0.0 is preserved.
  127. let a = (0, 0.0, -0.0, 0.5, 1, 1.0)
  128. testRoundtripVal(a): "[0,0.0,-0.0,0.5,1,1.0]"
  129. let a2 = $($a.toJson).parseJson
  130. whenRuntimeJs:
  131. doAssert a2 == "[0,0,-0.0,0.5,1,1]"
  132. do:
  133. doAssert a2 == "[0,0.0,-0.0,0.5,1,1.0]"
  134. let b = a2.parseJson.jsonTo(type(a))
  135. doAssert not b[1].signbit
  136. doAssert b[2].signbit
  137. doAssert not b[3].signbit
  138. block: # bug #15397, bug #13196
  139. let a = 0.1
  140. let x = 0.12345678901234567890123456789
  141. let b = (a + 0.2, 0.3, x)
  142. testRoundtripVal(b): "[0.30000000000000004,0.3,0.12345678901234568]"
  143. testRoundtripVal(0.12345678901234567890123456789): "0.12345678901234568"
  144. testRoundtripVal(epsilon(float64)): "2.220446049250313e-16"
  145. testRoundtripVal(1.0 + epsilon(float64)): "1.0000000000000002"
  146. block: # case object
  147. type Foo = object
  148. x0: float
  149. case t1: bool
  150. of true: z1: int8
  151. of false: z2: uint16
  152. x1: string
  153. testRoundtrip(Foo(t1: true, z1: 5, x1: "bar")): """{"x0":0.0,"t1":true,"z1":5,"x1":"bar"}"""
  154. testRoundtrip(Foo(x0: 1.5, t1: false, z2: 6)): """{"x0":1.5,"t1":false,"z2":6,"x1":""}"""
  155. type PFoo = ref Foo
  156. testRoundtrip(PFoo(x0: 1.5, t1: false, z2: 6)): """{"x0":1.5,"t1":false,"z2":6,"x1":""}"""
  157. block: # ref case object
  158. type Foo = ref object
  159. x0: float
  160. case t1: bool
  161. of true: z1: int8
  162. of false: z2: uint16
  163. x1: string
  164. testRoundtrip(Foo(t1: true, z1: 5, x1: "bar")): """{"x0":0.0,"t1":true,"z1":5,"x1":"bar"}"""
  165. testRoundtrip(Foo(x0: 1.5, t1: false, z2: 6)): """{"x0":1.5,"t1":false,"z2":6,"x1":""}"""
  166. block: # generic case object
  167. type Foo[T] = ref object
  168. x0: float
  169. case t1: bool
  170. of true: z1: int8
  171. of false: z2: uint16
  172. x1: string
  173. testRoundtrip(Foo[float](t1: true, z1: 5, x1: "bar")): """{"x0":0.0,"t1":true,"z1":5,"x1":"bar"}"""
  174. testRoundtrip(Foo[int](x0: 1.5, t1: false, z2: 6)): """{"x0":1.5,"t1":false,"z2":6,"x1":""}"""
  175. # sanity check: nesting inside a tuple
  176. testRoundtrip((Foo[int](x0: 1.5, t1: false, z2: 6), "foo")): """[{"x0":1.5,"t1":false,"z2":6,"x1":""},"foo"]"""
  177. block: # case object: 2 discriminants, `when` branch, range discriminant
  178. type Foo[T] = object
  179. case t1: bool
  180. of true:
  181. z1: int8
  182. of false:
  183. z2: uint16
  184. when T is float:
  185. case t2: range[0..3]
  186. of 0: z3: int8
  187. of 2,3: z4: uint16
  188. else: discard
  189. testRoundtrip(Foo[float](t1: true, z1: 5, t2: 3, z4: 12)): """{"t1":true,"z1":5,"t2":3,"z4":12}"""
  190. testRoundtrip(Foo[int](t1: false, z2: 7)): """{"t1":false,"z2":7}"""
  191. # pending https://github.com/nim-lang/Nim/issues/14698, test with `type Foo[T] = ref object`
  192. block: # bug: pass opt params in fromJson
  193. type Foo = object
  194. a: int
  195. b: string
  196. c: float
  197. type Bar = object
  198. foo: Foo
  199. boo: string
  200. var f: seq[Foo]
  201. try:
  202. fromJson(f, parseJson """[{"b": "bbb"}]""")
  203. doAssert false
  204. except ValueError:
  205. doAssert true
  206. fromJson(f, parseJson """[{"b": "bbb"}]""", Joptions(allowExtraKeys: true, allowMissingKeys: true))
  207. doAssert f == @[Foo(a: 0, b: "bbb", c: 0.0)]
  208. var b: Bar
  209. fromJson(b, parseJson """{"foo": {"b": "bbb"}}""", Joptions(allowExtraKeys: true, allowMissingKeys: true))
  210. doAssert b == Bar(foo: Foo(a: 0, b: "bbb", c: 0.0))
  211. block: # jsonTo with `opt`
  212. let b2 = """{"foo": {"b": "bbb"}}""".parseJson.jsonTo(Bar, Joptions(allowExtraKeys: true, allowMissingKeys: true))
  213. doAssert b2 == Bar(foo: Foo(a: 0, b: "bbb", c: 0.0))
  214. block testHashSet:
  215. testRoundtrip(HashSet[string]()): "[]"
  216. testRoundtrip([""].toHashSet): """[""]"""
  217. testRoundtrip(["one"].toHashSet): """["one"]"""
  218. var s: HashSet[string]
  219. fromJson(s, parseJson("""["one","two"]"""))
  220. doAssert s == ["one", "two"].toHashSet
  221. let jsonNode = toJson(s)
  222. doAssert jsonNode.elems.mapIt(it.str).sorted == @["one", "two"]
  223. block testOrderedSet:
  224. testRoundtrip(["one", "two", "three"].toOrderedSet):
  225. """["one","two","three"]"""
  226. block testOption:
  227. testRoundtrip(some("test")): "\"test\""
  228. testRoundtrip(none[string]()): "null"
  229. testRoundtrip(some(42)): "42"
  230. testRoundtrip(none[int]()): "null"
  231. block testStrtabs:
  232. testRoundtrip(newStringTable(modeStyleInsensitive)):
  233. """{"mode":"modeStyleInsensitive","table":{}}"""
  234. testRoundtrip(
  235. newStringTable("name", "John", "surname", "Doe", modeCaseSensitive)):
  236. """{"mode":"modeCaseSensitive","table":{"name":"John","surname":"Doe"}}"""
  237. block testJoptions:
  238. type
  239. AboutLifeUniverseAndEverythingElse = object
  240. question: string
  241. answer: int
  242. block testExceptionOnExtraKeys:
  243. var guide: AboutLifeUniverseAndEverythingElse
  244. let json = parseJson(
  245. """{"question":"6*9=?","answer":42,"author":"Douglas Adams"}""")
  246. doAssertRaises ValueError, fromJson(guide, json)
  247. doAssertRaises ValueError,
  248. fromJson(guide, json, Joptions(allowMissingKeys: true))
  249. type
  250. A = object
  251. a1,a2,a3: int
  252. var a: A
  253. let j = parseJson("""{"a3": 1, "a4": 2}""")
  254. doAssertRaises ValueError,
  255. fromJson(a, j, Joptions(allowMissingKeys: true))
  256. block testExceptionOnMissingKeys:
  257. var guide: AboutLifeUniverseAndEverythingElse
  258. let json = parseJson("""{"answer":42}""")
  259. doAssertRaises ValueError, fromJson(guide, json)
  260. doAssertRaises ValueError,
  261. fromJson(guide, json, Joptions(allowExtraKeys: true))
  262. block testAllowExtraKeys:
  263. var guide: AboutLifeUniverseAndEverythingElse
  264. let json = parseJson(
  265. """{"question":"6*9=?","answer":42,"author":"Douglas Adams"}""")
  266. fromJson(guide, json, Joptions(allowExtraKeys: true))
  267. doAssert guide == AboutLifeUniverseAndEverythingElse(
  268. question: "6*9=?", answer: 42)
  269. block refObject: #bug 17986
  270. type A = ref object
  271. case is_a: bool
  272. of true:
  273. a: int
  274. else:
  275. b: int
  276. var a = A()
  277. fromJson(a, """{"is_a": true, "a":1, "extra_key": 1}""".parseJson, Joptions(allowExtraKeys: true))
  278. doAssert $a[] == "(is_a: true, a: 1)"
  279. block testAllowMissingKeys:
  280. var guide = AboutLifeUniverseAndEverythingElse(
  281. question: "6*9=?", answer: 54)
  282. let json = parseJson("""{"answer":42}""")
  283. fromJson(guide, json, Joptions(allowMissingKeys: true))
  284. doAssert guide == AboutLifeUniverseAndEverythingElse(
  285. question: "6*9=?", answer: 42)
  286. block testAllowExtraAndMissingKeys:
  287. var guide = AboutLifeUniverseAndEverythingElse(
  288. question: "6*9=?", answer: 54)
  289. let json = parseJson(
  290. """{"answer":42,"author":"Douglas Adams"}""")
  291. fromJson(guide, json, Joptions(
  292. allowExtraKeys: true, allowMissingKeys: true))
  293. doAssert guide == AboutLifeUniverseAndEverythingElse(
  294. question: "6*9=?", answer: 42)
  295. type
  296. Foo = object
  297. a: array[2, string]
  298. case b: bool
  299. of false: f: float
  300. of true: t: tuple[i: int, s: string]
  301. case c: range[0 .. 2]
  302. of 0: c0: int
  303. of 1: c1: float
  304. of 2: c2: string
  305. block testExceptionOnMissingDiscriminantKey:
  306. var foo: Foo
  307. let json = parseJson("""{"a":["one","two"]}""")
  308. doAssertRaises ValueError, fromJson(foo, json)
  309. block testDoNotResetMissingFieldsWhenHaveDiscriminantKey:
  310. var foo = Foo(a: ["one", "two"], b: true, t: (i: 42, s: "s"),
  311. c: 0, c0: 1)
  312. let json = parseJson("""{"b":true,"c":2}""")
  313. fromJson(foo, json, Joptions(allowMissingKeys: true))
  314. doAssert foo.a == ["one", "two"]
  315. doAssert foo.b
  316. doAssert foo.t == (i: 42, s: "s")
  317. doAssert foo.c == 2
  318. doAssert foo.c2 == ""
  319. block testAllowMissingDiscriminantKeys:
  320. var foo: Foo
  321. let json = parseJson("""{"a":["one","two"],"c":1,"c1":3.14159}""")
  322. fromJson(foo, json, Joptions(allowMissingKeys: true))
  323. doAssert foo.a == ["one", "two"]
  324. doAssert not foo.b
  325. doAssert foo.f == 0.0
  326. doAssert foo.c == 1
  327. doAssert foo.c1 == 3.14159
  328. block testExceptionOnWrongDiscirminatBranchInJson:
  329. var foo = Foo(b: false, f: 3.14159, c: 0, c0: 42)
  330. let json = parseJson("""{"c2": "hello"}""")
  331. doAssertRaises ValueError,
  332. fromJson(foo, json, Joptions(allowMissingKeys: true))
  333. # Test that the original fields are not reset.
  334. doAssert not foo.b
  335. doAssert foo.f == 3.14159
  336. doAssert foo.c == 0
  337. doAssert foo.c0 == 42
  338. block testNoExceptionOnRightDiscriminantBranchInJson:
  339. var foo = Foo(b: false, f: 0, c:1, c1: 0)
  340. let json = parseJson("""{"f":2.71828,"c1": 3.14159}""")
  341. fromJson(foo, json, Joptions(allowMissingKeys: true))
  342. doAssert not foo.b
  343. doAssert foo.f == 2.71828
  344. doAssert foo.c == 1
  345. doAssert foo.c1 == 3.14159
  346. block testAllowExtraKeysInJsonOnWrongDisciriminatBranch:
  347. var foo = Foo(b: false, f: 3.14159, c: 0, c0: 42)
  348. let json = parseJson("""{"c2": "hello"}""")
  349. fromJson(foo, json, Joptions(allowMissingKeys: true,
  350. allowExtraKeys: true))
  351. # Test that the original fields are not reset.
  352. doAssert not foo.b
  353. doAssert foo.f == 3.14159
  354. doAssert foo.c == 0
  355. doAssert foo.c0 == 42
  356. block testInvalidTupleLength:
  357. let json = parseJson("[0]")
  358. # Should raise ValueError instead of index error
  359. doAssertRaises(ValueError):
  360. discard json.jsonTo((int, int))
  361. type
  362. InnerEnum = enum
  363. A
  364. B
  365. C
  366. InnerObject = object
  367. x: string
  368. y: InnerEnum
  369. block testOptionsArePassedWhenDeserialising:
  370. let json = parseJson("""{"x": "hello"}""")
  371. let inner = json.jsonTo(Option[InnerObject], Joptions(allowMissingKeys: true))
  372. doAssert inner.isSome()
  373. doAssert inner.get().x == "hello"
  374. doAssert inner.get().y == A
  375. block testOptionsArePassedWhenSerialising:
  376. let inner = some InnerObject(x: "hello", y: A)
  377. let json = inner.toJson(ToJsonOptions(enumMode: joptEnumSymbol))
  378. doAssert $json == """{"x":"hello","y":"A"}"""
  379. block: # bug #21638
  380. type Something = object
  381. doAssert "{}".parseJson.jsonTo(Something) == Something()
  382. when false:
  383. ## TODO: Implement support for nested variant objects allowing the tests
  384. ## bellow to pass.
  385. block testNestedVariantObjects:
  386. type
  387. Variant = object
  388. case b: bool
  389. of false:
  390. case bf: bool
  391. of false: bff: int
  392. of true: bft: float
  393. of true:
  394. case bt: bool
  395. of false: btf: string
  396. of true: btt: char
  397. testRoundtrip(Variant(b: false, bf: false, bff: 42)):
  398. """{"b": false, "bf": false, "bff": 42}"""
  399. testRoundtrip(Variant(b: false, bf: true, bft: 3.14159)):
  400. """{"b": false, "bf": true, "bft": 3.14159}"""
  401. testRoundtrip(Variant(b: true, bt: false, btf: "test")):
  402. """{"b": true, "bt": false, "btf": "test"}"""
  403. testRoundtrip(Variant(b: true, bt: true, btt: 'c')):
  404. """{"b": true, "bt": true, "btt": "c"}"""
  405. # TODO: Add additional tests with missing and extra JSON keys, both when
  406. # allowed and forbidden analogous to the tests for the not nested
  407. # variant objects.
  408. static: fn()
  409. fn()