github.com/google/cloudprober@v0.11.3/targets/statictargets_test.go (about)

     1  // Copyright 2021 The Cloudprober Authors.
     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  package targets
    16  
    17  import (
    18  	"reflect"
    19  	"testing"
    20  
    21  	"github.com/google/cloudprober/targets/endpoint"
    22  )
    23  
    24  func TestStaticTargets(t *testing.T) {
    25  	for _, test := range []struct {
    26  		desc      string
    27  		hosts     string
    28  		wantNames []string
    29  		wantPorts []int
    30  		wantErr   bool
    31  	}{
    32  		{
    33  			desc:      "valid hosts (extra space)",
    34  			hosts:     "www.google.com ,127.0.0.1, 2001::2001",
    35  			wantNames: []string{"www.google.com", "127.0.0.1", "2001::2001"},
    36  			wantPorts: []int{0, 0, 0},
    37  		},
    38  		{
    39  			desc:      "Ports in name",
    40  			hosts:     "www.google.com:80,127.0.0.1:8080,[2001::2001]:8081",
    41  			wantNames: []string{"www.google.com", "127.0.0.1", "2001::2001"},
    42  			wantPorts: []int{80, 8080, 8081},
    43  		},
    44  		{
    45  			desc:    "invalid host, IPv6 port in name without brackets",
    46  			hosts:   "www.google.com,127.0.0.1:8080,0:0:0:0:0:1:8081",
    47  			wantErr: true,
    48  		},
    49  		{
    50  			desc:    "invalid hosts,URL in name",
    51  			hosts:   "www.google.com/url1,127.0.0.1,2001::2001",
    52  			wantErr: true,
    53  		},
    54  	} {
    55  		t.Run(test.desc, func(t *testing.T) {
    56  			tgts, err := staticTargets(test.hosts)
    57  			if err != nil {
    58  				if !test.wantErr {
    59  					t.Errorf("Unexpected error: %v", err)
    60  				}
    61  				return
    62  			}
    63  			if test.wantErr {
    64  				t.Errorf("wanted error, but didn't get one")
    65  			}
    66  			wantEp := make([]endpoint.Endpoint, len(test.wantNames))
    67  			for i := 0; i < len(wantEp); i++ {
    68  				wantEp[i] = endpoint.Endpoint{Name: test.wantNames[i], Port: test.wantPorts[i]}
    69  			}
    70  			got := tgts.ListEndpoints()
    71  			if !reflect.DeepEqual(got, wantEp) {
    72  				t.Errorf("staticTargets: got=%v, wanted: %v", got, wantEp)
    73  			}
    74  		})
    75  	}
    76  }