github.com/Tyktechnologies/tyk@v2.9.5+incompatible/gateway/reload_loop_test.go (about)

     1  package gateway
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"net/url"
     7  	"sync/atomic"
     8  	"testing"
     9  	"time"
    10  )
    11  
    12  func TestReloadLoop_basic(t *testing.T) {
    13  	ReloadTestCase.Enable()
    14  	defer ReloadTestCase.Disable()
    15  	var n atomic.Value
    16  	add := func() {
    17  		if x := n.Load(); x != nil {
    18  			n.Store(x.(int) + 1)
    19  		} else {
    20  			n.Store(int(0))
    21  		}
    22  	}
    23  
    24  	reloadURLStructure(add)
    25  	reloadURLStructure(add)
    26  	ReloadTestCase.TickOk(t)
    27  	x := n.Load().(int)
    28  	if x != 1 {
    29  		t.Errorf("expected 1 got %d", x)
    30  	}
    31  }
    32  
    33  func TestReloadLoop_handler(t *testing.T) {
    34  	ReloadTestCase.Enable()
    35  	defer ReloadTestCase.Disable()
    36  	var n atomic.Value
    37  	add := func() {
    38  		if x := n.Load(); x != nil {
    39  			n.Store(x.(int) + 1)
    40  		} else {
    41  			n.Store(int(1))
    42  		}
    43  	}
    44  	h := resetHandler(add)
    45  	w := httptest.NewRecorder()
    46  	r := httptest.NewRequest(http.MethodGet, "/reload", nil)
    47  	h(w, r)
    48  	ReloadTestCase.TickOk(t)
    49  	x := n.Load().(int)
    50  	if x != 1 {
    51  		t.Errorf("expected 1 got %d", x)
    52  	}
    53  }
    54  
    55  func TestReloadLoop_handlerWithBlock(t *testing.T) {
    56  	ReloadTestCase.Enable()
    57  	defer ReloadTestCase.Disable()
    58  
    59  	signal := make(chan struct{}, 1)
    60  	go func() {
    61  		h := resetHandler(nil)
    62  		w := httptest.NewRecorder()
    63  		r := httptest.NewRequest(http.MethodGet, "/reload", nil)
    64  		q := make(url.Values)
    65  		q.Set("block", "true")
    66  		r.URL.RawQuery = q.Encode()
    67  
    68  		// we need to do this to make sure the goroutine has been scheduled before we
    69  		// trigger a tick.
    70  		signal <- struct{}{}
    71  		h(w, r)
    72  		signal <- struct{}{}
    73  	}()
    74  	<-signal
    75  	ReloadTestCase.TickOk(t)
    76  	select {
    77  	case <-signal:
    78  	case <-time.After(10 * time.Millisecond):
    79  		t.Fatal("Timedout on a blocking reload")
    80  	}
    81  }
    82  
    83  func TestReloadLoop_group(t *testing.T) {
    84  	ts := StartTest()
    85  	defer ts.Close()
    86  
    87  	res, err := http.Get(testReloadGroup)
    88  	if err != nil {
    89  		t.Fatal(err)
    90  	}
    91  	defer res.Body.Close()
    92  	if res.StatusCode != http.StatusOK {
    93  		t.Errorf("expected %d got %d", http.StatusOK, res.StatusCode)
    94  	}
    95  	time.Sleep(time.Second)
    96  	requeueLock.Lock()
    97  	n := len(requeue)
    98  	requeue = []func(){}
    99  	requeueLock.Unlock()
   100  	if n != 1 {
   101  		t.Errorf("expected 1 reload queue got %d", n)
   102  	}
   103  }