git.iko.soy/typeable/hjsonpointer
on master help sign in
12 files changed+562−201
since splitsnapshots
unifiedsplit
.travis.yml+104 Example.hs+29 MIT-LICENSE.txt+1−1 README.md+35−1 changelog.md+69 hjsonpointer.cabal+52−42 shell.nix+9 src/Data/JsonPointer.hs−77 src/JSONPointer.hs+169 stack.yaml+2 test/Unit.hs+92 tests/Unit.hs−80
.travis.ymlnew file+104
@@ -0,0 +1,104 @@
1+# This Travis job script has been generated by a script via
2+#
3+# runghc make_travis_yml_2.hs 'hjsonpointer.cabal'
4+#
5+# For more information, see https://github.com/hvr/multi-ghc-travis
6+
7+# NOTE: After generating comment out `cabal check`, it requires a description field.
8+
9+language: c
10+sudo: false
11+
12+git:
13+ submodules: false # whether to recursively clone submodules
14+
15+cache:
16+ directories:
17+ - $HOME/.cabal/packages
18+ - $HOME/.cabal/store
19+
20+before_cache:
21+ - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log
22+ # remove files that are regenerated by 'cabal update'
23+ - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.*
24+ - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json
25+ - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache
26+ - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar
27+ - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx
28+
29+ - rm -rfv $HOME/.cabal/packages/head.hackage
30+
31+matrix:
32+ include:
33+ - compiler: "ghc-8.0.2"
34+ # env: TEST=--disable-tests BENCH=--disable-benchmarks
35+ addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-8.0.2], sources: [hvr-ghc]}}
36+ - compiler: "ghc-8.2.2"
37+ # env: TEST=--disable-tests BENCH=--disable-benchmarks
38+ addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-8.2.2], sources: [hvr-ghc]}}
39+ - compiler: "ghc-8.4.1"
40+ # env: TEST=--disable-tests BENCH=--disable-benchmarks
41+ addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-8.4.1], sources: [hvr-ghc]}}
42+
43+before_install:
44+ - HC=${CC}
45+ - HCPKG=${HC/ghc/ghc-pkg}
46+ - unset CC
47+ - ROOTDIR=$(pwd)
48+ - mkdir -p $HOME/.local/bin
49+ - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH"
50+ - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') ))
51+ - echo $HCNUMVER
52+
53+install:
54+ - cabal --version
55+ - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]"
56+ - BENCH=${BENCH---enable-benchmarks}
57+ - TEST=${TEST---enable-tests}
58+ - HADDOCK=${HADDOCK-true}
59+ - INSTALLED=${INSTALLED-true}
60+ - GHCHEAD=${GHCHEAD-false}
61+ - travis_retry cabal update -v
62+ - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config"
63+ - rm -fv cabal.project cabal.project.local
64+ - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$'
65+ - "printf 'packages: \".\"\\n' > cabal.project"
66+ - cat cabal.project
67+ - if [ -f "./configure.ac" ]; then
68+ (cd "." && autoreconf -i);
69+ fi
70+ - rm -f cabal.project.freeze
71+ - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all
72+ - cabal new-build -w ${HC} --disable-tests --disable-benchmarks --project-file="cabal.project" --dep -j2 all
73+ - rm -rf .ghc.environment.* "."/dist
74+ - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX)
75+
76+# Here starts the actual work to be performed for the package under test;
77+# any command which exits with a non-zero exit code causes the build to fail.
78+script:
79+ # test that source-distributions can be generated
80+ - (cd "." && cabal sdist)
81+ - mv "."/dist/hjsonpointer-*.tar.gz ${DISTDIR}/
82+ - cd ${DISTDIR} || false
83+ - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \;
84+ - "printf 'packages: hjsonpointer-*/*.cabal\\n' > cabal.project"
85+ - cat cabal.project
86+ # this builds all libraries and executables (without tests/benchmarks)
87+ - cabal new-build -w ${HC} --disable-tests --disable-benchmarks all
88+
89+ # Build with installed constraints for packages in global-db
90+ - if $INSTALLED; then echo cabal new-build -w ${HC} --disable-tests --disable-benchmarks $(${HCPKG} list --global --simple-output --names-only | sed 's/\([a-zA-Z0-9-]\{1,\}\) */--constraint="\1 installed" /g') all | sh; else echo "Not building with installed constraints"; fi
91+
92+ # build & run tests, build benchmarks
93+ - cabal new-build -w ${HC} ${TEST} ${BENCH} all
94+ - if [ "x$TEST" = "x--enable-tests" ]; then cabal new-test -w ${HC} ${TEST} ${BENCH} all; fi
95+
96+ # cabal check
97+ # - (cd hjsonpointer-* && cabal check)
98+
99+ # haddock
100+ - rm -rf ./dist-newstyle
101+ - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi
102+
103+# REGENDATA ["hjsonpointer.cabal"]
104+# EOF
Example.hsnew file+29
@@ -0,0 +1,29 @@
1+
2+module Example where
3+
4+import Control.Monad (unless)
5+import Data.Aeson
6+import qualified JSONPointer as JP
7+
8+main :: IO ()
9+main = do
10+ -- JSON Pointers must either be empty or start with a /.
11+ pntr1 <- case JP.unescape "/foo/0" of
12+ Left _ -> error "Failed to construct JSON Pointer."
13+ Right pntr -> return pntr
14+
15+ -- We can also write JSON Pointers in Haskell.
16+ let pntr2 = JP.Pointer [JP.Token "/"]
17+ -- When we do this we don't have to escape / or ~ characters
18+ -- (as ~1 and ~0 respectively) like we do in an escaped JSON
19+ -- Pointer string.
20+ unless (JP.unescape "/~1" == Right pntr2) (error "ohno!")
21+
22+ print (JP.resolve pntr1 document)
23+ print (JP.resolve pntr2 document)
24+
25+ where
26+ document :: Value
27+ document = object [ "foo" .= [String "bar", String "baz"]
28+ , "/" .= String "quux"
29+ ]
MIT-LICENSE.txt+1−1
@@ -1,5 +1,5 @@
11The MIT License (MIT)
2−Copyright (c) 2015 Ian Grant Jeffries
2+Copyright (c) 2016 Ian Grant Jeffries
33
44Permission is hereby granted, free of charge, to any person obtaining a copy
55of this software and associated documentation files (the "Software"), to deal
README.md+35−1
@@ -2,9 +2,43 @@
22
33[JSON Pointer](http://tools.ietf.org/html/rfc6901) library for Haskell.
44
5+[Hackage](https://hackage.haskell.org/package/hjsonpointer) / [GitHub](https://github.com/seagreen/hjsonpointer) / [Travis CI](https://travis-ci.org/seagreen/hjsonpointer)
6+
57# Example
68
9+```haskell
10+module Example where
11+
12+import Control.Monad (unless)
13+import Data.Aeson
14+import qualified JSONPointer as JP
15+
16+main :: IO ()
17+main = do
18+ -- JSON Pointers must either be empty or start with a /.
19+ pntr1 <- case JP.unescape "/foo/0" of
20+ Left _ -> error "Failed to construct JSON Pointer."
21+ Right pntr -> return pntr
22+
23+ -- We can also write JSON Pointers in Haskell.
24+ let pntr2 = JP.Pointer [JP.Token "/"]
25+ -- When we do this we don't have to escape / or ~ characters
26+ -- (as ~1 and ~0 respectively) like we do in an escaped JSON
27+ -- Pointer string.
28+ unless (JP.unescape "/~1" == Right pntr2) (error "ohno!")
29+
30+ print (JP.resolve pntr1 document)
31+ print (JP.resolve pntr2 document)
32+
33+ where
34+ document :: Value
35+ document = object [ "foo" .= [String "bar", String "baz"]
36+ , "/" .= String "quux"
37+ ]
38+```
39+
40+Output:
741```
8−λ jsonPointer "/foo" >>= resolvePointer (Object $ singleton "foo" $ String "bar")
942Right (String "bar")
43+Right (String "quux")
1044```
changelog.mdnew file+69
@@ -0,0 +1,69 @@
1+# 1.5.0
2+
3++ Drop QuickCheck dependency (thanks @mmhat !).
4+
5+# 1.4.0
6+
7++ Enable GHC 8.4 (thanks @4e6 !).
8++ Drop GHC 7.10.
9+
10+# 1.3.0
11+
12++ Test with GHC 8.2. Drop GHC 7.8.
13+
14+# 1.2.0
15+
16++ Track upper bounds in a Hackage revision instead of source code.
17+
18+# 1.1.1
19+
20++ Bump aeson.
21+
22+# 1.1.0.2
23+
24++ Raise test dep upper bounds.
25+
26+# 1.1.0.1
27+
28++ Bump `vector`.
29+
30+# 1.1.0.0
31+
32++ Rename the module to `JSONPointer`.
33++ Bump aeson.
34++ Derive `Semigroup` for `Pointer`.
35++ Reorganize code.
36+
37+# 1.0.0.2
38+
39++ Bump hspec.
40+
41+# 1.0.0.1
42+
43++ Remove HUnit dep.
44+
45+# 1.0.0.0
46+
47++ Bump aeson.
48+
49+# 0.3.0.2
50+
51++ Switch to hspec for tests.
52+
53+# 0.3.0.1
54+
55++ Enable GHC 8.
56+
57+# 0.3.0.0
58+
59++ Rewrite.
60+
61+# 0.2
62+
63++ Fix mistake in `resolveRefTok`.
64++ Split errors over two types.
65++ Switch the order of pointer and value arguments for functions that take both. The pointer now comes first.
66+
67+# 0.1
68+
69++ Initial implementation.
hjsonpointer.cabal+52−42
@@ -1,46 +1,56 @@
1−name: hjsonpointer
2−version: 0.1.0.0
3−synopsis: JSON Pointer library for Haskell
4−homepage: https://github.com/seagreen/hjsonpointer
5−license: MIT
6−license-file: MIT-LICENSE.txt
7−author: Ian Grant Jeffries
8−maintainer: ian@housejeffries.com
9−category: Data
10−build-type: Simple
11−cabal-version: >=1.10
12−extra-source-files: README.md
1+name: hjsonpointer
2+version: 1.5.0
3+synopsis: JSON Pointer library
4+homepage: https://github.com/seagreen/hjsonpointer
5+license: MIT
6+license-file: MIT-LICENSE.txt
7+author: Ian Grant Jeffries
8+maintainer: ian@housejeffries.com
9+category: Data
10+build-type: Simple
11+cabal-version: >=1.10
12+-- Rerun multi-ghc-travis (executable make-travis-yml-2) after changing:
13+Tested-With: GHC == 8.0.2, GHC == 8.2.2, GHC == 8.4.1
14+extra-source-files:
15+ changelog.md
16+ README.md
1317
1418library
15− hs-source-dirs: src
16− exposed-modules: Data.JsonPointer
17− default-language: Haskell2010
18− default-extensions: OverloadedStrings
19− ghc-options: -Wall
20− build-depends: aeson >= 0.8 && < 0.9
21− , base >= 4.7 && < 4.8
22− , unordered-containers >= 0.2 && < 0.3
23− , text >= 1.2 && < 1.3
24− , vector >= 0.10 && < 0.11
19+ hs-source-dirs:
20+ src
21+ default-language: Haskell2010
22+ ghc-options:
23+ -Wall
24+ exposed-modules:
25+ JSONPointer
26+ build-depends:
27+ base >= 4.9 && < 5
28+ , aeson >= 0.7
29+ , hashable >= 1.2
30+ , unordered-containers >= 0.2
31+ , text >= 1.2
32+ , vector >= 0.10
2533
2634test-suite unit
27− type: exitcode-stdio-1.0
28− hs-source-dirs: tests
29− main-is: Unit.hs
30− default-language: Haskell2010
31− ghc-options: -Wall
32− default-extensions: OverloadedStrings
33− build-depends: aeson
34− , base
35− , hjsonpointer
36− , unordered-containers
37− , text
38− , vector
39− , http-types >= 0.8 && < 0.9
40− , HUnit >= 1.2 && < 1.3
41− , test-framework >= 0.8 && < 0.9
42− , test-framework-hunit >= 0.3 && < 0.4
43−
44−source-repository head
45− type: git
46− location: git://github.com/seagreen/hjsonpointer.git
35+ hs-source-dirs:
36+ test
37+ ./
38+ main-is: Unit.hs
39+ default-language: Haskell2010
40+ type: exitcode-stdio-1.0
41+ default-extensions:
42+ OverloadedStrings
43+ ghc-options:
44+ -Wall
45+ -fno-warn-orphans
46+ other-modules: Example
47+ build-depends:
48+ aeson
49+ , base
50+ , hjsonpointer
51+ , hspec >= 2.2
52+ , http-types >= 0.8
53+ , QuickCheck
54+ , unordered-containers
55+ , text
56+ , vector
shell.nixnew file+9
@@ -0,0 +1,9 @@
1+{ghc}:
2+with (import <nixpkgs> {});
3+
4+haskell.lib.buildStackProject {
5+ name = "none";
6+ inherit ghc;
7+ buildInputs = [
8+ ];
9+}
src/Data/JsonPointer.hsdeleted−77
@@ -1,77 +0,0 @@
1−module Data.JsonPointer where
2−
3−import Control.Applicative
4−import Control.Monad
5−import Data.Aeson
6−import qualified Data.HashMap.Strict as H
7−import Data.Text (Text)
8−import qualified Data.Text as T
9−import qualified Data.Vector as V
10−import Text.Read (readMaybe)
11−
12−newtype JsonPointer = JsonPointer { _unJsonPointer :: [Text] } deriving (Eq, Show)
13−
14−data PointerErr
15− -- | The Text to build a JSON Pointer must either be empty
16− -- or start with a '/'.
17− = InvalidFirstChar
18− | UnescapedTilde
19− | ObjectLookupFailed
20− | ArrayIndexInvalid
21− | ArrayElemNotFound
22− | UnindexableValue
23− deriving (Eq, Show)
24−
25−-- The Text to build a JSON Pointer must either be empty or start
26−-- with a '/'. If you're turning a URI Fragment into a JSON Pointer
27−-- you must drop the initial '#'.
28−jsonPointer :: Text -> Either PointerErr JsonPointer
29−jsonPointer t =
30− JsonPointer <$> (unescape =<< process (T.splitOn "/" t))
31− where
32− process ::[Text] -> Either PointerErr [Text]
33− process [] = Right []
34− process (x:xs) = do
35− unless (T.null x) $ Left InvalidFirstChar
36− Right xs
37−
38− unescape :: [Text] -> Either PointerErr [Text]
39− unescape xs = do
40− void $ mapM checkValid xs
41− Right $ T.replace "~0" "~" . T.replace "~1" "/" <$> xs
42−
43− checkValid :: Text -> Either PointerErr ()
44− checkValid x = do
45− let afterTildes = drop 1 $ T.splitOn "~" x
46− if all (\y -> T.isPrefixOf "0" y || T.isPrefixOf "1" y) afterTildes
47− then Right ()
48− else Left UnescapedTilde
49−
50−resolvePointer :: Value -> JsonPointer -> Either PointerErr Value
51−resolvePointer v p =
52− case _unJsonPointer p of
53− [] -> Right v
54− _ -> resolveRefTok v p >>= uncurry resolvePointer
55−
56−-- | For internal use and specialized applications that don't want to
57−-- resolve the entire pointer at once.
58−resolveRefTok :: Value -> JsonPointer -> Either PointerErr (Value, JsonPointer)
59−resolveRefTok v p = do
60− case _unJsonPointer p of
61− [] -> Right (v, p)
62− (tok:ps) ->
63− case v of
64− Object h ->
65− case H.lookup tok h of
66− Nothing -> Left ObjectLookupFailed
67− Just vv -> Right (vv, JsonPointer ps)
68− Array vs -> do
69− case readMaybe (T.unpack tok) of
70− Nothing -> Left ArrayIndexInvalid
71− Just n -> do
72− unless (n >= 0) $ Left ArrayIndexInvalid
73− unless (n < V.length vs) $ Left ArrayElemNotFound
74− Right (vs V.! n, JsonPointer ps)
75− vv -> do
76− unless (null ps) $ Left UnindexableValue
77− Right (vv, JsonPointer [])
src/JSONPointer.hsnew file+169
@@ -0,0 +1,169 @@
1+{-# LANGUAGE DeriveGeneric #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+
5+module JSONPointer where
6+
7+import Control.Monad (when)
8+import Data.Aeson
9+import qualified Data.Hashable as HA
10+import qualified Data.HashMap.Strict as HM
11+import Data.Semigroup (Semigroup)
12+import Data.Text (Text)
13+import qualified Data.Text as T
14+import qualified Data.Vector as V
15+import GHC.Generics (Generic)
16+import Text.Read (readMaybe)
17+
18+--------------------------------------------------
19+-- * Resolution
20+--------------------------------------------------
21+
22+data ResolutionError
23+ = ObjectLookupFailed
24+ | ArrayIndexInvalid
25+ | ArrayElemNotFound
26+ | ExpectedObjectOrArray
27+ deriving (Eq, Show)
28+
29+resolve :: Pointer -> Value -> Either ResolutionError Value
30+resolve (Pointer []) v = Right v
31+resolve (Pointer (t:ts)) v = resolveToken t v >>= resolve (Pointer ts)
32+
33+--------------------------------------------------
34+-- * Main types and escaping
35+--------------------------------------------------
36+
37+newtype Pointer
38+ = Pointer { _unPointer :: [Token] }
39+ deriving (Eq, Show, Semigroup, Monoid, Generic)
40+
41+instance HA.Hashable Pointer
42+
43+instance FromJSON Pointer where
44+ parseJSON = withText "JSON Pointer" $ \t ->
45+ case unescape t of
46+ Left e -> fail (show e)
47+ Right p -> pure p
48+
49+instance ToJSON Pointer where
50+ toJSON = String . escape
51+
52+-- | We don't try to distinguish between integer tokens and string
53+-- tokens since all tokens start as strings, and all tokens can
54+-- be used to resolve JSON objects.
55+--
56+-- Since these are unescaped you can write @"/"@ and @"~"@ normally.
57+-- (e.g. if you're referencing a key such as @"abc/123"@, go ahead
58+-- and write that exactly.
59+newtype Token
60+ = Token { _unToken :: Text }
61+ deriving (Eq, Show, Generic)
62+
63+instance HA.Hashable Token
64+
65+-- | This escapes @"/"@ (because it's the token separator character).
66+--
67+-- It also escapes @"~"@ (because it's the escape character).
68+escape :: Pointer -> Text
69+escape (Pointer []) = ""
70+escape (Pointer ts) =
71+ T.cons '/'
72+ . T.intercalate "/"
73+ . fmap (T.replace "/" "~1" . T.replace "~" "~0" . _unToken)
74+ $ ts
75+
76+data FormatError
77+ = InvalidFirstChar
78+ -- ^ JSON Pointers must either be empty or start with a @/@.
79+ | UnescapedTilde
80+ deriving (Eq, Show)
81+
82+-- | JSON Pointers must either be empty or start with a @/@. This means
83+-- that if you're turning a URI Fragment into a JSON Pointer you must
84+-- drop the initial @#@.
85+--
86+-- Note that the unescaping happening here is not the same as URI
87+-- decoding. If you are turning a URI fragment into a JSON Pointer you
88+-- must URI decode the 'Text' before using it as an argument to this
89+-- function. There's an example of how to do this in the tests using
90+-- "Network.HTTP.Types.URI.urlDecode" from http-types.
91+unescape :: Text -> Either FormatError Pointer
92+unescape txt =
93+ case T.splitOn "/" txt of
94+ [] -> Right (Pointer [])
95+ "":xs -> Pointer <$> traverse f xs
96+ _ -> Left InvalidFirstChar
97+ where
98+ f :: Text -> Either FormatError Token
99+ f t = case unescapeToken t of
100+ Nothing -> Left UnescapedTilde
101+ Just tok -> Right tok
102+
103+--------------------------------------------------
104+-- * Wrapper Types
105+--
106+-- $ These aren't used by the rest of the library
107+-- (as explained in the docs for 'Token').
108+--
109+-- However, they might be useful if you need to distinguish JSON Pointer
110+-- tokens from plain 'Text' or 'Int' without losing information by
111+-- converting to 'Token'.
112+--------------------------------------------------
113+
114+-- | A glorified @type@ alias. If you need to do JSON Pointer operations
115+-- you're looking for 'Token' instead.
116+--
117+-- NOTE: Unlike 'Token' this is escaped.
118+newtype Key
119+ = Key { _unKey :: Text }
120+ deriving (Eq, Show, Generic)
121+
122+instance HA.Hashable Key
123+
124+-- | A glorified @type@ alias. If you need to do JSON Pointer operations
125+-- you're looking for 'Token' instead.
126+newtype Index
127+ = Index { _unIndex :: Int }
128+ deriving (Eq, Show, Generic)
129+
130+instance HA.Hashable Index
131+
132+--------------------------------------------------
133+-- * Internals
134+--------------------------------------------------
135+
136+-- | For internal use (by 'unescape').
137+unescapeToken :: Text -> Maybe Token
138+unescapeToken t
139+ | not (isValid t) = Nothing
140+ | otherwise = Just . Token . replace $ t
141+ where
142+ -- All tildes must be followed by 0s or 1s.
143+ isValid :: Text -> Bool
144+ isValid x = all (\y -> T.isPrefixOf "0" y || T.isPrefixOf "1" y) afterTildes
145+ where
146+ afterTildes :: [Text]
147+ afterTildes = drop 1 $ T.splitOn "~" x
148+
149+ replace :: Text -> Text
150+ replace = T.replace "~0" "~" . T.replace "~1" "/"
151+
152+-- | For internal use (by 'resolve').
153+--
154+-- Might also be useful for specialized applications that don't
155+-- want to resolve an entire pointer at once.
156+resolveToken :: Token -> Value -> Either ResolutionError Value
157+resolveToken tok (Array vs) =
158+ case readMaybe . T.unpack . _unToken $ tok of
159+ Nothing -> Left ArrayIndexInvalid
160+ Just n -> do
161+ when (n < 0) (Left ArrayIndexInvalid)
162+ case vs V.!? n of
163+ Nothing -> Left ArrayElemNotFound
164+ Just res -> Right res
165+resolveToken tok (Object h) =
166+ case HM.lookup (_unToken tok) h of
167+ Nothing -> Left ObjectLookupFailed
168+ Just res -> Right res
169+resolveToken _ _ = Left ExpectedObjectOrArray
stack.yamlnew file+2
@@ -0,0 +1,2 @@
1+resolver: lts-12.10
2+pvp-bounds: upper-revision
test/Unit.hsnew file+92
@@ -0,0 +1,92 @@
1+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
2+{-# LANGUAGE StandaloneDeriving #-}
3+
4+module Main where
5+
6+import Data.Aeson
7+import Data.Bifunctor (first)
8+import Data.Foldable
9+import Data.Monoid
10+import Data.Text (Text)
11+import qualified Data.Text as T
12+import Data.Text.Encoding (decodeUtf8, encodeUtf8)
13+import qualified Data.Vector as V
14+import qualified JSONPointer as JP
15+import Network.HTTP.Types.URI (urlDecode)
16+
17+import Test.Hspec
18+import Test.QuickCheck (Arbitrary(..), property)
19+
20+import qualified Example
21+
22+deriving instance Arbitrary JP.Pointer
23+
24+instance Arbitrary JP.Token where
25+ arbitrary = JP.Token . T.pack <$> arbitrary
26+
27+main :: IO ()
28+main = hspec $ do
29+ describe "example" $ do
30+ it "compiles and runs without errors" Example.main
31+ describe "pointers" $ do
32+ it "can be stored as JSON without changing its value" (property roundtrip)
33+ it "can be represented in a JSON string value" jsonString
34+ it "can be represented in a URI fragment identifier" uriFragment
35+
36+roundtrip :: JP.Pointer -> Bool
37+roundtrip a = Just a == decode (encode a)
38+
39+jsonString :: Expectation
40+jsonString = traverse_ resolvesTo
41+ [ ("" , specExample)
42+ , ("/foo" , Array $ V.fromList ["bar", "baz"])
43+ , ("/foo/0", String "bar")
44+ , ("/" , Number 0)
45+ , ("/a~1b" , Number 1)
46+ , ("/c%d" , Number 2)
47+ , ("/e^f" , Number 3)
48+ , ("/g|h" , Number 4)
49+ , ("/i\\j" , Number 5)
50+ , ("/k\"l" , Number 6)
51+ , ("/ " , Number 7)
52+ , ("/m~0n" , Number 8)
53+ ]
54+
55+uriFragment :: Expectation
56+uriFragment = traverse_ resolvesTo . fmap (first decodeFragment) $
57+ [ ("#" , specExample)
58+ , ("#/foo" , Array $ V.fromList ["bar", "baz"])
59+ , ("#/foo/0", String "bar")
60+ , ("#/" , Number 0)
61+ , ("#/a~1b" , Number 1)
62+ , ("#/c%25d", Number 2)
63+ , ("#/e%5Ef", Number 3)
64+ , ("#/g%7Ch", Number 4)
65+ , ("#/i%5Cj", Number 5)
66+ , ("#/k%22l", Number 6)
67+ , ("#/%20" , Number 7)
68+ , ("#/m~0n" , Number 8)
69+ ]
70+ where
71+ decodeFragment :: Text -> Text
72+ decodeFragment = T.drop 1 . decodeUtf8 . urlDecode True . encodeUtf8
73+
74+resolvesTo :: (Text, Value) -> Expectation
75+resolvesTo (t, expected) =
76+ case JP.unescape t of
77+ Left e -> expectationFailure (show e <> " error for pointer: " <> show t)
78+ Right p -> JP.resolve p specExample `shouldBe` Right expected
79+
80+specExample :: Value
81+specExample = object
82+ [ "foo" .= (["bar", "baz"] :: [Text])
83+ , "" .= (0 :: Int)
84+ , "a/b" .= (1 :: Int)
85+ , "c%d" .= (2 :: Int)
86+ , "e^f" .= (3 :: Int)
87+ , "g|h" .= (4 :: Int)
88+ , "i\\j" .= (5 :: Int)
89+ , "k\"l" .= (6 :: Int)
90+ , " " .= (7 :: Int)
91+ , "m~n" .= (8 :: Int)
92+ ]
tests/Unit.hsdeleted−80
@@ -1,80 +0,0 @@
1−module Main where
2−
3−import Control.Monad
4−import Data.Aeson
5−import qualified Data.HashMap.Strict as H
6−import Data.JsonPointer
7−import Data.Monoid
8−import Data.Text (Text)
9−import qualified Data.Text as T
10−import Data.Text.Encoding
11−import qualified Data.Vector as V
12−import Network.HTTP.Types.URI
13−import Test.Framework (defaultMain, testGroup)
14−import Test.Framework.Providers.HUnit (testCase)
15−import Test.HUnit hiding (Test)
16−
17−
18−main :: IO ()
19−main = defaultMain
20− [ testGroup "unit"
21− [ testCase "Can be represented in a JSON string value" jsonString
22− , testCase "Can be represented in a URI fragment identifier" uriFragment
23− ]
24− ]
25−
26−specExample :: Value
27−specExample =
28− Object $ H.fromList
29− [ ("foo" , Array $ V.fromList ["bar", "baz"])
30− , ("" , Number 0)
31− , ("a/b" , Number 1)
32− , ("c%d" , Number 2)
33− , ("e^f" , Number 3)
34− , ("g|h" , Number 4)
35− , ("i\\j", Number 5)
36− , ("k\"l", Number 6)
37− , (" " , Number 7)
38− , ("m~n" , Number 8)
39− ]
40−
41−jsonString :: Assertion
42−jsonString =
43− void $ mapM
44− (\(a,expected) -> assertEqual ("Tried to resolve " <> show a) (Right expected)
45− $ jsonPointer a >>= resolvePointer specExample)
46− [ ("" , specExample)
47− , ("/foo" , Array $ V.fromList ["bar", "baz"])
48− , ("/foo/0", String "bar")
49− , ("/" , Number 0)
50− , ("/a~1b" , Number 1)
51− , ("/c%d" , Number 2)
52− , ("/e^f" , Number 3)
53− , ("/g|h" , Number 4)
54− , ("/i\\j" , Number 5)
55− , ("/k\"l" , Number 6)
56− , ("/ " , Number 7)
57− , ("/m~0n" , Number 8)
58− ]
59−
60−uriFragment :: Assertion
61−uriFragment =
62− void $ mapM
63− (\(a,expected) -> assertEqual ("Tried to resolve " <> show a) (Right expected)
64− $ jsonPointer (decodeFragment a) >>= resolvePointer specExample)
65− [ ("#" , specExample)
66− , ("#/foo" , Array $ V.fromList ["bar", "baz"])
67− , ("#/foo/0", String "bar")
68− , ("#/" , Number 0)
69− , ("#/a~1b" , Number 1)
70− , ("#/c%25d", Number 2)
71− , ("#/e%5Ef", Number 3)
72− , ("#/g%7Ch", Number 4)
73− , ("#/i%5Cj", Number 5)
74− , ("#/k%22l", Number 6)
75− , ("#/%20" , Number 7)
76− , ("#/m~0n" , Number 8)
77− ]
78− where
79− decodeFragment :: Text -> Text
80− decodeFragment = T.drop 1 . decodeUtf8 . urlDecode True . encodeUtf8