Home > other >  How to test with hardwired function
How to test with hardwired function

Time:09-22

My understanding is that code should be written without testing in mind, and that testing needs to bend to cater to the code. My problem is that I have a function f1 that calls out for input data (a Haskell data type) that is returned from another function f2. So how can I write a test case that provides different input data?

Of course I could add an arg to f1 for the input, but after all that is catering to testing. It's actually messier than that, because f1 is actually a Plutus contract, and the arg would need to be serialized to JSON -- all for the sake of testing. Alternatively, I could read the input from a file, and provide the filepath as an arg -- the arg is bad enough, but I don't want to go with a file if I don't have to.

Perhaps Template Haskell can help, but I'm not sure how. Or perhaps since every rule has an exception, here too an exception should be made. Kindly advise.

data ActualData = ActualData String String Integer
newtype Input = Input [ActualData]

f1:: Contract () Schema Text () 
f1 = do
    let input = f2 
    ...

f2 :: Input -- to be determined in the future, currently unknown
f2 = Input
    [ ActualData "BlackRock" "pkh1" 10
    , ActualData "GreenRock" "pkh2" 20
    ]

CodePudding user response:

I think the simplest is probably just to expose two functions. One accepts the input data as a plain old function input, and the other knows to use f2. So:

f1WithArg :: X -> Y
f1WithArg x = {- ... -}

f1 :: Y
f1 = f2 >>= f1WithArg -- or whatever

Then you would write all your tests in terms of f1WithArg, and just trust that f1 doesn't do any interesting computation.

Alternatively, you could expose a single f1 that takes a Maybe X, with a similar implementation pattern:

f1Auto :: Maybe X -> Y
f1Auto Nothing = f2 >>= f1Auto . Just -- or whatever
f1Auto (Just x) = {- ... -}

Some interface like that might be useful if you ever need to programmatically decide whether the input should come from f2 or not, but that sounds like it's not the case for you.

  • Related