Mocking CGO function call for Unit testing

54 Views Asked by At

I am using Tensorflow Lite API in C to infer results from a model file, for which code is written in a .c file across different functions. The functions include get_interpreter which creates a new interpreter, etc.

Now, this is all in C code. I am calling this C function in Go using CGo support in Go.

Go function (pseudocode):

package main

import "C"

func callCApi() error {
    // load data
    // get_interpreter returns an interpreter of type TfLiteInterpreter*
    interpreter = C.get_interpreter(param1, param2)
    // run inference
    // errors are returned if any during the above stages, else nil is returned
    return nil
}

I want to unit test the above Go code callCApi(), how do I achieve this?

I understand that the above C function get_interpreter must be mocked; how can this be mocked?

1

There are 1 best solutions below

2
xhd2015 On

I assume you want to mock callCApi.

For mocking functions without boring interface abstraction, you can try xgo.

Here is how xgo would solve your problem:

package main

import (
    "context"
    "fmt"
    "C"

    "github.com/xhd2015/xgo/runtime/core"
    "github.com/xhd2015/xgo/runtime/mock"
)

func callCApi() error {
    // load data
    // get_interpreter returns an interpreter of type TfLiteInterpreter*
    interpreter = C.get_interpreter(param1, param2)
    // run inference
    // errors are returned if any during the above stages, else nil is returned
    return nil
}


func main() {
    mock.Mock(callCApi, func(ctx context.Context, fn *core.FuncInfo, args core.Object, results core.Object) error {
        // do what you like on args and results
        return nil
    })
    // the control flow will be transferred to mock.Mock
    callCApi()   
}

Check https://github.com/xhd2015/xgo for details.

Disclaimer: creator of the xgo project after years of diving into go compiler.