github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/create_role_test.go (about)

     1  // Copyright 2020 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package sql_test
    12  
    13  import (
    14  	"testing"
    15  
    16  	"github.com/cockroachdb/cockroach/pkg/sql"
    17  	"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
    18  	"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
    19  	"github.com/cockroachdb/cockroach/pkg/testutils"
    20  	"github.com/cockroachdb/cockroach/pkg/util/leaktest"
    21  )
    22  
    23  func TestUserName(t *testing.T) {
    24  	defer leaktest.AfterTest(t)()
    25  
    26  	testCases := []struct {
    27  		username   string
    28  		normalized string
    29  		err        string
    30  		sqlstate   string
    31  	}{
    32  		{"Abc123", "abc123", "", ""},
    33  		{"0123121132", "0123121132", "", ""},
    34  		{"HeLlO", "hello", "", ""},
    35  		{"Ομηρος", "ομηρος", "", ""},
    36  		{"_HeLlO", "_hello", "", ""},
    37  		{"a-BC-d", "a-bc-d", "", ""},
    38  		{"A.Bcd", "a.bcd", "", ""},
    39  		{"WWW.BIGSITE.NET", "www.bigsite.net", "", ""},
    40  		{"", "", `username "" invalid`, pgcode.InvalidName},
    41  		{"-ABC", "", `username "-abc" invalid`, pgcode.InvalidName},
    42  		{".ABC", "", `username ".abc" invalid`, pgcode.InvalidName},
    43  		{"*.wildcard", "", `username "\*.wildcard" invalid`, pgcode.InvalidName},
    44  		{"foofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoof", "", `username "foofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoof" is too long`, pgcode.NameTooLong},
    45  		{"M", "m", "", ""},
    46  		{".", "", `username "." invalid`, pgcode.InvalidName},
    47  	}
    48  
    49  	for _, tc := range testCases {
    50  		normalized, err := sql.NormalizeAndValidateUsername(tc.username)
    51  		if !testutils.IsError(err, tc.err) {
    52  			t.Errorf("%q: expected %q, got %v", tc.username, tc.err, err)
    53  			continue
    54  		}
    55  		if err != nil {
    56  			if pgcode := pgerror.GetPGCode(err); pgcode != tc.sqlstate {
    57  				t.Errorf("%q: expected SQLSTATE %s, got %s", tc.username, tc.sqlstate, pgcode)
    58  				continue
    59  			}
    60  		}
    61  		if normalized != tc.normalized {
    62  			t.Errorf("%q: expected %q, got %q", tc.username, tc.normalized, normalized)
    63  		}
    64  	}
    65  }