git.iko.soy/typeable/hjsonpointer
on 7f51dd1 help sign in
13 files changed+233−556
since splitsnapshots
unifiedsplit
.travis.yml−104 Example.hs−29 MIT-LICENSE.txt+1−1 README.md+14−29 changelog.md−69 changelog.txt+9 hjsonpointer.cabal+43−52 shell.nix−9 src/Data/JsonPointer.hs+79 src/JSONPointer.hs−169 stack.yaml−2 test/Unit.hs−92 tests/Unit.hs+87
.travis.ymldeleted−104
@@ -1,104 +0,0 @@
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.hsdeleted−29
@@ -1,29 +0,0 @@
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) 2016 Ian Grant Jeffries
2+Copyright (c) 2015 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+14−29
@@ -2,43 +2,28 @@
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−
75# Example
86
9−```haskell
10−module Example where
7+```
8+{-# LANGUAGE OverloadedStrings #-}
9+
10+module Main where
1111
12−import Control.Monad (unless)
1312import Data.Aeson
14−import qualified JSONPointer as JP
13+import qualified Data.HashMap.Strict as H
14+import Data.JsonPointer
1515
1616main :: 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− ]
17+main =
18+ case jsonPointer "/foo" of
19+ Left e -> print e
20+ Right pntr ->
21+ case resolvePointer pntr (Object $ H.singleton "foo" $ String "bar") of
22+ Left e2 -> print e2
23+ Right v -> print v
3824```
3925
4026Output:
4127```
42−Right (String "bar")
43−Right (String "quux")
28+String "bar"
4429```
changelog.mddeleted−69
@@ -1,69 +0,0 @@
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.
changelog.txtnew file+9
@@ -0,0 +1,9 @@
1+# 0.2
2+
3+Fix mistake in resolveRefTok.
4+Split errors over two types.
5+Switch the order of pointer and value arguments for functions that take both. The pointer now comes first.
6+
7+# 0.1
8+
9+Initial implementation.
hjsonpointer.cabal+43−52
@@ -1,56 +1,47 @@
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
1+name: hjsonpointer
2+version: 0.2.0.2
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+extra-source-files: changelog.txt
13+ README.md
1714
1815library
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
16+ hs-source-dirs: src
17+ exposed-modules: Data.JsonPointer
18+ default-language: Haskell2010
19+ default-extensions: OverloadedStrings
20+ ghc-options: -Wall
21+ build-depends: aeson >= 0.7 && < 0.9
22+ , base >= 4.6 && < 4.9
23+ , unordered-containers >= 0.2 && < 0.3
24+ , text >= 1.2 && < 1.3
25+ , vector >= 0.10 && < 0.11
3326
3427test-suite unit
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
28+ type: exitcode-stdio-1.0
29+ hs-source-dirs: tests
30+ main-is: Unit.hs
31+ default-language: Haskell2010
32+ ghc-options: -Wall
33+ default-extensions: OverloadedStrings
34+ build-depends: aeson
35+ , base
36+ , hjsonpointer
37+ , unordered-containers
38+ , text
39+ , vector
40+ , http-types >= 0.8 && < 0.9
41+ , HUnit >= 1.2 && < 1.3
42+ , test-framework >= 0.8 && < 0.9
43+ , test-framework-hunit >= 0.3 && < 0.4
44+
45+source-repository head
46+ type: git
47+ location: git://github.com/seagreen/hjsonpointer.git
shell.nixdeleted−9
@@ -1,9 +0,0 @@
1−{ghc}:
2−with (import <nixpkgs> {});
3−
4−haskell.lib.buildStackProject {
5− name = "none";
6− inherit ghc;
7− buildInputs = [
8− ];
9−}
src/Data/JsonPointer.hsnew file+79
@@ -0,0 +1,79 @@
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 PointerFormatError
15+ -- | The Text to build a JSON Pointer must either be empty
16+ -- or start with a "/".
17+ = InvalidFirstChar
18+ | UnescapedTilde
19+ deriving (Eq, Show)
20+
21+data ResolutionError
22+ = ObjectLookupFailed
23+ | ArrayIndexInvalid
24+ | ArrayElemNotFound
25+ | ExpectedObjectOrArray
26+ deriving (Eq, Show)
27+
28+-- | The Text to build a JSON Pointer must either be empty or start
29+-- with a "/". If you're turning a URI Fragment into a JSON Pointer
30+-- you must drop the initial "#".
31+jsonPointer :: Text -> Either PointerFormatError JsonPointer
32+jsonPointer t =
33+ JsonPointer <$> (unescape =<< process (T.splitOn "/" t))
34+ where
35+ process ::[Text] -> Either PointerFormatError [Text]
36+ process [] = Right []
37+ process (x:xs)
38+ -- This checks that the JsonPointer started with a "/":
39+ | (not . T.null $ x) = Left InvalidFirstChar
40+ | otherwise = Right xs
41+
42+ unescape :: [Text] -> Either PointerFormatError [Text]
43+ unescape xs = do
44+ void $ mapM checkValid xs
45+ Right $ T.replace "~0" "~" . T.replace "~1" "/" <$> xs
46+
47+ checkValid :: Text -> Either PointerFormatError ()
48+ checkValid x = do
49+ let afterTildes = drop 1 $ T.splitOn "~" x
50+ if all (\y -> T.isPrefixOf "0" y || T.isPrefixOf "1" y) afterTildes
51+ then Right ()
52+ else Left UnescapedTilde
53+
54+resolvePointer :: JsonPointer -> Value -> Either ResolutionError Value
55+resolvePointer p v =
56+ case _unJsonPointer p of
57+ [] -> Right v
58+ _ -> resolveRefTok p v >>= uncurry resolvePointer
59+
60+-- | For internal use and specialized applications that don't want to
61+-- resolve the entire pointer at once.
62+resolveRefTok :: JsonPointer -> Value -> Either ResolutionError (JsonPointer, Value)
63+resolveRefTok p v = do
64+ case _unJsonPointer p of
65+ [] -> Right (p, v)
66+ (tok:ps) ->
67+ case v of
68+ Object h ->
69+ case H.lookup tok h of
70+ Nothing -> Left ObjectLookupFailed
71+ Just vv -> Right (JsonPointer ps, vv)
72+ Array vs -> do
73+ case readMaybe (T.unpack tok) of
74+ Nothing -> Left ArrayIndexInvalid
75+ Just n -> do
76+ when (n < 0) $ Left ArrayIndexInvalid
77+ when (n >= V.length vs) $ Left ArrayElemNotFound
78+ Right (JsonPointer ps, vs V.! n)
79+ _ -> Left ExpectedObjectOrArray
src/JSONPointer.hsdeleted−169
@@ -1,169 +0,0 @@
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.yamldeleted−2
@@ -1,2 +0,0 @@
1−resolver: lts-12.10
2−pvp-bounds: upper-revision
test/Unit.hsdeleted−92
@@ -1,92 +0,0 @@
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.hsnew file+87
@@ -0,0 +1,87 @@
1+module Main where
2+
3+import Control.Applicative
4+import Control.Arrow
5+import Control.Monad
6+import Data.Aeson
7+import qualified Data.HashMap.Strict as H
8+import Data.JsonPointer
9+import Data.Monoid
10+import Data.Text (Text)
11+import qualified Data.Text as T
12+import Data.Text.Encoding
13+import qualified Data.Vector as V
14+import Network.HTTP.Types.URI
15+import Test.Framework (defaultMain, testGroup)
16+import Test.Framework.Providers.HUnit (testCase)
17+import Test.HUnit hiding (Test)
18+
19+
20+main :: IO ()
21+main = defaultMain
22+ [ testGroup "unit"
23+ [ testCase "Can be represented in a JSON string value" jsonString
24+ , testCase "Can be represented in a URI fragment identifier" uriFragment
25+ ]
26+ ]
27+
28+specExample :: Value
29+specExample =
30+ Object $ H.fromList
31+ [ ("foo" , Array $ V.fromList ["bar", "baz"])
32+ , ("" , Number 0)
33+ , ("a/b" , Number 1)
34+ , ("c%d" , Number 2)
35+ , ("e^f" , Number 3)
36+ , ("g|h" , Number 4)
37+ , ("i\\j", Number 5)
38+ , ("k\"l", Number 6)
39+ , (" " , Number 7)
40+ , ("m~n" , Number 8)
41+ ]
42+
43+resolvesTo :: (Text, Value) -> Assertion
44+resolvesTo (t, expected) =
45+ case jsonPointer t of
46+ Left e -> assertFailure (show e <> " error for pointer: " <> show t)
47+ Right p ->
48+ assertEqual ("Resolved value for pointer: " <> show t)
49+ (Right expected)
50+ $ resolvePointer p specExample
51+
52+jsonString :: Assertion
53+jsonString =
54+ void $ mapM resolvesTo
55+ [ ("" , specExample)
56+ , ("/foo" , Array $ V.fromList ["bar", "baz"])
57+ , ("/foo/0", String "bar")
58+ , ("/" , Number 0)
59+ , ("/a~1b" , Number 1)
60+ , ("/c%d" , Number 2)
61+ , ("/e^f" , Number 3)
62+ , ("/g|h" , Number 4)
63+ , ("/i\\j" , Number 5)
64+ , ("/k\"l" , Number 6)
65+ , ("/ " , Number 7)
66+ , ("/m~0n" , Number 8)
67+ ]
68+
69+uriFragment :: Assertion
70+uriFragment =
71+ void $ mapM resolvesTo $ first decodeFragment <$>
72+ [ ("#" , specExample)
73+ , ("#/foo" , Array $ V.fromList ["bar", "baz"])
74+ , ("#/foo/0", String "bar")
75+ , ("#/" , Number 0)
76+ , ("#/a~1b" , Number 1)
77+ , ("#/c%25d", Number 2)
78+ , ("#/e%5Ef", Number 3)
79+ , ("#/g%7Ch", Number 4)
80+ , ("#/i%5Cj", Number 5)
81+ , ("#/k%22l", Number 6)
82+ , ("#/%20" , Number 7)
83+ , ("#/m~0n" , Number 8)
84+ ]
85+ where
86+ decodeFragment :: Text -> Text
87+ decodeFragment = T.drop 1 . decodeUtf8 . urlDecode True . encodeUtf8