github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/juju/errors/package_test.go (about) 1 // Copyright 2013, 2014 Canonical Ltd. 2 // Licensed under the LGPLv3, see LICENCE file for details. 3 4 package errors_test 5 6 import ( 7 "fmt" 8 "io/ioutil" 9 "strings" 10 "testing" 11 12 gc "gopkg.in/check.v1" 13 14 "github.com/insionng/yougam/libraries/juju/errors" 15 ) 16 17 func Test(t *testing.T) { 18 gc.TestingT(t) 19 } 20 21 func checkDetails(c *gc.C, err error, details string) { 22 c.Assert(err, gc.NotNil) 23 expectedDetails := replaceLocations(details) 24 c.Assert(errors.Details(err), gc.Equals, expectedDetails) 25 } 26 27 func checkErr(c *gc.C, err, cause error, msg string, details string) { 28 c.Assert(err, gc.NotNil) 29 c.Assert(err.Error(), gc.Equals, msg) 30 c.Assert(errors.Cause(err), gc.Equals, cause) 31 expectedDetails := replaceLocations(details) 32 c.Assert(errors.Details(err), gc.Equals, expectedDetails) 33 } 34 35 func replaceLocations(line string) string { 36 result := "" 37 for { 38 i := strings.Index(line, "$") 39 if i == -1 { 40 break 41 } 42 result += line[0:i] 43 line = line[i+1:] 44 i = strings.Index(line, "$") 45 if i == -1 { 46 panic("no second $") 47 } 48 result += location(line[0:i]).String() 49 line = line[i+1:] 50 } 51 result += line 52 return result 53 } 54 55 func location(tag string) Location { 56 loc, ok := tagToLocation[tag] 57 if !ok { 58 panic(fmt.Sprintf("tag %q not found", tag)) 59 } 60 return loc 61 } 62 63 type Location struct { 64 file string 65 line int 66 } 67 68 func (loc Location) String() string { 69 return fmt.Sprintf("%s:%d", loc.file, loc.line) 70 } 71 72 var tagToLocation = make(map[string]Location) 73 74 func setLocationsForErrorTags(filename string) { 75 data, err := ioutil.ReadFile(filename) 76 if err != nil { 77 panic(err) 78 } 79 filename = "github.com/insionng/yougam/libraries/juju/errors/" + filename 80 lines := strings.Split(string(data), "\n") 81 for i, line := range lines { 82 if j := strings.Index(line, "//err "); j >= 0 { 83 tag := line[j+len("//err "):] 84 if _, found := tagToLocation[tag]; found { 85 panic(fmt.Sprintf("tag %q already processed previously", tag)) 86 } 87 tagToLocation[tag] = Location{file: filename, line: i + 1} 88 } 89 } 90 } 91 92 func init() { 93 setLocationsForErrorTags("error_test.go") 94 setLocationsForErrorTags("functions_test.go") 95 }