Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix line numbers in Go test output?

Tags:

testing

go

Let's consider this simple testing code.

(Note: assertSomething is super simple here, but normally I'd write a more specialised helper for the task at hand that would look at multiple things and could report more than one type of error.)

package hello

import "testing"

func TestFoo(t *testing.T) {
    assertSomething(t, 2+2 == 4) // line 6
    assertSomething(t, 2+3 == 6) // line 7
}

func assertSomething(t *testing.T, expected bool) {
    if !expected {
        t.Error("Something's not right") // line 12
    }
}

When I run go test, I get the following:

--- FAIL: TestFoo (0.00s)
    hello.go:12: Something's not right
FAIL
exit status 1
FAIL    kos/hello   0.008s

I have two questions:

1) The error points to line 12 - why? How does t.Error find out which line it was called from?

2) In the helper, I'd like to specify that t.Error should look stack level higher to determine the line number to print, so that I would get a message like this:

--- FAIL: TestFoo (0.00s)
    hello.go:7: Something's not right

Python allows me to do this, for instance, in warnings.warn("message", stacklevel=2) - how would I implement the equivalent here?

like image 826
Kos Avatar asked Mar 06 '15 23:03

Kos


1 Answers

Things have changed since go 1.9.

Helper() method has been added to testing.T and testing.B. It's intended to be invoked from testing helpers such as assertSomething to indicate the function is a helper and we're not interested in line numbers coming from it.

package main

import "testing"

func TestFoo(t *testing.T) {
    assertSomething(t, 2+2 == 4) // line 6
    assertSomething(t, 2+3 == 6) // line 7
}

func assertSomething(t *testing.T, expected bool) {
    if !expected {
        t.Helper()
        t.Error("Something's not right") // line 12
    }
}

The output contains correct line numbers:

=== RUN   TestFoo
--- FAIL: TestFoo (0.00s)
    main.go:7: Something's not right
FAIL

You can also try it on Go Playground.

like image 167
roolebo Avatar answered Oct 18 '22 11:10

roolebo