github.com/m-lab/locate@v0.17.6/cmd/heartbeat/health/endpoint-check_test.go (about)

     1  package health
     2  
     3  import (
     4  	"net/http"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/m-lab/locate/cmd/heartbeat/health/healthtest"
     9  )
    10  
    11  func Test_checkHealthEndpoint(t *testing.T) {
    12  	tests := []struct {
    13  		name    string
    14  		code    int
    15  		want    bool
    16  		wantErr bool
    17  	}{
    18  		{
    19  			name:    "200-status",
    20  			code:    http.StatusOK,
    21  			want:    true,
    22  			wantErr: false,
    23  		},
    24  		{
    25  			name:    "500-status",
    26  			code:    http.StatusInternalServerError,
    27  			want:    false,
    28  			wantErr: false,
    29  		},
    30  		{
    31  			name:    "error-server-not-running",
    32  			want:    false,
    33  			wantErr: true,
    34  		},
    35  	}
    36  	for _, tt := range tests {
    37  		t.Run(tt.name, func(t *testing.T) {
    38  			if !tt.wantErr {
    39  				srv := healthtest.TestHealthServer(tt.code)
    40  				healthAddress = srv.URL + "/health"
    41  				defer srv.Close()
    42  			}
    43  
    44  			hc := NewEndpointClient(time.Second)
    45  			got, err := hc.checkHealthEndpoint()
    46  			if (err != nil) != tt.wantErr {
    47  				t.Errorf("checkHealthEndpoint() error = %v, wantErr %v", err, tt.wantErr)
    48  				return
    49  			}
    50  
    51  			if got != tt.want {
    52  				t.Errorf("checkHealthEndpoint() = %v, want %v", got, tt.want)
    53  			}
    54  		})
    55  	}
    56  }
    57  
    58  func Test_checkHealthEndpoint_timeout(t *testing.T) {
    59  	srv := healthtest.TestTimeoutServer(2 * time.Second)
    60  	healthAddress = srv.URL + "/health"
    61  	defer srv.Close()
    62  
    63  	hc := NewEndpointClient(time.Second)
    64  	got, err := hc.checkHealthEndpoint()
    65  	if err == nil {
    66  		t.Errorf("checkHealthEndpoint() error = %v, wantErr %s", err, "context deadline error")
    67  		return
    68  	}
    69  
    70  	if got != false {
    71  		t.Errorf("checkHealthEndpoint() = %v, want %v", got, false)
    72  	}
    73  }