-- SPDX-FileCopyrightText: 2022 Oxhead Alpha
-- SPDX-License-Identifier: LicenseRef-MIT-OA

-- | Internal utilities for unit testing.

module Test.Cleveland.Michelson.Internal.Entrypoints
  ( EPList
  , EPMismatch(.., EPComparisonResultOK)
  , ignoreExtraEntrypoints
  , compareEntrypoints
  , contractMatchesEntrypoints
  , contractCoversEntrypoints
  , testContractEntrypoints
  , assertEPComparisonSuccessful
  , michelsonRoundtripContract
  , michelineRoundtripContract
  ) where

import Data.Aeson (eitherDecode, encode)
import Data.Map qualified as Map
import Fmt (Buildable(..), blockMapF, nameF, pretty, unlinesF)
import Test.HUnit (Assertion, assertFailure)
import Test.Tasty (TestName, TestTree, testGroup)
import Test.Tasty.HUnit (testCase)

import Morley.Micheline (fromExpression, toExpression)
import Morley.Michelson.Parser (MichelsonSource(MSUnspecified))
import Morley.Michelson.Printer (printUntypedContract)
import Morley.Michelson.Runtime (parseExpandContract)
import Morley.Michelson.TypeCheck (TCError, mkSomeParamType)
import Morley.Michelson.Untyped hiding (Contract)
import Morley.Michelson.Untyped qualified as U
import Morley.Util.MismatchError (MismatchError(..))
import Morley.Util.Named

-- | Convenience type synonym for a list of pairs of entrypoint names and types
type EPList = [(EpName, U.Ty)]

-- | A pattern syononym for no mismatches
pattern EPComparisonResultOK :: EPMismatch
pattern $mEPComparisonResultOK :: forall r. EPMismatch -> (Void# -> r) -> (Void# -> r) -> r
EPComparisonResultOK <- EPMismatch [] [] []

-- | Entrypoint comparison mismatch report
data EPMismatch = EPMismatch
  { EPMismatch -> EPList
epmmExtra :: EPList
    -- ^ Extraneous entrypoints, i.e. those that exist in the actual contract, but not
    -- in the specification
  , EPMismatch -> EPList
epmmMissing :: EPList
    -- ^ Missing entrypoints, i.e. those that exist in the specification, but not the
    -- actual contract
  , EPMismatch -> [(EpName, MismatchError Ty)]
epmmTypeMismatch :: [(EpName, MismatchError Ty)]
    -- ^ Entrypoints that exist in both the contract and the specification, but types do not
    -- match.
  }

instance Buildable EPMismatch where
  build :: EPMismatch -> Builder
build EPMismatch
EPComparisonResultOK = Builder
"Entrypoints match specificaton"
  build EPMismatch{EPList
[(EpName, MismatchError Ty)]
epmmTypeMismatch :: [(EpName, MismatchError Ty)]
epmmMissing :: EPList
epmmExtra :: EPList
epmmTypeMismatch :: EPMismatch -> [(EpName, MismatchError Ty)]
epmmMissing :: EPMismatch -> EPList
epmmExtra :: EPMismatch -> EPList
..} = Builder -> Builder -> Builder
nameF Builder
"Entrypoints do not match specification" (Builder -> Builder) -> Builder -> Builder
forall a b. (a -> b) -> a -> b
$
    [Builder] -> Builder
forall (f :: * -> *) a. (Foldable f, Buildable a) => f a -> Builder
unlinesF ([Builder] -> Builder) -> [Builder] -> Builder
forall a b. (a -> b) -> a -> b
$ (Builder -> Bool) -> [Builder] -> [Builder]
forall a. (a -> Bool) -> [a] -> [a]
filter (Builder -> Builder -> Bool
forall a. Eq a => a -> a -> Bool
/=Builder
forall a. Monoid a => a
mempty) [Builder
extra, Builder
missing, Builder
typemm]
    where
    extra :: Builder
extra | EPList -> Bool
forall t. Container t => t -> Bool
null EPList
epmmExtra = Builder
forall a. Monoid a => a
mempty
          | Bool
otherwise = Builder -> Builder -> Builder
nameF Builder
"Extraneous entrypoints in the contract" (Builder -> Builder) -> Builder -> Builder
forall a b. (a -> b) -> a -> b
$ EPList -> Builder
forall t k v.
(IsList t, Item t ~ (k, v), Buildable k, Buildable v) =>
t -> Builder
blockMapF EPList
epmmExtra
    missing :: Builder
missing | EPList -> Bool
forall t. Container t => t -> Bool
null EPList
epmmMissing = Builder
forall a. Monoid a => a
mempty
            | Bool
otherwise = Builder -> Builder -> Builder
nameF Builder
"Missing entrypoints in the contract" (Builder -> Builder) -> Builder -> Builder
forall a b. (a -> b) -> a -> b
$ EPList -> Builder
forall t k v.
(IsList t, Item t ~ (k, v), Buildable k, Buildable v) =>
t -> Builder
blockMapF EPList
epmmMissing
    typemm :: Builder
typemm | [(EpName, MismatchError Ty)] -> Bool
forall t. Container t => t -> Bool
null [(EpName, MismatchError Ty)]
epmmTypeMismatch = Builder
forall a. Monoid a => a
mempty
           | Bool
otherwise = Builder -> Builder -> Builder
nameF Builder
"Type mismatch in entrypoints" (Builder -> Builder) -> Builder -> Builder
forall a b. (a -> b) -> a -> b
$ [(EpName, MismatchError Ty)] -> Builder
forall t k v.
(IsList t, Item t ~ (k, v), Buildable k, Buildable v) =>
t -> Builder
blockMapF [(EpName, MismatchError Ty)]
epmmTypeMismatch

-- | Ignore extraneous entrypoint names in 'EPMismatch'. Essentially sets
-- 'epmmExtra' to @[]@.
ignoreExtraEntrypoints :: EPMismatch -> EPMismatch
ignoreExtraEntrypoints :: EPMismatch -> EPMismatch
ignoreExtraEntrypoints EPMismatch
mm = EPMismatch
mm{ epmmExtra :: EPList
epmmExtra = [] }

-- | Compare two sets of entrypoints. Accepts ordered 'Map's to enforce sorting order.
compareEntrypoints :: "expected" :! Map EpName U.Ty -> "actual" :! (Map EpName U.Ty) -> EPMismatch
compareEntrypoints :: ("expected" :! Map EpName Ty)
-> ("actual" :! Map EpName Ty) -> EPMismatch
compareEntrypoints (Name "expected" -> ("expected" :! Map EpName Ty) -> Map EpName Ty
forall (name :: Symbol) a. Name name -> (name :! a) -> a
arg IsLabel "expected" (Name "expected")
Name "expected"
#expected -> Map EpName Ty
expected) (Name "actual" -> ("actual" :! Map EpName Ty) -> Map EpName Ty
forall (name :: Symbol) a. Name name -> (name :! a) -> a
arg IsLabel "actual" (Name "actual")
Name "actual"
#actual -> Map EpName Ty
actual) = EPMismatch :: EPList -> EPList -> [(EpName, MismatchError Ty)] -> EPMismatch
EPMismatch{EPList
[(EpName, MismatchError Ty)]
epmmTypeMismatch :: [(EpName, MismatchError Ty)]
epmmMissing :: EPList
epmmExtra :: EPList
epmmTypeMismatch :: [(EpName, MismatchError Ty)]
epmmMissing :: EPList
epmmExtra :: EPList
..}
  where
    epmmExtra :: EPList
epmmExtra = Map EpName Ty -> EPList
forall k a. Map k a -> [(k, a)]
Map.toList (Map EpName Ty -> EPList) -> Map EpName Ty -> EPList
forall a b. (a -> b) -> a -> b
$ Map EpName Ty -> Map EpName Ty -> Map EpName Ty
forall k a b. Ord k => Map k a -> Map k b -> Map k a
Map.difference Map EpName Ty
actual Map EpName Ty
expected
    epmmMissing :: EPList
epmmMissing = Map EpName Ty -> EPList
forall k a. Map k a -> [(k, a)]
Map.toList (Map EpName Ty -> EPList) -> Map EpName Ty -> EPList
forall a b. (a -> b) -> a -> b
$ Map EpName Ty -> Map EpName Ty -> Map EpName Ty
forall k a b. Ord k => Map k a -> Map k b -> Map k a
Map.difference Map EpName Ty
expected Map EpName Ty
actual
    inBoth :: Map EpName (Ty, Ty)
inBoth = (Ty -> Ty -> (Ty, Ty))
-> Map EpName Ty -> Map EpName Ty -> Map EpName (Ty, Ty)
forall k a b c.
Ord k =>
(a -> b -> c) -> Map k a -> Map k b -> Map k c
Map.intersectionWith (,) Map EpName Ty
expected Map EpName Ty
actual
    epmmTypeMismatch :: [(EpName, MismatchError Ty)]
epmmTypeMismatch = Map EpName (MismatchError Ty) -> [(EpName, MismatchError Ty)]
forall k a. Map k a -> [(k, a)]
Map.toList (Map EpName (MismatchError Ty) -> [(EpName, MismatchError Ty)])
-> Map EpName (MismatchError Ty) -> [(EpName, MismatchError Ty)]
forall a b. (a -> b) -> a -> b
$ (((Ty, Ty) -> Maybe (MismatchError Ty))
 -> Map EpName (Ty, Ty) -> Map EpName (MismatchError Ty))
-> Map EpName (Ty, Ty)
-> ((Ty, Ty) -> Maybe (MismatchError Ty))
-> Map EpName (MismatchError Ty)
forall a b c. (a -> b -> c) -> b -> a -> c
flip ((Ty, Ty) -> Maybe (MismatchError Ty))
-> Map EpName (Ty, Ty) -> Map EpName (MismatchError Ty)
forall a b k. (a -> Maybe b) -> Map k a -> Map k b
Map.mapMaybe Map EpName (Ty, Ty)
inBoth \(Ty
e, Ty
a) ->
      if Ty
e Ty -> Ty -> Bool
forall a. Eq a => a -> a -> Bool
/= Ty
a
      then MismatchError Ty -> Maybe (MismatchError Ty)
forall a. a -> Maybe a
Just (MismatchError Ty -> Maybe (MismatchError Ty))
-> MismatchError Ty -> Maybe (MismatchError Ty)
forall a b. (a -> b) -> a -> b
$ MkMismatchError :: forall a. a -> a -> MismatchError a
MkMismatchError { meExpected :: Ty
meExpected = Ty
e, meActual :: Ty
meActual = Ty
a }
      else Maybe (MismatchError Ty)
forall a. Maybe a
Nothing

-- | Check if the contract exactly matches the given entrypoints. Will report both
-- missing and extraneous entrypoint names, and type mismatches.
contractMatchesEntrypoints :: U.Contract -> Map EpName U.Ty -> Either TCError EPMismatch
contractMatchesEntrypoints :: Contract -> Map EpName Ty -> Either TCError EPMismatch
contractMatchesEntrypoints (Contract -> ParameterType
forall op. Contract' op -> ParameterType
contractParameter -> ParameterType
pt) Map EpName Ty
expected = case ParameterType -> Either TCError SomeParamType
mkSomeParamType ParameterType
pt of
  Right{} -> EPMismatch -> Either TCError EPMismatch
forall a b. b -> Either a b
Right (EPMismatch -> Either TCError EPMismatch)
-> EPMismatch -> Either TCError EPMismatch
forall a b. (a -> b) -> a -> b
$ ("expected" :! Map EpName Ty)
-> ("actual" :! Map EpName Ty) -> EPMismatch
compareEntrypoints (IsLabel "expected" (Name "expected")
Name "expected"
#expected Name "expected" -> Map EpName Ty -> "expected" :! Map EpName Ty
forall (name :: Symbol) a. Name name -> a -> NamedF Identity a name
:! Map EpName Ty
expected) (IsLabel "actual" (Name "actual")
Name "actual"
#actual Name "actual" -> Map EpName Ty -> "actual" :! Map EpName Ty
forall (name :: Symbol) a. Name name -> a -> NamedF Identity a name
:! ParameterType -> Map EpName Ty
mkEntrypointsMap ParameterType
pt)
  Left TCError
err -> TCError -> Either TCError EPMismatch
forall a b. a -> Either a b
Left TCError
err

-- | Check if the contract contains the entrypoints given in spec (with matching types).
-- Ignores any additional entrypoints present in the contract.
contractCoversEntrypoints :: U.Contract -> Map EpName U.Ty -> Either TCError EPMismatch
contractCoversEntrypoints :: Contract -> Map EpName Ty -> Either TCError EPMismatch
contractCoversEntrypoints = (EPMismatch -> EPMismatch)
-> Either TCError EPMismatch -> Either TCError EPMismatch
forall (p :: * -> * -> *) b c a.
Bifunctor p =>
(b -> c) -> p a b -> p a c
second EPMismatch -> EPMismatch
ignoreExtraEntrypoints (Either TCError EPMismatch -> Either TCError EPMismatch)
-> (Contract -> Map EpName Ty -> Either TCError EPMismatch)
-> Contract
-> Map EpName Ty
-> Either TCError EPMismatch
forall a b c. SuperComposition a b c => a -> b -> c
... Contract -> Map EpName Ty -> Either TCError EPMismatch
contractMatchesEntrypoints

-- | Turn 'Either' 'TCError' 'EPMismatch' into an 'Assertion'
assertEPComparisonSuccessful :: Either TCError EPMismatch -> Assertion
assertEPComparisonSuccessful :: Either TCError EPMismatch -> Assertion
assertEPComparisonSuccessful = \case
  Right EPMismatch
EPComparisonResultOK -> Assertion
forall (f :: * -> *). Applicative f => f ()
pass
  Left TCError
tcerr -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ TCError -> String
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty TCError
tcerr
  Right EPMismatch
mismatch -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ EPMismatch -> String
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty EPMismatch
mismatch

-- | Expect the contract to match with the entrypoints given in spec (with matching types).
-- Comparison is defined by the first argument; use @ignoreExtraEntrypoints@ for cover test,
-- @id@ for match test.
--
-- Also tests if the same holds after Michelson and Micheline roundtrips of the contract.
testContractEntrypoints
  :: (EPMismatch -> EPMismatch)
  -> TestName
  -> U.Contract
  -> Map EpName U.Ty
  -> TestTree
testContractEntrypoints :: (EPMismatch -> EPMismatch)
-> String -> Contract -> Map EpName Ty -> TestTree
testContractEntrypoints EPMismatch -> EPMismatch
compMode String
name Contract
contract Map EpName Ty
spec
  = String -> [TestTree] -> TestTree
testGroup String
name
      [ String -> Assertion -> TestTree
testCase String
"Contract itself" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ (Contract -> Contract) -> Assertion
test Contract -> Contract
forall a. a -> a
id
      , String -> Assertion -> TestTree
testCase String
"After Michelson roundtrip" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ (Contract -> Contract) -> Assertion
test HasCallStack => Contract -> Contract
Contract -> Contract
michelsonRoundtripContract
      , String -> Assertion -> TestTree
testCase String
"After Micheline roundtrip" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ (Contract -> Contract) -> Assertion
test HasCallStack => Contract -> Contract
Contract -> Contract
michelineRoundtripContract
      ]
  where test :: (Contract -> Contract) -> Assertion
test Contract -> Contract
modifier = Either TCError EPMismatch -> Assertion
assertEPComparisonSuccessful (Either TCError EPMismatch -> Assertion)
-> Either TCError EPMismatch -> Assertion
forall a b. (a -> b) -> a -> b
$ (EPMismatch -> EPMismatch)
-> Either TCError EPMismatch -> Either TCError EPMismatch
forall (p :: * -> * -> *) b c a.
Bifunctor p =>
(b -> c) -> p a b -> p a c
second EPMismatch -> EPMismatch
compMode (Either TCError EPMismatch -> Either TCError EPMismatch)
-> Either TCError EPMismatch -> Either TCError EPMismatch
forall a b. (a -> b) -> a -> b
$ Contract -> Map EpName Ty -> Either TCError EPMismatch
contractMatchesEntrypoints (Contract -> Contract
modifier Contract
contract) Map EpName Ty
spec

-- | Round-trip the contract through Michelson text representation.
--
-- This is useful if you're intending to use the contract with Michelson text output and want to
-- check if that output satisfies tests (which /should be/ the same for internal representation
-- and output, but bugs happen)
michelsonRoundtripContract :: HasCallStack => U.Contract -> U.Contract
michelsonRoundtripContract :: Contract -> Contract
michelsonRoundtripContract Contract
contract =
  Either ParserException Contract -> Contract
forall a b. (HasCallStack, Buildable a) => Either a b -> b
unsafe (Either ParserException Contract -> Contract)
-> (Text -> Either ParserException Contract) -> Text -> Contract
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MichelsonSource -> Text -> Either ParserException Contract
parseExpandContract MichelsonSource
MSUnspecified (Text -> Either ParserException Contract)
-> (Text -> Text) -> Text -> Either ParserException Contract
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
forall a. ToText a => a -> Text
toText
    (Text -> Contract) -> Text -> Contract
forall a b. (a -> b) -> a -> b
$ Bool -> Contract -> Text
forall op. RenderDoc op => Bool -> Contract' op -> Text
printUntypedContract Bool
True Contract
contract

-- | Round-trip the contract through Micheline JSON representation.
--
-- This is useful if you're intending to use the contract with Micheline JSON output and want to
-- check if that output satisfies tests (which /should be/ the same for internal representation
-- and output, but bugs happen)
michelineRoundtripContract :: HasCallStack => U.Contract -> U.Contract
michelineRoundtripContract :: Contract -> Contract
michelineRoundtripContract Contract
contract =
  Either FromExpressionError Contract -> Contract
forall a b. (HasCallStack, Buildable a) => Either a b -> b
unsafe (Either FromExpressionError Contract -> Contract)
-> (Expression -> Either FromExpressionError Contract)
-> Expression
-> Contract
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Expression -> Either FromExpressionError Contract
forall a.
FromExpression a =>
Expression -> Either FromExpressionError a
fromExpression
    (Expression -> Either FromExpressionError Contract)
-> (Expression -> Expression)
-> Expression
-> Either FromExpressionError Contract
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> Expression)
-> (Expression -> Expression)
-> Either String Expression
-> Expression
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Text -> Expression
forall a. HasCallStack => Text -> a
error (Text -> Expression) -> (String -> Text) -> String -> Expression
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
forall a. ToText a => a -> Text
toText) Expression -> Expression
forall a. a -> a
id
    (Either String Expression -> Expression)
-> (Expression -> Either String Expression)
-> Expression
-> Expression
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either String Expression
forall a. FromJSON a => ByteString -> Either String a
eitherDecode (ByteString -> Either String Expression)
-> (Expression -> ByteString)
-> Expression
-> Either String Expression
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Expression -> ByteString
forall a. ToJSON a => a -> ByteString
encode
    (Expression -> Contract) -> Expression -> Contract
forall a b. (a -> b) -> a -> b
$ Contract -> Expression
forall a. ToExpression a => a -> Expression
toExpression Contract
contract