@@ -5,10 +5,10 @@
55module UnitTests (ioTests, tests) where
66
77import Control.Monad (forM)
8−import Data.Aeson (decode, eitherDecode, encode, genericToJSON, genericToEncoding)
9−import Data.Aeson.TH ( deriveJSON )
8+import Data.Aeson (decode, eitherDecode, encode, genericToJSON, genericToEncoding, FromJSON(..), withObject, (.:), (.:?), (.:!))
109import Data.Aeson.Encode (encodeToTextBuilder)
11−import Data.Aeson.Types (ToJSON(..), FromJSON, Value, camelTo, camelTo2, defaultOptions, omitNothingFields)
10+import Data.Aeson.TH (deriveJSON)
11+import Data.Aeson.Types (ToJSON(..), Value, camelTo, camelTo2, defaultOptions, omitNothingFields)
1212import Data.Char (toUpper)
1313import Data.Time (UTCTime)
1414import Data.Time.Format (parseTime)
@@ -49,6 +49,7 @@ tests = testGroup "unit" [
4949 testCase "good" $ utcTimeGood
5050 , testCase "bad" $ utcTimeBad
5151 ]
52+ , testGroup ".:, .:?, .:!" $ fmap (testCase "-") dotColonMark
5253 ]
5354
5455roundTripCamel :: String -> Assertion
@@ -161,6 +162,36 @@ utcTimeBad = do
161162 let (dec :: Maybe UTCTime) = decode . LT.encodeUtf8 $ (LT.concat ["\"", s, "\""]) in
162163 assertEqual "verify failure" Nothing dec
163164
165+------------------------------------------------------------------------------
166+-- Comparison (.:?) and (.:!)
167+------------------------------------------------------------------------------
168+
169+newtype T1 = T1 (Maybe Int) deriving (Eq, Show)
170+newtype T2 = T2 (Maybe Int) deriving (Eq, Show)
171+newtype T3 = T3 (Maybe Int) deriving (Eq, Show)
172+
173+instance FromJSON T1 where parseJSON = fmap T1 . withObject "T1" (.: "value")
174+instance FromJSON T2 where parseJSON = fmap T2 . withObject "T2" (.:? "value")
175+instance FromJSON T3 where parseJSON = fmap T3 . withObject "T3" (.:! "value")
176+
177+dotColonMark :: [Assertion]
178+dotColonMark = [
179+ assertEqual ".: not-present" Nothing (decode ex1 :: Maybe T1)
180+ , assertEqual ".: 42" (Just (T1 (Just 42))) (decode ex2 :: Maybe T1)
181+ , assertEqual ".: null" (Just (T1 Nothing)) (decode ex3 :: Maybe T1)
182+
183+ , assertEqual ".:? not-present" (Just (T2 (Nothing))) (decode ex1 :: Maybe T2)
184+ , assertEqual ".:? 42" (Just (T2 (Just 42))) (decode ex2 :: Maybe T2)
185+ , assertEqual ".:? null" (Just (T2 Nothing)) (decode ex3 :: Maybe T2)
186+
187+ , assertEqual ".:! not-present" (Just (T3 (Nothing))) (decode ex1 :: Maybe T3)
188+ , assertEqual ".:! 42" (Just (T3 (Just 42))) (decode ex2 :: Maybe T3)
189+ , assertEqual ".:! null" Nothing (decode ex3 :: Maybe T3)
190+ ]
191+ where ex1 = "{}"
192+ ex2 = "{\"value\": 42 }"
193+ ex3 = "{\"value\": null }"
194+
164195
165196------------------------------------------------------------------------------
166197-- Comparison between bytestring and text encoders