Unit Testing DAML functions

I am trying to write unit tests for all the functions I have written in DAML. I am aware that if a function returns something I will be able to assert if it is equal or not equal to a particular value using the DA.Assert module.

However, i have some functions that may throw runtime errors and I was wondering if there was a to test that. For eg. suppose you had a function that uses fromSome or fromSomeNote, how will I assert that the function throws a suitable error when None is an input.

sayHello: Optional Text -> Text
sayHello value= do
  let name = fromSomeNote "Missing name" value
  "Hello, " <> name

How would I write a unit test for the above function to assert that the ledger will throw Missing name if i dont pass an input

fromSome ends up calling the error function which throws a GeneralError exception. That exception can be caught and you can assert on it. You can also factor out the logic for that into a helper if you find yourself doing that frequently. The other option is to not use fromSome and instead represent the error explicitly as a Left "error" message which may be preferable in some cases.

module Main where

import Daml.Script
import DA.Exception
import DA.Optional
import DA.Assert

sayHello: Optional Text -> Text
sayHello value= do
  let name = fromSomeNote "Missing name" value
  "Hello, " <> name

testSayHello = script do
  try do
    pure (sayHello None)
    abort "unexpected success"
  catch GeneralError e -> e === "Missing name"

-- Note that we need to wrap it in a lambda to avoid
-- the exception being thrown when calling the function instead
-- of inside the body.
shouldThrowGeneralError : (() -> a) -> Text -> Script ()
shouldThrowGeneralError f t = do
  try do
    pure (f ())
    abort "unexpected success"
  catch GeneralError e -> e === t

testSayHello' = script do
  shouldThrowGeneralError (\_ -> sayHello None) "Missing name"
2 Likes

How would I assert errors if they are called as part of a choice logic? Something like submitMustFailWithError ?

@gtpaulose2
When asking a new question on the forum, please always start a new thread. If you need to reference an existing thread, include a link in your post. Lengthy threads with multiple unrelated or loosely related discussions make a poor forum experience because they’re hard to navigate and because they make the forum less searchable.

To answer your question, I’m not sure I fully understand what you’re asking. Are you asking how to do exception handling in the body of a choice? If this is your question, you can use “try-catch”, which allows to handle exceptions like precondition or assertion errors. See Exception Handling section in Daml documentation for details.
If you’re looking for something else, please start a new thread and elaborate.

Noted, created a new topic here: Asserting Errors in Unit Test when thrown in a choice