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

     1  // Copyright 2018 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 regex
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/google/cloudprober/logger"
    21  )
    22  
    23  func TestInvalidConfig(t *testing.T) {
    24  	// Empty config
    25  	testConfig := ""
    26  	v := Validator{}
    27  	err := v.Init(testConfig, &logger.Logger{})
    28  	if err == nil {
    29  		t.Errorf("v.Init(%s, l): expected error but got nil", testConfig)
    30  	}
    31  
    32  	// Invalid regex as Go regex doesn't support negative lookaheads.
    33  	testConfig = "(?!cloudprober)"
    34  	v = Validator{}
    35  	err = v.Init(testConfig, &logger.Logger{})
    36  	if err == nil {
    37  		t.Errorf("v.Init(%s, l): expected error but got nil", testConfig)
    38  	}
    39  }
    40  
    41  func verifyValidate(t *testing.T, respBody []byte, regexStr string, expected bool) {
    42  	t.Helper()
    43  	// Test initializing with pattern string.
    44  	v := Validator{}
    45  	err := v.Init(regexStr, &logger.Logger{})
    46  	if err != nil {
    47  		t.Errorf("v.Init(%s, l): got error: %v", regexStr, err)
    48  	}
    49  
    50  	result, err := v.Validate(respBody)
    51  	if err != nil {
    52  		t.Errorf("v.Validate(nil, %s): got error: %v", string(respBody), err)
    53  	}
    54  
    55  	if result != expected {
    56  		if err != nil {
    57  			t.Errorf("v.Validate(nil, %s): result: %v, expected: %v", string(respBody), result, expected)
    58  		}
    59  	}
    60  }
    61  
    62  func TestPatternString(t *testing.T) {
    63  	rows := []struct {
    64  		regex    string
    65  		respBody []byte
    66  		expected bool
    67  	}{
    68  		{
    69  			regex:    "cloud.*",
    70  			respBody: []byte("cloudprober"),
    71  			expected: true,
    72  		},
    73  		{
    74  			regex:    "[Cc]loud.*",
    75  			respBody: []byte("Cloudprober"),
    76  			expected: false,
    77  		},
    78  	}
    79  
    80  	for _, r := range rows {
    81  		verifyValidate(t, r.respBody, r.regex, r.expected)
    82  	}
    83  
    84  }