bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/opentsdb/name_test.go (about)

     1  package opentsdb
     2  
     3  import (
     4  	"testing"
     5  
     6  	"bosun.org/name"
     7  )
     8  
     9  func createVaidator(t *testing.T) name.RuneLevelProcessor {
    10  	validator, err := NewOpenTsdbNameProcessor("")
    11  	if err != nil {
    12  		t.Error(err)
    13  		return nil
    14  	}
    15  
    16  	return validator
    17  }
    18  
    19  func TestNameValidation(t *testing.T) {
    20  	testCases := []struct {
    21  		testString string
    22  		expectPass bool
    23  	}{
    24  		{"abc", true},
    25  		{"one.two.three", true},
    26  		{"1/2/3/4", true},
    27  		{"abc-123/456_xyz", true},
    28  		{"", false},
    29  		{" ", false},
    30  		{"abc$", false},
    31  		{"abc!xyz", false},
    32  	}
    33  
    34  	validator := createVaidator(t)
    35  
    36  	for _, testCase := range testCases {
    37  		if validator.IsValid(testCase.testString) != testCase.expectPass {
    38  			t.Errorf("Expected IsValid test for '%s' to yeild '%t' not '%t'",
    39  				testCase.testString, testCase.expectPass, !testCase.expectPass)
    40  		}
    41  	}
    42  }
    43  
    44  func TestRuneLevelValidation(t *testing.T) {
    45  	testCases := []struct {
    46  		testRune   rune
    47  		expectPass bool
    48  	}{
    49  		{'a', true},
    50  		{'Z', true},
    51  		{'0', true},
    52  		{'9', true},
    53  		{'-', true},
    54  		{'_', true},
    55  		{'.', true},
    56  		{'/', true},
    57  
    58  		{'£', false},
    59  		{'$', false},
    60  		{'?', false},
    61  	}
    62  
    63  	validator := createVaidator(t)
    64  
    65  	for _, testCase := range testCases {
    66  		if validator.IsRuneValid(testCase.testRune) != testCase.expectPass {
    67  			t.Errorf("Expected rune '%c' to be [valid=%t] but it was [valid=%t]",
    68  				testCase.testRune, testCase.expectPass, !testCase.expectPass)
    69  		}
    70  	}
    71  }
    72  
    73  func TestFormat(t *testing.T) {
    74  	testCases := []struct {
    75  		test     string
    76  		expected string
    77  	}{
    78  		{"abc", "abc"},
    79  		{"a.b/c_d-e", "a.b/c_d-e"},
    80  		{"one two three", "onetwothree"},
    81  		{"   one    two    three   ", "onetwothree"},
    82  		{"a$b£c:d", "abcd"},
    83  	}
    84  
    85  	validator := createVaidator(t)
    86  
    87  	for _, testCase := range testCases {
    88  		formatted, err := validator.FormatName(testCase.test)
    89  		if err != nil {
    90  			t.Error(err)
    91  		}
    92  
    93  		if formatted != testCase.expected {
    94  			t.Errorf("Expected '%s' but got '%s'", testCase.expected, formatted)
    95  		}
    96  	}
    97  }