@@ -3,7 +3,7 @@ module Test.BasicsSpec where
33import Prelude
44
55import Data.Array.NonEmpty as NEA
6−import Data.Either (Either(..))
6+import Data.Either (Either(..), isLeft)
77import Data.Foldable (traverse_)
88import Data.JSDate as JSDate
99import Data.List as List
@@ -144,9 +144,30 @@ spec = describe "En- and decoding" do
144144
145145 describe "works on variant types" do
146146 it "roundtrips" do
147− roundtrips (inj (Proxy ∷ _ "erwin") "e" ∷ Variant ("erwin" ∷ String))
147+ let input = inj (Proxy ∷ _ "a") {} ∷ Variant (a ∷ {}, b ∷ {})
148+ let asJSON = writeJSON input
149+ readJSON asJSON `shouldEqual` Right input
150+
151+ let input2 = inj (Proxy ∷ _ "b") {} ∷ Variant (a ∷ {}, b ∷ {})
152+ let asJSON2 = writeJSON input2
153+ readJSON asJSON2 `shouldEqual` Right input2
154+
155+ roundtrips (inj (Proxy ∷ _ "erwin") "e" ∷ Variant (erwin ∷ String))
148156 roundtrips (inj (Proxy ∷ _ "jackie") 7 ∷ Variant ExampleVariant)
149157
158+ it "does not select an absent optional branch" do
159+ let expected = inj (Proxy ∷ _ "a") 42 ∷ Variant (a ∷ Int, b ∷ Maybe Int)
160+ readJSON """{"a":42}""" `shouldEqual` Right expected
161+
162+ it "accepts an explicitly null optional branch" do
163+ let expected = inj (Proxy ∷ _ "b") Nothing ∷ Variant (a ∷ Int, b ∷ Maybe Int)
164+ readJSON """{"b":null}""" `shouldEqual` Right expected
165+
166+ it "rejects objects without a matching variant key" do
167+ traverse_
168+ (\json → isLeft (readJSON json ∷ _ (Variant (a ∷ {}, b ∷ {}))) `shouldEqual` true)
169+ [ "{}", """{"unknown":{}}""" ]
170+
150171 describe "works on tagged variant types" do
151172 it "roundtrips" do
152173 roundtrips (TaggedVariant (erwin "e") ∷ TaggedVariant "super" "hans" (Erwin ()))