1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
// Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package loggo_test
import (
"fmt"
"io/ioutil"
"strings"
"github.com/juju/loggo/v2"
gc "gopkg.in/check.v1"
)
func init() {
setLocationsForTags("logging_test.go")
setLocationsForTags("writer_test.go")
}
func assertLocation(c *gc.C, msg loggo.Entry, tag string) {
loc := location(tag)
c.Assert(msg.Filename, gc.Equals, loc.file)
c.Assert(msg.Line, gc.Equals, loc.line)
}
// All this location stuff is to avoid having hard coded line numbers
// in the tests. Any line where as a test writer you want to capture the
// file and line number, add a comment that has `//tag name` as the end of
// the line. The name must be unique across all the tests, and the test
// will panic if it is not. This name is then used to read the actual
// file and line numbers.
func location(tag string) Location {
loc, ok := tagToLocation[tag]
if !ok {
panic(fmt.Errorf("tag %q not found", tag))
}
return loc
}
type Location struct {
file string
line int
}
func (loc Location) String() string {
return fmt.Sprintf("%s:%d", loc.file, loc.line)
}
var tagToLocation = make(map[string]Location)
func setLocationsForTags(filename string) {
data, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
lines := strings.Split(string(data), "\n")
for i, line := range lines {
if j := strings.Index(line, "//tag "); j >= 0 {
tag := line[j+len("//tag "):]
if _, found := tagToLocation[tag]; found {
panic(fmt.Errorf("tag %q already processed previously", tag))
}
tagToLocation[tag] = Location{file: filename, line: i + 1}
}
}
}
|