Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap golang test functions

Tags:

go

I'd like to wrap standard golang test functions, such as t.Errorf from the testing package.

I tried this:

// AssertEqual tests that the expected and actual values match
func AssertEqual(t *testing.T, expected interface{}, actual interface{}) {
    switch expected.(type) {
    case string:
        if expected != actual {
            t.Errorf("Error:\nexpected: %s\nactual: %s", expected, actual)
        }
    default:
        t.Errorf("Unsupported type")
    }
}

However, when a test fails, I get the function and line number of my helper function:

test_asserts.go:12: Error:
    expected: 
    actual: TestValue

Is there a way to error at the line number of the caller?

like image 696
EmpireJones Avatar asked Feb 06 '23 06:02

EmpireJones


1 Answers

With the recent Go 1.9 (August 2017), all you need to do is adding one line to your function:

t.Helper()

That will silence this function in error report, and your actual error line will be the one you expect (ie the one calling this function)

See pkg/testing/#T.Helper (also available for Benchmark test, but... not for the TB interface, where it was forgotten! Feb. 2021: this is available, see below)

// AssertEqual tests that the expected and actual values match
func AssertEqual(t *testing.T, expected interface{}, actual interface{}) {
    t.Helper()
    switch expected.(type) {
    case string:
        if expected != actual {
            t.Errorf("Error:\nexpected: %s\nactual: %s", expected, actual)
        }
    default:
        t.Errorf("Unsupported type")
    }
}

xuiqzy mentions in the comments in Feb. 2021 the interface testing.TB which now has Helper().
See commit bc29313, Apr. 2017, go1.9beta1, CL 38796 for implementing proposal 4899.

We propose to add a new testing.TB method, Helper, which marks the calling function as a test helper.

When logging test messages, package testing ignores frames that are inside marked helper functions.
It prints the first stack position inside a non-helper function.

like image 77
VonC Avatar answered Feb 20 '23 14:02

VonC