Skip to content

Commit

Permalink
Add panicx.LocationOfMethod().
Browse files Browse the repository at this point in the history
  • Loading branch information
jmalloc committed Nov 22, 2020
1 parent 65c19b1 commit afda095
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
4 changes: 4 additions & 0 deletions engine/panicx/linenumber_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,7 @@ func doNothing() {}
func panicWithUnexpectedMessage() { panic(dogma.UnexpectedMessage) }
func locationOfCallLayer1() Location { return LocationOfCall() }
func locationOfCallLayer2() Location { return locationOfCallLayer1() }

type locationOfMethodT struct{}

func (locationOfMethodT) Method() {}
17 changes: 16 additions & 1 deletion engine/panicx/location.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ func (l Location) String() string {

// LocationOfFunc returns the location of the definition of fn.
func LocationOfFunc(fn interface{}) Location {
rv := reflect.ValueOf(fn)
return locationOfFunc(reflect.ValueOf(fn))
}

func locationOfFunc(rv reflect.Value) Location {
if rv.Kind() != reflect.Func {
panic("fn must be a function")
}
Expand All @@ -60,6 +63,18 @@ func LocationOfFunc(fn interface{}) Location {
return loc
}

// LocationOfMethod returns the location of the definition of fn.
func LocationOfMethod(recv interface{}, m string) Location {
rt := reflect.TypeOf(recv)

rm, ok := rt.MethodByName(m)
if !ok {
panic("method does not exist")
}

return locationOfFunc(rm.Func)
}

// LocationOfCall returns the location where its caller was called itself.
func LocationOfCall() Location {
var loc Location
Expand Down
14 changes: 14 additions & 0 deletions engine/panicx/location_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,20 @@ var _ = Describe("type Location", func() {
})
})

Describe("func LocationOfMethod()", func() {
It("returns the expected location", func() {
loc := LocationOfMethod(locationOfMethodT{}, "Method")

Expect(loc).To(MatchAllFields(
Fields{
"Func": Equal("github.com/dogmatiq/testkit/engine/panicx_test.locationOfMethodT.Method"),
"File": HaveSuffix("/engine/panicx/linenumber_test.go"),
"Line": Equal(57),
},
))
})
})

Describe("func LocationOfCall()", func() {
It("returns the expected location", func() {
loc := locationOfCallLayer2()
Expand Down

0 comments on commit afda095

Please sign in to comment.