tricorder-types 1.0.0.0 → 1.1.0.0
raw patch · 14 files changed
+602/−65 lines, 14 filesdep +autodocodecdep +autodocodec-schemadep ~atelier-corePVP ok
version bump matches the API change (PVP)
Dependencies added: autodocodec, autodocodec-schema
Dependency ranges changed: atelier-core
API changes (from Hackage documentation)
- Tricorder.API.FieldMask.Projection: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.API.FieldMask.Projection.Projection
+ Tricorder.API.FieldMask.Projection: codec :: Schema -> ValueCodec Projection Void
+ Tricorder.API.FieldMask.Projection: optionalKeys :: Codec context input output -> Codec context input output
+ Tricorder.API.FieldMask.Schema: fromCodec :: ValueCodec input output -> Schema
+ Tricorder.API.JsonSchema: document :: Text -> ValueCodec input output -> Text
+ Tricorder.API.Response: Error :: MessageWithLoc -> Response a
+ Tricorder.API.Response: MessageWithLoc :: Text -> Text -> MessageWithLoc
+ Tricorder.API.Response: Pending :: MessageWithLoc -> Response a
+ Tricorder.API.Response: Success :: a -> Response a
+ Tricorder.API.Response: [location] :: MessageWithLoc -> Text
+ Tricorder.API.Response: [message] :: MessageWithLoc -> Text
+ Tricorder.API.Response: codec :: ValueCodec input output -> ValueCodec (Response input) (Response output)
+ Tricorder.API.Response: data MessageWithLoc
+ Tricorder.API.Response: data Response a
+ Tricorder.API.Response: instance Autodocodec.Class.HasCodec Tricorder.API.Response.MessageWithLoc
+ Tricorder.API.Response: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.API.Response.MessageWithLoc
+ Tricorder.API.Response: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.API.Response.MessageWithLoc
+ Tricorder.API.Response: instance GHC.Base.Applicative Tricorder.API.Response.Response
+ Tricorder.API.Response: instance GHC.Base.Functor Tricorder.API.Response.Response
+ Tricorder.API.Response: instance GHC.Base.Monad Tricorder.API.Response.Response
+ Tricorder.API.Response: instance GHC.Classes.Eq Tricorder.API.Response.MessageWithLoc
+ Tricorder.API.Response: instance GHC.Classes.Eq a => GHC.Classes.Eq (Tricorder.API.Response.Response a)
+ Tricorder.API.Response: instance GHC.Generics.Generic (Tricorder.API.Response.Response a)
+ Tricorder.API.Response: instance GHC.Generics.Generic Tricorder.API.Response.MessageWithLoc
+ Tricorder.API.Response: instance GHC.Show.Show Tricorder.API.Response.MessageWithLoc
+ Tricorder.API.Response: instance GHC.Show.Show a => GHC.Show.Show (Tricorder.API.Response.Response a)
+ Tricorder.API.Test.SuiteView: instance Autodocodec.Class.HasCodec Tricorder.API.Test.SuiteView.CaseView
+ Tricorder.API.Test.SuiteView: instance Autodocodec.Class.HasCodec Tricorder.API.Test.SuiteView.Outcome
+ Tricorder.API.Test.SuiteView: instance Autodocodec.Class.HasCodec Tricorder.API.Test.SuiteView.Status
+ Tricorder.API.Test.SuiteView: instance Autodocodec.Class.HasCodec Tricorder.API.Test.SuiteView.SuiteView
+ Tricorder.API.Test.SuiteView: instance GHC.Enum.Bounded Tricorder.API.Test.SuiteView.Outcome
+ Tricorder.API.Test.SuiteView: instance GHC.Enum.Bounded Tricorder.API.Test.SuiteView.Status
+ Tricorder.API.Test.SuiteView: instance GHC.Enum.Enum Tricorder.API.Test.SuiteView.Outcome
+ Tricorder.API.Test.SuiteView: instance GHC.Enum.Enum Tricorder.API.Test.SuiteView.Status
+ Tricorder.API.Test.SuitesResponse: SuitesResponse :: [suite] -> SuitesResponse suite
+ Tricorder.API.Test.SuitesResponse: [suites] :: SuitesResponse suite -> [suite]
+ Tricorder.API.Test.SuitesResponse: codec :: ValueCodec input output -> ValueCodec (SuitesResponse input) (SuitesResponse output)
+ Tricorder.API.Test.SuitesResponse: instance GHC.Classes.Eq suite => GHC.Classes.Eq (Tricorder.API.Test.SuitesResponse.SuitesResponse suite)
+ Tricorder.API.Test.SuitesResponse: instance GHC.Show.Show suite => GHC.Show.Show (Tricorder.API.Test.SuitesResponse.SuitesResponse suite)
+ Tricorder.API.Test.SuitesResponse: newtype SuitesResponse suite
Files
- CHANGELOG.md +25/−0
- src/Tricorder/API/FieldMask/Projection.hs +63/−14
- src/Tricorder/API/FieldMask/Schema.hs +22/−0
- src/Tricorder/API/JsonSchema.hs +23/−0
- src/Tricorder/API/Response.hs +84/−0
- src/Tricorder/API/Test/Args.hs +23/−2
- src/Tricorder/API/Test/SuiteView.hs +75/−10
- src/Tricorder/API/Test/SuiteView/Schema.hs +5/−18
- src/Tricorder/API/Test/SuitesResponse.hs +21/−0
- test/Unit/Tricorder/API/FieldMask/ProjectionSpec.hs +72/−17
- test/Unit/Tricorder/API/FieldMask/SchemaSpec.hs +38/−1
- test/Unit/Tricorder/API/ResponseSpec.hs +41/−0
- test/Unit/Tricorder/API/SuitesResponseSpec.hs +98/−0
- tricorder-types.cabal +12/−3
CHANGELOG.md view
@@ -7,6 +7,31 @@ ## [Unreleased] +## [1.1.0.0] - 2026-11-18++### Added++- `--help-json` flag for `tricorder test suites`, showing the JSON Schema of+ the output of `tricorder test suites --json`.+- `autodocodec` codecs (`HasCodec` instances) for `SuiteView`, `CaseView`,+ `Status` and `Outcome` in `Tricorder.API.Test.SuiteView`. Their `ToJSON`+ instances are derived from these.+- `Tricorder.API.FieldMask.Schema.fromCodec`, deriving the fields of a field+ mask `Schema` from a codec. `Tricorder.API.Test.SuiteView.Schema.schema` is+ derived from the codec of `SuiteView`.+- `Tricorder.API.FieldMask.Projection.codec`, encoding projections with their+ fields in selection order, and `Tricorder.API.FieldMask.Projection.optionalKeys`,+ for the JSON Schema of projections.+- `Tricorder.API.Response`, the JSON envelope (`Response`, `MessageWithLoc`)+ of command output and its codec, moved from `tricorder`.+- `Tricorder.API.Test.SuitesResponse`, the payload of+ `tricorder test suites --json` and its codec, moved from `tricorder`.++### Removed++- `ToJSON` instance of `Tricorder.API.FieldMask.Projection.Projection`, in+ favour of `Tricorder.API.FieldMask.Projection.codec`.+ ## [1.0.0.0] - 2026-10-29 ### Changed
src/Tricorder/API/FieldMask/Projection.hs view
@@ -1,23 +1,37 @@--- | Parsing field masks, checking them against the shape of a response, and--- projecting response values down to the selected fields. module Tricorder.API.FieldMask.Projection ( Projection (..) , project+ , codec+ , optionalKeys , renderYaml ) where -import Data.Aeson (ToJSON (..), Value (..), object, pairs, (.=))+import Autodocodec+ ( Codec (..)+ , ObjectCodec+ , ValueCodec+ , bimapCodec+ , eitherCodec+ , listCodec+ , named+ , object+ , optionalFieldWith'+ , optionalKeyCodec+ , valueCodec+ , (.=)+ )+import Data.Aeson (Value (..)) import Data.Aeson.Key qualified as Key import Data.Aeson.KeyMap qualified as KeyMap+import Data.List qualified as List import Data.Yaml.Builder qualified as Yaml import Tricorder.API.FieldMask.Schema (Schema (..)) --- | A JSON value cut down to the fields of a 'Schema', with its fields in--- schema order.+-- | Parts of a JSON value. data Projection = PObject [(Text, Projection)] | PArray [Projection]@@ -25,15 +39,50 @@ deriving stock (Eq, Show) -instance ToJSON Projection where- toJSON = \case- PObject fields -> object [Key.fromText name .= value | (name, value) <- fields]- PArray values -> toJSON values- PScalar value -> value- toEncoding = \case- PObject fields -> pairs $ foldMap (\(name, value) -> Key.fromText name .= value) fields- PArray values -> toEncoding values- PScalar value -> toEncoding value+-- | Encodes a projection with just the fields defined in the given 'Schema'.+-- This is effectively just an encoder, though, hence the 'Void' decoding type.+codec :: Schema -> ValueCodec Projection Void+codec schema =+ named "Projection"+ $ bimapCodec (const $ Left "projections can only be encoded") split+ $ eitherCodec (listCodec $ codec schema)+ $ eitherCodec (object "Projection" $ fieldsCodec schema)+ $ valueCodec+ where+ split = \case+ PArray values -> Left values+ PObject fields -> Right $ Left fields+ PScalar value -> Right $ Right value+++fieldsCodec :: Schema -> ObjectCodec [(Text, Projection)] ()+fieldsCodec (Schema fields) =+ for_ fields \(name, sub) ->+ optionalFieldWith' name (codec $ fromMaybe (Schema []) sub) .= List.lookup name+++-- | Mark every field as optional. Discriminated unions are kept as-is, as they+-- need their discriminator.+optionalKeys :: Codec context input output -> Codec context input output+optionalKeys = \case+ RequiredKeyCodec key valueCodec' doc ->+ BimapCodec (maybe (Left $ "missing key " <> toString key) (Right . coerce)) (Just . coerce)+ $ optionalKeyCodec key (optionalKeys valueCodec') doc+ OptionalKeyCodec key valueCodec' doc -> OptionalKeyCodec key (optionalKeys valueCodec') doc+ OptionalKeyWithDefaultCodec key valueCodec' def doc ->+ OptionalKeyWithDefaultCodec key (optionalKeys valueCodec') def doc+ OptionalKeyWithOmittedDefaultCodec key valueCodec' def doc ->+ OptionalKeyWithOmittedDefaultCodec key (optionalKeys valueCodec') def doc+ ObjectOfCodec name objectCodec -> ObjectOfCodec name (optionalKeys objectCodec)+ ArrayOfCodec name element -> ArrayOfCodec name (optionalKeys element)+ HashMapCodec element -> HashMapCodec (optionalKeys element)+ MapCodec element -> MapCodec (optionalKeys element)+ BimapCodec from to inner -> BimapCodec from to (optionalKeys inner)+ EitherCodec union left right -> EitherCodec union (optionalKeys left) (optionalKeys right)+ CommentCodec comment inner -> CommentCodec comment (optionalKeys inner)+ ReferenceCodec name inner -> ReferenceCodec name (optionalKeys inner)+ ApCodec function argument -> ApCodec (optionalKeys function) (optionalKeys argument)+ other -> other -- | Keep only the fields in the 'Schema'. Arrays are projected element-wise,
src/Tricorder/API/FieldMask/Schema.hs view
@@ -2,11 +2,14 @@ ( Schema (..) , leaf , nested+ , fromCodec , select , render ) where +import Autodocodec (ValueCodec)+import Autodocodec.Schema (JSONSchema (..), ObjectSchema (..), jsonSchemaVia) import Options.Applicative.Help (Doc) import Data.List qualified as List@@ -30,6 +33,25 @@ nested :: Text -> [(Text, Maybe Schema)] -> (Text, Maybe Schema) nested name fields = (name, Just $ Schema fields)+++-- | The fields of the objects a codec encodes, in the order the codec encodes+-- them. Fields holding objects, or lists of objects, get a nested 'Schema'.+--+-- Codecs that do not encode objects have no fields.+fromCodec :: ValueCodec input output -> Schema+fromCodec = fromMaybe (Schema []) . fromJsonSchema . jsonSchemaVia+ where+ fromJsonSchema = \case+ CommentSchema _ schema -> fromJsonSchema schema+ ArraySchema schema -> fromJsonSchema schema+ ObjectSchema schema -> Just $ Schema $ objectFields schema+ _ -> Nothing++ objectFields = \case+ ObjectKeySchema name _ schema _ -> [(name, fromJsonSchema schema)]+ ObjectAllOfSchema schemas -> concatMap objectFields schemas+ _ -> [] -- | Narrow a 'Schema' down to the fields of a 'FieldMask', keeping the order
+ src/Tricorder/API/JsonSchema.hs view
@@ -0,0 +1,23 @@+module Tricorder.API.JsonSchema (document) where++import Autodocodec (ValueCodec)+import Autodocodec.Schema (jsonSchemaVia)+import Data.Aeson (Value (..), toJSON)+import Data.Aeson.Text (encodeToLazyText)++import Data.Aeson.KeyMap qualified as KeyMap+++-- | The JSON Schema (draft 2020-12) of what a codec encodes, as a document+-- with a title, rendered as JSON.+document :: Text -> ValueCodec input output -> Text+document title codec =+ toStrict $ encodeToLazyText $ case toJSON $ jsonSchemaVia codec of+ Object fields -> Object $ KeyMap.union header fields+ schema -> schema+ where+ header =+ KeyMap.fromList+ [ ("$schema", toJSON @Text "https://json-schema.org/draft/2020-12/schema")+ , ("title", toJSON title)+ ]
+ src/Tricorder/API/Response.hs view
@@ -0,0 +1,84 @@+module Tricorder.API.Response+ ( Response (..)+ , MessageWithLoc (..)+ , codec+ )+where++import Autodocodec+ ( Autodocodec (..)+ , ValueCodec+ , dimapCodec+ , disjointEitherCodec+ , object+ , requiredField+ , requiredFieldWith+ , (.=)+ )+import Data.Aeson (FromJSON, ToJSON)++import Autodocodec qualified+++-- | The envelope around the JSON output of commands: the payload on success,+-- or why there is none.+data Response a+ = Error MessageWithLoc+ | Pending MessageWithLoc+ | Success a+ deriving stock (Eq, Functor, Generic, Show)+++instance Applicative Response where+ pure = Success+ Error message <*> _ = Error message+ _ <*> Error message = Error message+ Pending message <*> _ = Pending message+ _ <*> Pending message = Pending message+ Success f <*> Success a = Success $ f a+++instance Monad Response where+ Error message >>= _ = Error message+ Pending message >>= _ = Pending message+ Success a >>= f = f a+++-- | Exactly one of @success@, @pending@ or @error@, given the codec of the+-- payload.+codec :: ValueCodec input output -> ValueCodec (Response input) (Response output)+codec payload =+ dimapCodec fromEither toEither+ $ disjointEitherCodec+ (object "Error" $ requiredField "error" "The build or tests failed, or the request was invalid.")+ $ disjointEitherCodec+ (object "Pending" $ requiredField "pending" "The build or tests are still running.")+ (object "Success" $ requiredFieldWith "success" payload "The result.")+ where+ fromEither = \case+ Left message -> Error message+ Right (Left message) -> Pending message+ Right (Right a) -> Success a+ toEither = \case+ Error message -> Left message+ Pending message -> Right $ Left message+ Success a -> Right $ Right a+++data MessageWithLoc = MessageWithLoc+ { location :: Text+ , message :: Text+ }+ deriving stock (Eq, Generic, Show)+ deriving (FromJSON, ToJSON) via Autodocodec MessageWithLoc+++instance Autodocodec.HasCodec MessageWithLoc where+ codec =+ object "MessageWithLoc"+ $ MessageWithLoc+ <$> requiredField+ "location"+ "Where the message comes from, e.g. `build`, `postBuild`, `finished` or `arguments`."+ .= (.location)+ <*> requiredField "message" "A human-readable description." .= (.message)
src/Tricorder/API/Test/Args.hs view
@@ -1,5 +1,6 @@ module Tricorder.API.Test.Args (parser) where +import Autodocodec (HasCodec (..)) import Options.Applicative ( Parser , ParserInfo@@ -9,6 +10,8 @@ , helpDoc , hsubparser , info+ , infoOption+ , long , metavar , progDesc , strArgument@@ -18,16 +21,21 @@ import Options.Applicative.Help.Pretty qualified as Doc import Tricorder.API.Test (Command)+import Tricorder.API.Test.SuiteView (SuiteView) import Tricorder.API.FieldMask qualified as FieldMask import Tricorder.API.FieldMask.Args qualified as FieldMask.Args+import Tricorder.API.FieldMask.Projection qualified as FieldMask.Projection import Tricorder.API.FieldMask.Schema qualified as FieldMask (Schema (..)) import Tricorder.API.FieldMask.Schema qualified as FieldMask.Schema import Tricorder.API.IfBuildIsPending.Args qualified as IfBuildIsPending.Args import Tricorder.API.IfDaemonIsStopped.Args qualified as IfDaemonIsStopped.Args+import Tricorder.API.JsonSchema qualified as JsonSchema import Tricorder.API.OutputFormat.Args qualified as OutputFormat.Args+import Tricorder.API.Response qualified as Response import Tricorder.API.Test qualified as Test import Tricorder.API.Test.SuiteView.Schema qualified as SuiteView.Schema+import Tricorder.API.Test.SuitesResponse qualified as SuitesResponse import Tricorder.API.TestFilter.Args qualified as TestFilter.Args @@ -42,7 +50,7 @@ $ command "suites" ( info- suitesParser+ (suitesParser <**> helpJson) ( progDesc "Show test suites, their test cases and output." <> footer suitesFooter )@@ -54,7 +62,7 @@ fmap Test.Suites $ Test.SuitesOptions <$> many (strArgument (metavar "TEST-TARGET..." <> help "Test suites to show (default: all)"))- <*> TestFilter.Args.parser (help "Show only failed test suites, and only their failed test cases")+ <*> TestFilter.Args.parser (help "Show only failed test suites, and only their failed test cases.") <*> FieldMask.Args.parser ( helpDoc $ Just@@ -79,6 +87,19 @@ <*> OutputFormat.Args.parser <*> IfBuildIsPending.Args.parser <*> IfDaemonIsStopped.Args.parser+++helpJson :: Parser (a -> a)+helpJson =+ infoOption+ ( toString+ $ JsonSchema.document "tricorder test suites --json"+ $ Response.codec+ $ SuitesResponse.codec+ $ FieldMask.Projection.optionalKeys+ $ codec @SuiteView+ )+ (long "help-json" <> help "Show the JSON Schema of the output of --json and exit.") suitesFooter :: String
src/Tricorder/API/Test/SuiteView.hs view
@@ -6,9 +6,22 @@ ) where -import Atelier.Time (AsRawUnit, Millisecond)-import Atelier.Types.JSON.QuietSnake (QuietSnake (..))-import Data.Aeson (ToJSON (..))+import Atelier.Time (AsRawUnit (..), Millisecond)+import Autodocodec+ ( Autodocodec (..)+ , Bounds (..)+ , HasCodec (..)+ , JSONCodec+ , boundedEnumCodec+ , dimapCodec+ , integerWithBoundsCodec+ , object+ , optionalField+ , optionalFieldWith+ , requiredField+ , (.=)+ )+import Data.Aeson (ToJSON) -- | Fields that do not apply to a suite's 'Status' are 'Nothing', and are@@ -24,28 +37,80 @@ , cases :: Maybe [CaseView] } deriving stock (Eq, Generic, Show)- deriving (ToJSON) via QuietSnake SuiteView+ deriving (ToJSON) via Autodocodec SuiteView +instance HasCodec SuiteView where+ codec =+ object "SuiteView"+ $ SuiteView+ <$> requiredField "name" "The Cabal target of the test suite, e.g. `pkg:test:pkg-test`."+ .= (.name)+ <*> requiredField+ "status"+ "`running` while the suite runs, `errored` if it could not be run, otherwise `passed` or `failed`."+ .= (.status)+ <*> optionalField "error" "Why the suite could not be run. Only for `errored` suites."+ .= (.error)+ <*> optionalFieldWith "passed_cases" countCodec "Number of passed test cases. Only for finished suites."+ .= (.passedCases)+ <*> optionalFieldWith "total_cases" countCodec "Number of test cases. Only for finished suites."+ .= (.totalCases)+ <*> optionalFieldWith+ "duration_ms"+ (dimapCodec (AsRawUnit . fromIntegral) (fromIntegral . (.getAsRawUnit)) countCodec)+ "How long the suite ran, in milliseconds. Only for finished suites."+ .= (.durationMs)+ <*> optionalField "output" "The output of the suite. Only for finished suites."+ .= (.output)+ <*> optionalField "cases" "The test cases of the suite. Only for finished suites."+ .= (.cases)++ data Status = Running | Errored | Passed | Failed- deriving stock (Eq, Generic, Show)- deriving (ToJSON) via QuietSnake Status+ deriving stock (Bounded, Enum, Eq, Generic, Show)+ deriving (ToJSON) via Autodocodec Status +instance HasCodec Status where+ codec = boundedEnumCodec \case+ Running -> "running"+ Errored -> "errored"+ Passed -> "passed"+ Failed -> "failed"++ data CaseView = CaseView { description :: Text , outcome :: Outcome , failure :: Maybe Text } deriving stock (Eq, Generic, Show)- deriving (ToJSON) via QuietSnake CaseView+ deriving (ToJSON) via Autodocodec CaseView +instance HasCodec CaseView where+ codec =+ object "CaseView"+ $ CaseView+ <$> requiredField "description" "The description of the test case." .= (.description)+ <*> requiredField "outcome" "Whether the test case passed." .= (.outcome)+ <*> optionalField "failure" "Why the test case failed. Only for failed test cases." .= (.failure)++ data Outcome = CasePassed | CaseFailed- deriving stock (Eq, Generic, Show)+ deriving stock (Bounded, Enum, Eq, Generic, Show)+ deriving (ToJSON) via Autodocodec Outcome -instance ToJSON Outcome where- toJSON = \case+instance HasCodec Outcome where+ codec = boundedEnumCodec \case CasePassed -> "passed" CaseFailed -> "failed"+++-- | A non-negative integer.+countCodec :: JSONCodec Int+countCodec =+ dimapCodec fromInteger toInteger+ $ integerWithBoundsCodec Bounds {boundsLower = Just 0, boundsUpper = Nothing}
src/Tricorder/API/Test/SuiteView/Schema.hs view
@@ -1,30 +1,17 @@ module Tricorder.API.Test.SuiteView.Schema (defaultFields, schema) where +import Autodocodec (HasCodec (..))+ import Tricorder.API.FieldMask (FieldMask (..))+import Tricorder.API.Test.SuiteView (SuiteView) import Tricorder.API.FieldMask qualified as FieldMask-import Tricorder.API.FieldMask.Schema qualified as FieldMask (Schema (..))+import Tricorder.API.FieldMask.Schema qualified as FieldMask (Schema) import Tricorder.API.FieldMask.Schema qualified as FieldMask.Schema --- | Every field of a 'SuiteView', as named in its JSON encoding. schema :: FieldMask.Schema-schema =- FieldMask.Schema- [ FieldMask.Schema.leaf "name"- , FieldMask.Schema.leaf "status"- , FieldMask.Schema.leaf "error"- , FieldMask.Schema.leaf "passed_cases"- , FieldMask.Schema.leaf "total_cases"- , FieldMask.Schema.leaf "duration_ms"- , FieldMask.Schema.leaf "output"- , FieldMask.Schema.nested- "cases"- [ FieldMask.Schema.leaf "description"- , FieldMask.Schema.leaf "outcome"- , FieldMask.Schema.leaf "failure"- ]- ]+schema = FieldMask.Schema.fromCodec $ codec @SuiteView -- | A summary of each suite, leaving out the (potentially large) test output
+ src/Tricorder/API/Test/SuitesResponse.hs view
@@ -0,0 +1,21 @@+module Tricorder.API.Test.SuitesResponse+ ( SuitesResponse (..)+ , codec+ )+where++import Autodocodec (ValueCodec, listCodec, object, requiredFieldWith, (.=))+++-- | Test suites, each cut down to the requested fields.+newtype SuitesResponse suite = SuitesResponse+ { suites :: [suite]+ }+ deriving stock (Eq, Show)+++codec :: ValueCodec input output -> ValueCodec (SuitesResponse input) (SuitesResponse output)+codec suite =+ object "SuitesResponse"+ $ SuitesResponse+ <$> requiredFieldWith "suites" (listCodec suite) "The requested test suites." .= (.suites)
test/Unit/Tricorder/API/FieldMask/ProjectionSpec.hs view
@@ -1,11 +1,22 @@ module Unit.Tricorder.API.FieldMask.ProjectionSpec (test_Projection) where -import Data.Aeson (Value (..), object, (.=))-import Data.Aeson.Text (encodeToLazyText)+import Autodocodec (object, parseJSONVia, requiredField, toEncodingVia, (.=))+import Autodocodec.Schema (jsonSchemaVia, validateAccordingTo)+import Data.Aeson (Value (..))+import Data.Aeson.Encoding (encodingToLazyByteString)+import Data.Aeson.Types (parseEither) import Test.Tasty (TestTree, testGroup)-import Test.Tasty.HUnit (testCase, (@?=))+import Test.Tasty.HUnit (assertBool, testCase, (@?=)) -import Tricorder.API.FieldMask.Projection (Projection (..), project, renderYaml)+import Data.Aeson qualified as Aeson++import Tricorder.API.FieldMask.Projection+ ( Projection (..)+ , codec+ , optionalKeys+ , project+ , renderYaml+ ) import Tricorder.API.FieldMask.Schema (Schema (..), leaf, nested) @@ -14,6 +25,8 @@ testGroup "Tricorder.API.FieldMask.Projection" [ testGroup "project" testProject+ , testGroup "codec" testCodec+ , testGroup "optionalKeys" testOptionalKeys ] @@ -30,21 +43,63 @@ , testCase "leaves out missing and null fields" do project (Schema [leaf "name", leaf "missing", leaf "error"]) suite @?= PObject [("name", PScalar "suite")]- , testCase "encodes JSON objects in selection order" do- encodeToLazyText (project (Schema [leaf "status", leaf "name"]) suite)- @?= "{\"status\":\"failed\",\"name\":\"suite\"}" , testCase "renders YAML in selection order" do renderYaml (project (Schema [leaf "status", leaf "name"]) suite) @?= "status: failed\nname: suite\n" ]+++testCodec :: [TestTree]+testCodec =+ [ testCase "encodes JSON objects in selection order" do+ encode (Schema [leaf "status", leaf "name"])+ @?= "{\"status\":\"failed\",\"name\":\"suite\"}"+ , testCase "encodes nested fields of every element of an array" do+ encode (Schema [nested "cases" [leaf "outcome", leaf "description"]])+ @?= "{\"cases\":[{\"outcome\":\"passed\",\"description\":\"a\"},{\"outcome\":\"failed\",\"description\":\"b\"}]}"+ , testCase "leaves out fields missing from the projection" do+ encode (Schema [leaf "name", leaf "error"]) @?= "{\"name\":\"suite\"}"+ , testCase "fails to decode, even what it encoded" do+ assertBool "decoded" $ isLeft $ parseEither (parseJSONVia $ codec $ Schema [leaf "name"]) suite+ ] where- suite =- object- [ "name" .= ("suite" :: Text)- , "status" .= ("failed" :: Text)- , "error" .= Null- , "cases"- .= [ object ["description" .= ("a" :: Text), "outcome" .= ("passed" :: Text)]- , object ["description" .= ("b" :: Text), "outcome" .= ("failed" :: Text)]- ]- ]+ encode selection = encodingToLazyByteString $ toEncodingVia (codec selection) $ project selection suite+++testOptionalKeys :: [TestTree]+testOptionalKeys =+ [ testCase "accepts objects missing required keys" do+ assertBool "missing key rejected"+ $ validateAccordingTo+ (Aeson.object ["name" Aeson..= ("suite" :: Text)])+ (jsonSchemaVia $ optionalKeys pair)+ , testCase "keeps the types of the keys" do+ assertBool "wrong type accepted"+ $ not+ $ validateAccordingTo+ (Aeson.object ["count" Aeson..= ("one" :: Text)])+ (jsonSchemaVia $ optionalKeys pair)+ , testCase "leaves the schema of the original codec as-is" do+ assertBool "missing key accepted"+ $ not+ $ validateAccordingTo (Aeson.object ["name" Aeson..= ("suite" :: Text)]) (jsonSchemaVia pair)+ ]+ where+ pair =+ object "Pair"+ $ (,)+ <$> requiredField @Text "name" "a name" .= fst+ <*> requiredField @Int "count" "a count" .= snd+++suite :: Value+suite =+ Aeson.object+ [ "name" Aeson..= ("suite" :: Text)+ , "status" Aeson..= ("failed" :: Text)+ , "error" Aeson..= Null+ , "cases"+ Aeson..= [ Aeson.object ["description" Aeson..= ("a" :: Text), "outcome" Aeson..= ("passed" :: Text)]+ , Aeson.object ["description" Aeson..= ("b" :: Text), "outcome" Aeson..= ("failed" :: Text)]+ ]+ ]
test/Unit/Tricorder/API/FieldMask/SchemaSpec.hs view
@@ -1,12 +1,22 @@ module Unit.Tricorder.API.FieldMask.SchemaSpec (test_Schema) where +import Autodocodec+ ( JSONCodec+ , listCodec+ , object+ , optionalFieldWith+ , requiredField+ , requiredFieldWith+ , textCodec+ , (.=)+ ) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=)) import Data.Text qualified as T import Tricorder.API.FieldMask.Args (parse)-import Tricorder.API.FieldMask.Schema (Schema (..), leaf, nested, select)+import Tricorder.API.FieldMask.Schema (Schema (..), fromCodec, leaf, nested, select) test_Schema :: TestTree@@ -14,6 +24,7 @@ testGroup "Tricorder.API.FieldMask.Schema" [ testGroup "select" testSelect+ , testGroup "fromCodec" testFromCodec ] @@ -34,6 +45,32 @@ ] where select' input = select schema =<< parse input+++testFromCodec :: [TestTree]+testFromCodec =+ [ testCase "lists the fields of an object in codec order, nesting through lists of objects" do+ fromCodec suiteCodec+ @?= Schema [leaf "name", leaf "tags", nested "cases" [leaf "description", leaf "outcome"]]+ , testCase "a codec of something other than an object has no fields" do+ fromCodec textCodec @?= Schema []+ ]+ where+ suiteCodec :: JSONCodec (Text, [Text], Maybe [(Text, Text)])+ suiteCodec =+ object "Suite"+ $ (,,)+ <$> requiredField "name" "the name" .= (\(name, _, _) -> name)+ <*> requiredField "tags" "the tags" .= (\(_, tags, _) -> tags)+ <*> optionalFieldWith "cases" (listCodec caseCodec) "the cases" .= (\(_, _, cases) -> cases)+++caseCodec :: JSONCodec (Text, Text)+caseCodec =+ object "Case"+ $ (,)+ <$> requiredFieldWith "description" textCodec "the description" .= fst+ <*> requiredFieldWith "outcome" textCodec "the outcome" .= snd schema :: Schema
+ test/Unit/Tricorder/API/ResponseSpec.hs view
@@ -0,0 +1,41 @@+module Unit.Tricorder.API.ResponseSpec (test_Response) where++import Autodocodec (JSONCodec, toJSONVia)+import Autodocodec.Schema (jsonSchemaVia, validateAccordingTo)+import Data.Aeson (object, (.=))+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, testCase, (@?=))++import Autodocodec qualified++import Tricorder.API.Response (MessageWithLoc (..), Response (..), codec)+++test_Response :: TestTree+test_Response =+ testGroup+ "Tricorder.API.Response"+ [ testCase "encodes each constructor as an object with a single key" do+ toJSONVia responseCodec <$> [Error message, Pending message, Success 1]+ @?= [ object ["error" .= messageJson]+ , object ["pending" .= messageJson]+ , object ["success" .= (1 :: Int)]+ ]+ , testCase "every constructor matches the schema" do+ for_ [Error message, Pending message, Success 1] \response ->+ assertBool (show response) $ validateAccordingTo (toJSONVia responseCodec response) schema+ , testCase "the schema rejects more than one key" do+ assertBool "accepted"+ $ not+ $ validateAccordingTo (object ["error" .= messageJson, "pending" .= messageJson]) schema+ , testCase "the schema checks the payload" do+ assertBool "accepted" $ not $ validateAccordingTo (object ["success" .= ("one" :: Text)]) schema+ ]+ where+ message = MessageWithLoc "build" "message"+ messageJson = object ["location" .= ("build" :: Text), "message" .= ("message" :: Text)]++ responseCodec :: JSONCodec (Response Int)+ responseCodec = codec Autodocodec.codec++ schema = jsonSchemaVia responseCodec
+ test/Unit/Tricorder/API/SuitesResponseSpec.hs view
@@ -0,0 +1,98 @@+module Unit.Tricorder.API.SuitesResponseSpec (test_SuitesResponse) where++import Atelier.Time (AsRawUnit (..))+import Autodocodec (HasCodec (..), toEncodingVia, toJSONVia)+import Autodocodec.Schema (jsonSchemaVia, validateAccordingTo)+import Data.Aeson (Value, eitherDecode, toJSON)+import Data.Aeson.Encoding (encodingToLazyByteString)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++import Tricorder.API.FieldMask.Args (parse)+import Tricorder.API.Response (Response (..))+import Tricorder.API.Test.SuiteView (CaseView (..), Outcome (..), Status (..), SuiteView (..))+import Tricorder.API.Test.SuitesResponse (SuitesResponse (..))++import Tricorder.API.FieldMask.Projection qualified as Projection+import Tricorder.API.FieldMask.Schema qualified as FieldMask.Schema+import Tricorder.API.Response qualified as Response+import Tricorder.API.Test.SuiteView.Schema qualified as SuiteView.Schema+import Tricorder.API.Test.SuitesResponse qualified as SuitesResponse+++test_SuitesResponse :: TestTree+test_SuitesResponse =+ testGroup+ "Tricorder.API.Test.SuitesResponse"+ [ testCase "projected suites match the schema of any projection" do+ for_+ [ "name"+ , "status,name"+ , "name,status,error,passed_cases,total_cases,duration_ms"+ , "output"+ , "cases"+ , "name,cases(outcome)"+ ]+ \fields -> do+ encoded <- encodeSuites fields+ assertBool (toString fields) $ validateAccordingTo encoded projectionSchema+ , testCase "encodes fields in the order they were selected in" do+ selection <- either (assertFailure . toString) pure $ select "status,name"+ encodingToLazyByteString+ (toEncodingVia (suitesCodec selection) $ Success $ SuitesResponse [projected selection runningView])+ @?= "{\"success\":{\"suites\":[{\"status\":\"running\",\"name\":\"test:suite\"}]}}"+ , testCase "the schema rejects unknown values" do+ assertBool "accepted"+ $ not+ $ validateAccordingTo+ (toJSONVia (Response.codec $ SuitesResponse.codec codec) $ Success $ SuitesResponse [toJSON @Int 1])+ projectionSchema+ ]+ where+ projectionSchema =+ jsonSchemaVia $ Response.codec $ SuitesResponse.codec $ Projection.optionalKeys $ codec @SuiteView++ encodeSuites fields = do+ selection <- either (assertFailure . toString) pure $ select fields+ either assertFailure pure+ $ eitherDecode @Value+ $ encodingToLazyByteString+ $ toEncodingVia (suitesCodec selection)+ $ Success+ $ SuitesResponse+ $ projected selection <$> [finishedView, erroredView, runningView]++ select fields = FieldMask.Schema.select SuiteView.Schema.schema =<< parse fields+ projected selection = Projection.project selection . toJSON+ suitesCodec = Response.codec . SuitesResponse.codec . Projection.codec+++finishedView :: SuiteView+finishedView =+ SuiteView+ { name = "test:suite"+ , status = Failed+ , error = Nothing+ , passedCases = Just 1+ , totalCases = Just 2+ , durationMs = Just $ AsRawUnit 5+ , output = Just "output"+ , cases = Just [CaseView "a" CasePassed Nothing, CaseView "b" CaseFailed (Just "failure")]+ }+++erroredView :: SuiteView+erroredView =+ finishedView+ { status = Errored+ , error = Just "error"+ , passedCases = Nothing+ , totalCases = Nothing+ , durationMs = Nothing+ , output = Nothing+ , cases = Nothing+ }+++runningView :: SuiteView+runningView = erroredView {status = Running, error = Nothing}
tricorder-types.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: tricorder-types-version: 1.0.0.0+version: 1.1.0.0 synopsis: Shared domain types for various Tricorder components description: Shared domain types for various Tricorder components like [Tricorder itself](https://hackage.haskell.org/package/tricorder) and@@ -49,10 +49,13 @@ Tricorder.API.IfDaemonIsStopped.Args Tricorder.API.IfThereArePendingQueries Tricorder.API.IfThereArePendingQueries.Args+ Tricorder.API.JsonSchema Tricorder.API.OutputFormat Tricorder.API.OutputFormat.Args+ Tricorder.API.Response Tricorder.API.Test Tricorder.API.Test.Args+ Tricorder.API.Test.SuitesResponse Tricorder.API.Test.SuiteView Tricorder.API.Test.SuiteView.Schema Tricorder.API.TestFilter@@ -87,8 +90,10 @@ ghc-options: -Weverything -Wno-unsafe -Wno-missing-safe-haskell-mode -Wno-monomorphism-restriction -Wno-missing-kind-signatures -Wno-missing-local-signatures -Wno-missing-import-lists -Wno-implicit-prelude -Wno-unticked-promoted-constructors -Wno-unused-packages -Wno-all-missed-specialisations -Wno-missed-specialisations build-depends: aeson >=2.2 && <2.4- , atelier-core ==1.0.*+ , atelier-core ==1.1.* , atelier-prelude ==0.4.*+ , autodocodec >=0.6 && <0.8+ , autodocodec-schema ==0.2.* , base >=4.18 && <4.23 , effectful ==2.7.* , megaparsec >=9.7 && <9.9@@ -108,6 +113,8 @@ Unit.Tricorder.API.FieldMask.ArgsSpec Unit.Tricorder.API.FieldMask.ProjectionSpec Unit.Tricorder.API.FieldMask.SchemaSpec+ Unit.Tricorder.API.ResponseSpec+ Unit.Tricorder.API.SuitesResponseSpec Unit.Tricorder.API.SuiteView.SchemaSpec Paths_tricorder_types autogen-modules:@@ -136,8 +143,10 @@ tasty-discover:tasty-discover build-depends: aeson >=2.2 && <2.4- , atelier-core ==1.0.*+ , atelier-core ==1.1.* , atelier-prelude ==0.4.*+ , autodocodec >=0.6 && <0.8+ , autodocodec-schema ==0.2.* , base >=4.18 && <4.23 , tasty ==1.5.* , tasty-discover ==5.2.*