github.com/zak-blake/goa@v1.4.1/middleware/xray/test_expectations.go (about) 1 package xray 2 3 import ( 4 "fmt" 5 "os" 6 "strings" 7 "sync" 8 9 pkgerrors "github.com/pkg/errors" 10 ) 11 12 type ( 13 // TestClientExpectation is a generic mock. 14 TestClientExpectation struct { 15 mu sync.Mutex 16 expected expectations 17 unexpected []string 18 } 19 20 // expectations is the data structure used to record expected function 21 // calls and the corresponding behavior. 22 expectations map[string][]interface{} 23 ) 24 25 // NewTestClientExpectation creates a new *TestClientExpectation 26 func NewTestClientExpectation() *TestClientExpectation { 27 return &TestClientExpectation{ 28 mu: sync.Mutex{}, 29 expected: make(expectations), 30 } 31 } 32 33 // Expect records the request handler in the list of expected request calls. 34 func (c *TestClientExpectation) Expect(fn string, e interface{}) { 35 c.mu.Lock() 36 defer c.mu.Unlock() 37 c.expected[fn] = append(c.expected[fn], e) 38 } 39 40 // ExpectNTimes records the request handler n times in the list of expected request calls. 41 func (c *TestClientExpectation) ExpectNTimes(n int, fn string, e interface{}) { 42 c.mu.Lock() 43 defer c.mu.Unlock() 44 45 for i := 0; i < n; i++ { 46 c.expected[fn] = append(c.expected[fn], e) 47 } 48 } 49 50 // Expectation removes the expectation for the function with the given name from the expected calls 51 // if there is one and returns it. If there is no (more) expectations for the function, 52 // it prints a warning to stderr and returns nil. 53 func (c *TestClientExpectation) Expectation(fn string) interface{} { 54 c.mu.Lock() 55 defer c.mu.Unlock() 56 es, ok := c.expected[fn] 57 if !ok { 58 err := pkgerrors.New("!!! Expectation not found for: " + fn) 59 fmt.Fprintf(os.Stderr, "\n%+v\n", err) 60 c.unexpected = append(c.unexpected, fn) 61 return nil 62 } 63 e := es[0] 64 if len(es) == 1 { 65 delete(c.expected, fn) 66 } else { 67 c.expected[fn] = c.expected[fn][1:] 68 } 69 return e 70 } 71 72 // MetExpectations returns nil if there no expectation left to be called and if there is no call 73 // that was made that did not match an expectation. It returns an error describing what is left to 74 // be called or what was called with no expectation otherwise. 75 func (c *TestClientExpectation) MetExpectations() error { 76 c.mu.Lock() 77 defer c.mu.Unlock() 78 var msg string 79 if len(c.unexpected) > 0 { 80 msg = fmt.Sprintf("%s was called but wasn't expected.", strings.Join(c.unexpected, ", ")) 81 } 82 if len(c.expected) > 0 { 83 if len(msg) > 0 { 84 msg += "\n" 85 } 86 i := 0 87 keys := make([]string, len(c.expected)) 88 for e := range c.expected { 89 keys[i] = e 90 i++ 91 } 92 msg += fmt.Sprintf("%s was expected to be called but wasn't.", strings.Join(keys, ", ")) 93 } 94 if msg == "" { 95 return nil 96 } 97 return fmt.Errorf(msg) 98 }