0

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 Answer 1

-1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to unit test callCApi for which get_interpreter must be mocked.
It makes no difference.Wrap the C.get_interpreter in a go function, and mock that go function is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.