refactor the tests of options (#16527)

This commit is contained in:
flywind 2021-01-01 12:01:07 -06:00 • committed by GitHub
commit b5101b23b5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,19 +1,8 @@
discard """ discard """
output: '''{"foo":{"test":"123"}}''' targets: "c js"
""" """
import json, options import std/[json, options]
type
Foo = ref object
test: string
Test = object
foo: Option[Foo]
let js = """{"foo": {"test": "123"}}"""
let parsed = parseJson(js)
let a = parsed.to(Test)
echo $(%*a)
# RefPerson is used to test that overloaded `==` operator is not called by # RefPerson is used to test that overloaded `==` operator is not called by
@ -26,6 +15,27 @@ proc `==`(a, b: RefPerson): bool =
assert(not a.isNil and not b.isNil) assert(not a.isNil and not b.isNil)
a.name == b.name a.name == b.name
template disableJsVm(body) =
# something doesn't work in JS VM
when defined(js):
when nimvm: discard
else: body
else:
body
proc main() =
type
Foo = ref object
test: string
Test = object
foo: Option[Foo]
let js = """{"foo": {"test": "123"}}"""
let parsed = parseJson(js)
let a = parsed.to(Test)
doAssert $(%*a) == """{"foo":{"test":"123"}}"""
block options: block options:
# work around a bug in unittest # work around a bug in unittest
let intNone = none(int) let intNone = none(int)
@ -75,8 +85,11 @@ block options:
doAssert($(some("Correct")) == "Some(\"Correct\")") doAssert($(some("Correct")) == "Some(\"Correct\")")
doAssert($(stringNone) == "None[string]") doAssert($(stringNone) == "None[string]")
disableJsVm:
block map_with_a_void_result: block map_with_a_void_result:
var procRan = 0 var procRan = 0
# TODO closure anonymous functions doesn't work in VM with JS
# Error: cannot evaluate at compile time: procRan
some(123).map(proc (v: int) = procRan = v) some(123).map(proc (v: int) = procRan = v)
doAssert procRan == 123 doAssert procRan == 123
intNone.map(proc (v: int) = doAssert false) intNone.map(proc (v: int) = doAssert false)
@ -156,3 +169,29 @@ block options:
block: block:
let p = some(RefPerson.new()) let p = some(RefPerson.new())
doAssert p.isSome doAssert p.isSome
block: # test cstring
block:
let x = some("".cstring)
doAssert x.isSome
doAssert x.get == ""
block:
let x = some("12345".cstring)
doAssert x.isSome
doAssert x.get == "12345"
block:
let x = "12345".cstring
let y = some(x)
doAssert y.isSome
doAssert y.get == "12345"
block:
let x = none(cstring)
doAssert x.isNone
doAssert $x == "None[cstring]"
static: main()
main()