github.com/google/cloudprober@v0.11.3/validators/validators_test.go (about)

     1  // Copyright 2019 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 validators
    16  
    17  import (
    18  	"reflect"
    19  	"testing"
    20  
    21  	"github.com/google/cloudprober/logger"
    22  )
    23  
    24  type testValidator struct {
    25  	Succeed bool
    26  }
    27  
    28  func (tv *testValidator) Init(config interface{}, l *logger.Logger) error {
    29  	return nil
    30  }
    31  
    32  func (tv *testValidator) Validate(responseObject interface{}, responseBody []byte) (bool, error) {
    33  	if tv.Succeed {
    34  		return true, nil
    35  	}
    36  	return false, nil
    37  }
    38  
    39  var testValidators = []*Validator{
    40  	{
    41  		Name:     "test-v1",
    42  		Validate: func(input *Input) (bool, error) { return true, nil },
    43  	},
    44  	{
    45  		Name:     "test-v2",
    46  		Validate: func(input *Input) (bool, error) { return false, nil },
    47  	},
    48  }
    49  
    50  func TestRunValidators(t *testing.T) {
    51  	vfMap := ValidationFailureMap(testValidators)
    52  	failures := RunValidators(testValidators, &Input{}, vfMap, nil)
    53  
    54  	if vfMap.GetKey("test-v1").Int64() != 0 {
    55  		t.Error("Got unexpected test-v1 validation failure.")
    56  	}
    57  
    58  	if vfMap.GetKey("test-v2").Int64() != 1 {
    59  		t.Errorf("Didn't get expected test-v2 validation failure.")
    60  	}
    61  
    62  	if !reflect.DeepEqual(failures, []string{"test-v2"}) {
    63  		t.Errorf("Didn't get expected validation failures. Expected: {\"test-v2\"}, Got: %v", failures)
    64  	}
    65  }
    66  
    67  func TestValidatorFailureMap(t *testing.T) {
    68  	vfMap := ValidationFailureMap(testValidators)
    69  
    70  	expectedKeys := []string{"test-v1", "test-v3"}
    71  	if reflect.DeepEqual(vfMap.Keys(), expectedKeys) {
    72  		t.Errorf("Didn't get expected keys in the mao. Got: %s, Expected: %v", vfMap.Keys(), expectedKeys)
    73  	}
    74  }