forked from hasura/graphql-engine
-
Notifications
You must be signed in to change notification settings - Fork 1
/
JSONPathSpec.hs
59 lines (50 loc) · 1.92 KB
/
JSONPathSpec.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
module Data.Parser.JSONPathSpec (spec) where
import Data.Aeson (JSONPath)
import Data.Aeson.Key qualified as K
import Data.Aeson.Types (JSONPathElement (..))
import Data.Parser.JSONPath
import Data.Text qualified as T
import Hasura.Prelude
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec = do
describe "encoding a JSON path" $ do
it "encodes a one-level path"
$ encodeJSONPath [Key "ABCD"]
`shouldBe` "$.ABCD"
it "encodes a multi-level path"
$ encodeJSONPath [Key "7seven", Index 0, Key "@!^@*#(!("]
`shouldBe` "$[\"7seven\"][0][\"@!^@*#(!(\"]"
it "escapes control characters and quotes"
$ encodeJSONPath [Key "/\\ '\" \t\r\n \xfffd"]
`shouldBe` "$[\"/\\\\ '\\\" \\t\\r\\n \xfffd\"]"
describe "parsing a JSON path" $ do
it "parses a single '$'"
$ parseJSONPath "$"
`shouldBe` Right []
it "parses bracketed single quotes"
$ parseJSONPath "$['foo \\' \" bar']"
`shouldBe` Right [Key "foo ' \" bar"]
it "parses bracketed double quotes"
$ parseJSONPath "$[\"bar ' \\\" foo\"]"
`shouldBe` Right [Key "bar ' \" foo"]
describe "the round trip" $ do
it "encodes and parses random JSON paths"
$ withMaxSuccess 1000
$ forAll (resize 20 generateJSONPath)
$ \jsonPath ->
let encPath = encodeJSONPath jsonPath
parsedJSONPathE = parseJSONPath encPath
in case parsedJSONPathE of
Left err -> counterexample (T.unpack (err <> ": " <> encPath)) False
Right parsedJSONPath -> property $ parsedJSONPath === jsonPath
generateJSONPath :: Gen JSONPath
generateJSONPath = map (either id id) <$> listOf1 genPathElementEither
where
genPathElementEither = do
indexLeft <- Left <$> genIndex
keyRight <- Right <$> genKey
elements [indexLeft, keyRight]
genIndex = Index <$> choose (0, 100)
genKey = Key . K.fromText . T.pack <$> listOf1 arbitraryUnicodeChar