github.com/looshlee/beatles@v0.0.0-20220727174639-742810ab631c/pkg/kvstore/consul_test.go (about)

     1  // Copyright 2016-2018 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // +build !privileged_tests
    16  
    17  package kvstore
    18  
    19  import (
    20  	"io"
    21  	"net/http"
    22  	"os"
    23  	"testing"
    24  	"time"
    25  
    26  	consulAPI "github.com/hashicorp/consul/api"
    27  	. "gopkg.in/check.v1"
    28  )
    29  
    30  type ConsulSuite struct {
    31  	BaseTests
    32  }
    33  
    34  var _ = Suite(&ConsulSuite{})
    35  
    36  func (e *ConsulSuite) SetUpTest(c *C) {
    37  	SetupDummy("consul")
    38  }
    39  
    40  func (e *ConsulSuite) TearDownTest(c *C) {
    41  	Client().Close()
    42  }
    43  
    44  var handler http.HandlerFunc
    45  
    46  func TestMain(m *testing.M) {
    47  	mux := http.NewServeMux()
    48  	// path is hardcoded in consul
    49  	mux.HandleFunc("/v1/status/leader", func(w http.ResponseWriter, r *http.Request) {
    50  		handler(w, r)
    51  	})
    52  
    53  	mux.HandleFunc("/v1/session/create", func(w http.ResponseWriter, r *http.Request) {
    54  		io.WriteString(w, "{ \"ID\": \"adf4238a-882b-9ddc-4a9d-5b6758e4159e\"}")
    55  	})
    56  
    57  	// /v1/session/renew/{uuid} does not need to be handled for the basic
    58  	// test to succeed
    59  
    60  	srv := &http.Server{
    61  		Addr:    ":8000",
    62  		Handler: mux,
    63  	}
    64  
    65  	go srv.ListenAndServe()
    66  
    67  	os.Exit(m.Run())
    68  }
    69  
    70  func TestConsulClientOk(t *testing.T) {
    71  	maxRetries = 3
    72  	doneC := make(chan struct{})
    73  
    74  	handler = func(w http.ResponseWriter, r *http.Request) {
    75  		io.WriteString(w, "\"nanananananananananleaaderrrr\"")
    76  		close(doneC)
    77  	}
    78  
    79  	_, err := newConsulClient(&consulAPI.Config{
    80  		Address: ":8000",
    81  	}, nil)
    82  
    83  	select {
    84  	case <-doneC:
    85  	case <-time.After(time.Second * 5):
    86  		t.Log("timeout")
    87  		t.FailNow()
    88  	}
    89  
    90  	// we should not get a failure
    91  	if err != nil {
    92  		t.Log("error:" + err.Error())
    93  		t.FailNow()
    94  	}
    95  }