jeudi 3 décembre 2020

Mocking specific error types in golang unit tests

I have been working on handling soft failures in some golang functions, and want to create some unit tests for the various failure scenarios. For example some of the checks include:

        switch err := err.(type) {
        case net.Error:
                if err.(net.Error).Temporary() || err.(net.Error).Timeout() {
                        ...
                }
        case *url.Error:
                if err, ok := err.Err.(net.Error); ok && err.Timeout() {
                        ...
                }
        case *net.OpError:
                if syscallErr, ok := err.Err.(*os.SyscallError); ok {
                        if syscallErr.Err == syscall.ECONNRESET {
                                ...
                        }
                }
        ...

I believe I just need my mock function to return errors compatible with those conditions. I see net.Error, net.OpError, url.Error, and os.SyscallError types exported. However I can't find any examples of anyone constructing a net.Error value and returning it - people put a lot of work into creating an external processes that fail in various ways but no examples of returning a net.Error with a Timeout function that returns true.

Likewise I could not find any examples of wrapping an error that wasn't produced with fmt.Errorf so I'm unsure if something more then errors.Wrap() is involved when not using the base builtin error type.

Aucun commentaire:

Enregistrer un commentaire