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

     1  package health
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"testing"
     7  
     8  	"cloud.google.com/go/compute/apiv1/computepb"
     9  	"github.com/googleapis/gax-go"
    10  	"github.com/m-lab/locate/cmd/heartbeat/metadata"
    11  )
    12  
    13  func TestGCPChecker_GetHealth(t *testing.T) {
    14  	tests := []struct {
    15  		name   string
    16  		client GCEClient
    17  		want   float64
    18  	}{
    19  		{
    20  			name: "healthy",
    21  			client: &fakeGCEClient{
    22  				status: []string{"HEALTHY"},
    23  				err:    false,
    24  			},
    25  			want: 1,
    26  		},
    27  		{
    28  			name: "unhealthy",
    29  			client: &fakeGCEClient{
    30  				status: []string{"UNHEALTHY"},
    31  				err:    false,
    32  			},
    33  			want: 0,
    34  		},
    35  		{
    36  			name: "mix",
    37  			client: &fakeGCEClient{
    38  				status: []string{"HEALTHY", "HEALTHY", "UNHEALTHY"},
    39  				err:    false,
    40  			},
    41  			want: 1,
    42  		},
    43  		{
    44  			name: "healthy-lower-case",
    45  			client: &fakeGCEClient{
    46  				status: []string{"healthy"},
    47  				err:    false,
    48  			},
    49  			want: 1,
    50  		},
    51  		{
    52  			name: "error",
    53  			client: &fakeGCEClient{
    54  				err: true,
    55  			},
    56  			want: 0,
    57  		},
    58  	}
    59  	for _, tt := range tests {
    60  		t.Run(tt.name, func(t *testing.T) {
    61  			c := NewGCPChecker(tt.client, &metadata.GCPMetadata{})
    62  			if got := c.GetHealth(context.Background()); got != tt.want {
    63  				t.Errorf("GCPChecker.GetHealth() = %v, want %v", got, tt.want)
    64  			}
    65  		})
    66  	}
    67  }
    68  
    69  type fakeGCEClient struct {
    70  	status []string
    71  	err    bool
    72  }
    73  
    74  func (c *fakeGCEClient) GetHealth(ctx context.Context, req *computepb.GetHealthRegionBackendServiceRequest, opts ...gax.CallOption) (*computepb.BackendServiceGroupHealth, error) {
    75  	if c.err {
    76  		return nil, errors.New("health error")
    77  	}
    78  
    79  	health := make([]*computepb.HealthStatus, 0)
    80  	for _, s := range c.status {
    81  		statusPtr := s
    82  		health = append(health, &computepb.HealthStatus{HealthState: &statusPtr})
    83  	}
    84  	return &computepb.BackendServiceGroupHealth{
    85  		HealthStatus: health,
    86  	}, nil
    87  }