github.com/xmidt-org/webpa-common@v1.11.9/xhttp/busy_test.go (about) 1 package xhttp 2 3 import ( 4 "context" 5 "net/http" 6 "net/http/httptest" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 "github.com/stretchr/testify/require" 11 ) 12 13 func testBusyInvalidMaxTransactions(t *testing.T) { 14 assert := assert.New(t) 15 16 assert.Panics(func() { 17 Busy(0) 18 }) 19 20 assert.Panics(func() { 21 Busy(-1) 22 }) 23 } 24 25 func testBusySimple(t *testing.T) { 26 var ( 27 assert = assert.New(t) 28 require = require.New(t) 29 30 next = http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) { 31 response.WriteHeader(231) 32 }) 33 34 response = httptest.NewRecorder() 35 request = httptest.NewRequest("GET", "/", nil) 36 37 decorated = Busy(1)(next) 38 ) 39 40 require.NotNil(decorated) 41 decorated.ServeHTTP(response, request) 42 assert.Equal(231, response.Code) 43 } 44 45 func testBusyCancelation(t *testing.T) { 46 var ( 47 assert = assert.New(t) 48 require = require.New(t) 49 50 firstReceived = make(chan struct{}) 51 firstWaiting = make(chan struct{}) 52 firstComplete = make(chan struct{}) 53 54 next = http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { 55 close(firstReceived) 56 <-firstWaiting 57 response.WriteHeader(299) 58 }) 59 60 decorated = Busy(1)(next) 61 ) 62 63 require.NotNil(decorated) 64 65 // spawn a "long running" in flight HTTP transaction 66 go func() { 67 defer close(firstComplete) 68 69 var ( 70 response = httptest.NewRecorder() 71 request = httptest.NewRequest("GET", "/longrunning", nil) 72 ) 73 74 decorated.ServeHTTP(response, request) 75 assert.Equal(299, response.Code) 76 }() 77 78 <-firstReceived 79 80 // now any HTTP transaction should be held up waiting on the semaphore 81 82 var ( 83 ctx, cancel = context.WithCancel(context.Background()) 84 response = httptest.NewRecorder() 85 request = httptest.NewRequest("GET", "/rejected", nil).WithContext(ctx) 86 ) 87 88 cancel() 89 decorated.ServeHTTP(response, request) 90 assert.Equal(http.StatusServiceUnavailable, response.Code) 91 92 close(firstWaiting) 93 <-firstComplete 94 } 95 96 func TestBusy(t *testing.T) { 97 t.Run("InvalidMaxTransactions", testBusyInvalidMaxTransactions) 98 t.Run("Simple", testBusySimple) 99 t.Run("Cancelation", testBusyCancelation) 100 }