github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/edgetest/context_rest.go (about) 1 package edgetest 2 3 import ( 4 "sync/atomic" 5 "time" 6 7 "github.com/ronaksoft/rony" 8 dummyGateway "github.com/ronaksoft/rony/internal/gateway/dummy" 9 ) 10 11 /* 12 Creation Time: 2020 - Dec - 09 13 Created by: (ehsan) 14 Maintainers: 15 1. Ehsan N. Moosa (E2) 16 Auditor: Ehsan N. Moosa (E2) 17 Copyright Ronak Software Group 2020 18 */ 19 20 type restCtx struct { 21 id uint64 22 gw *dummyGateway.Gateway 23 err error 24 expect CheckFunc 25 doneCh chan struct{} 26 kvs []*rony.KeyValue 27 method string 28 path string 29 body []byte 30 } 31 32 func newRESTContext(gw *dummyGateway.Gateway) *restCtx { 33 c := &restCtx{ 34 id: atomic.AddUint64(&connID, 1), 35 gw: gw, 36 doneCh: make(chan struct{}, 1), 37 } 38 39 return c 40 } 41 42 // Request set the request you wish to send to the server 43 func (c *restCtx) Request(method, path string, body []byte, kvs ...*rony.KeyValue) *restCtx { 44 c.method = method 45 c.path = path 46 c.body = body 47 c.kvs = kvs 48 49 return c 50 } 51 52 // Expect let you set what you expect to receive. If cf is set, then you can do more 53 // checks on the response and return error if the response was not fully acceptable 54 func (c *restCtx) Expect(cf CheckFunc) *restCtx { 55 c.expect = cf 56 57 return c 58 } 59 60 func (c *restCtx) RunShort(kvs ...*rony.KeyValue) error { 61 return c.Run(time.Second*10, kvs...) 62 } 63 64 func (c *restCtx) RunLong(kvs ...*rony.KeyValue) error { 65 return c.Run(time.Minute, kvs...) 66 } 67 68 func (c *restCtx) Run(timeout time.Duration, kvs ...*rony.KeyValue) error { 69 // We return error early if we have encountered error before Run 70 if c.err != nil { 71 return c.err 72 } 73 74 go func() { 75 respBody, respHdr := c.gw.REST(c.id, c.method, c.path, c.body, kvs...) 76 hdr := make([]*rony.KeyValue, 0, len(respHdr)) 77 for k, v := range respHdr { 78 hdr = append(hdr, &rony.KeyValue{Key: k, Value: v}) 79 } 80 c.err = c.expect(respBody, hdr...) 81 c.doneCh <- struct{}{} 82 }() 83 84 // Wait for Response(s) 85 select { 86 case <-c.doneCh: 87 case <-time.After(timeout): 88 c.err = ErrTimeout 89 } 90 91 return c.err 92 }