Update ValidateInstanceName to return the validated name and modify tests accordingly

This commit is contained in:
2025-08-04 20:46:15 +02:00
parent 934d1c5aaa
commit 85b3638efb
3 changed files with 14 additions and 7 deletions

View File

@@ -31,7 +31,7 @@ func (im *instanceManager) CreateInstance(name string, options *instance.CreateI
return nil, fmt.Errorf("maximum number of instances (%d) reached", im.instancesConfig.MaxInstances) return nil, fmt.Errorf("maximum number of instances (%d) reached", im.instancesConfig.MaxInstances)
} }
err := validation.ValidateInstanceName(name) name, err := validation.ValidateInstanceName(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -102,16 +102,16 @@ func validateStructStrings(v any, fieldPath string) error {
return nil return nil
} }
func ValidateInstanceName(name string) error { func ValidateInstanceName(name string) (string, error) {
// Validate instance name // Validate instance name
if name == "" { if name == "" {
return ValidationError(fmt.Errorf("name cannot be empty")) return "", ValidationError(fmt.Errorf("name cannot be empty"))
} }
if !validNamePattern.MatchString(name) { if !validNamePattern.MatchString(name) {
return ValidationError(fmt.Errorf("name contains invalid characters (only alphanumeric, hyphens, underscores allowed)")) return "", ValidationError(fmt.Errorf("name contains invalid characters (only alphanumeric, hyphens, underscores allowed)"))
} }
if len(name) > 50 { if len(name) > 50 {
return ValidationError(fmt.Errorf("name too long (max 50 characters)")) return "", ValidationError(fmt.Errorf("name too long (max 50 characters)"))
} }
return nil return name, nil
} }

View File

@@ -41,10 +41,17 @@ func TestValidateInstanceName(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
err := validation.ValidateInstanceName(tt.input) name, err := validation.ValidateInstanceName(tt.input)
if (err != nil) != tt.wantErr { if (err != nil) != tt.wantErr {
t.Errorf("ValidateInstanceName(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr) t.Errorf("ValidateInstanceName(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
} }
if tt.wantErr {
return // Skip further checks if we expect an error
}
// If no error, check that the name is returned as expected
if name != tt.input {
t.Errorf("ValidateInstanceName(%q) = %q, want %q", tt.input, name, tt.input)
}
}) })
} }
} }