bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/name/regexp_test.go (about)

     1  package name
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"testing"
     7  )
     8  
     9  const hostnamePattern = `^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$`
    10  
    11  func generateString(length int) string {
    12  	sb := strings.Builder{}
    13  	for i := 0; i < length; i++ {
    14  		sb.WriteString("a")
    15  	}
    16  
    17  	return sb.String()
    18  }
    19  
    20  func TestRegexpValidation(t *testing.T) {
    21  	testCases := []struct {
    22  		testString string
    23  		expectPass bool
    24  	}{
    25  		{"host", true},
    26  		{"host-name", true},
    27  		{"machine.domain.com", true},
    28  		{"abc123", true},
    29  		{"123.com", true},
    30  		{"192.168.0.12", true},
    31  		{generateString(63), true},
    32  		{fmt.Sprintf("%s.%s.%s.%s.%s", generateString(63), generateString(63), generateString(63), generateString(63), generateString(63)), true},
    33  
    34  		{"", false},
    35  		{"   ", false},
    36  		{"-host", false},
    37  		{"host-", false},
    38  		{"host.", false},
    39  		{"host|name", false},
    40  		{"host name", false},
    41  		{generateString(64), false},
    42  		{"abc." + generateString(64), false},
    43  	}
    44  
    45  	validator, err := NewRegexpValidator(hostnamePattern)
    46  	if err != nil {
    47  		t.Error(err)
    48  		return
    49  	}
    50  
    51  	for _, testCase := range testCases {
    52  		if validator.IsValid(testCase.testString) != testCase.expectPass {
    53  			t.Errorf("Expected IsValid test for '%s' to yeild '%t' not '%t'",
    54  				testCase.testString, testCase.expectPass, !testCase.expectPass)
    55  		}
    56  	}
    57  }