github.com/clly/consul@v1.4.5/agent/cache-types/testing.go (about) 1 package cachetype 2 3 import ( 4 "reflect" 5 "time" 6 7 "github.com/hashicorp/consul/agent/cache" 8 "github.com/mitchellh/go-testing-interface" 9 ) 10 11 // TestRPC returns a mock implementation of the RPC interface. 12 func TestRPC(t testing.T) *MockRPC { 13 // This function is relatively useless but this allows us to perhaps 14 // perform some initialization later. 15 return &MockRPC{} 16 } 17 18 // TestFetchCh returns a channel that returns the result of the Fetch call. 19 // This is useful for testing timing and concurrency with Fetch calls. 20 // Errors will show up as an error type on the resulting channel so a 21 // type switch should be used. 22 func TestFetchCh( 23 t testing.T, 24 typ cache.Type, 25 opts cache.FetchOptions, 26 req cache.Request) <-chan interface{} { 27 resultCh := make(chan interface{}) 28 go func() { 29 result, err := typ.Fetch(opts, req) 30 if err != nil { 31 resultCh <- err 32 return 33 } 34 35 resultCh <- result 36 }() 37 38 return resultCh 39 } 40 41 // TestFetchChResult tests that the result from TestFetchCh matches 42 // within a reasonable period of time (it expects it to be "immediate" but 43 // waits some milliseconds). 44 func TestFetchChResult(t testing.T, ch <-chan interface{}, expected interface{}) { 45 t.Helper() 46 47 select { 48 case result := <-ch: 49 if err, ok := result.(error); ok { 50 t.Fatalf("Result was error: %s", err) 51 return 52 } 53 54 if !reflect.DeepEqual(result, expected) { 55 t.Fatalf("Result doesn't match!\n\n%#v\n\n%#v", result, expected) 56 } 57 58 case <-time.After(50 * time.Millisecond): 59 } 60 }