Rename validation 'New' funcs

This commit is contained in:
Tim Hockin 2015-11-03 16:17:48 -08:00
parent 682f2a5a79
commit ceee678b29
12 changed files with 297 additions and 297 deletions

View File

@ -92,7 +92,7 @@ func TestNewInvalid(t *testing.T) {
Details *unversioned.StatusDetails Details *unversioned.StatusDetails
}{ }{
{ {
validation.NewFieldDuplicate("field[0].name", "bar"), validation.NewDuplicateError("field[0].name", "bar"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
@ -103,7 +103,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
validation.NewFieldInvalid("field[0].name", "bar", "detail"), validation.NewInvalidError("field[0].name", "bar", "detail"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
@ -114,7 +114,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
validation.NewFieldNotFound("field[0].name", "bar"), validation.NewNotFoundError("field[0].name", "bar"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
@ -125,7 +125,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
validation.NewFieldNotSupported("field[0].name", "bar", nil), validation.NewNotSupportedError("field[0].name", "bar", nil),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
@ -136,7 +136,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
validation.NewFieldRequired("field[0].name"), validation.NewRequiredError("field[0].name"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",

View File

@ -27,10 +27,10 @@ func ValidateEvent(event *api.Event) validation.ErrorList {
// TODO: There is no namespace required for node. // TODO: There is no namespace required for node.
if event.InvolvedObject.Kind != "Node" && if event.InvolvedObject.Kind != "Node" &&
event.Namespace != event.InvolvedObject.Namespace { event.Namespace != event.InvolvedObject.Namespace {
allErrs = append(allErrs, validation.NewFieldInvalid("involvedObject.namespace", event.InvolvedObject.Namespace, "namespace does not match involvedObject")) allErrs = append(allErrs, validation.NewInvalidError("involvedObject.namespace", event.InvolvedObject.Namespace, "namespace does not match involvedObject"))
} }
if !validation.IsDNS1123Subdomain(event.Namespace) { if !validation.IsDNS1123Subdomain(event.Namespace) {
allErrs = append(allErrs, validation.NewFieldInvalid("namespace", event.Namespace, "")) allErrs = append(allErrs, validation.NewInvalidError("namespace", event.Namespace, ""))
} }
return allErrs return allErrs
} }

File diff suppressed because it is too large Load Diff

View File

@ -42,21 +42,21 @@ func ValidateHorizontalPodAutoscalerName(name string, prefix bool) (bool, string
func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAutoscalerSpec) validation.ErrorList { func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAutoscalerSpec) validation.ErrorList {
allErrs := validation.ErrorList{} allErrs := validation.ErrorList{}
if autoscaler.MinReplicas != nil && *autoscaler.MinReplicas < 1 { if autoscaler.MinReplicas != nil && *autoscaler.MinReplicas < 1 {
allErrs = append(allErrs, validation.NewFieldInvalid("minReplicas", autoscaler.MinReplicas, `must be bigger or equal to 1`)) allErrs = append(allErrs, validation.NewInvalidError("minReplicas", autoscaler.MinReplicas, `must be bigger or equal to 1`))
} }
if autoscaler.MaxReplicas < 1 { if autoscaler.MaxReplicas < 1 {
allErrs = append(allErrs, validation.NewFieldInvalid("maxReplicas", autoscaler.MaxReplicas, `must be bigger or equal to 1`)) allErrs = append(allErrs, validation.NewInvalidError("maxReplicas", autoscaler.MaxReplicas, `must be bigger or equal to 1`))
} }
if autoscaler.MinReplicas != nil && autoscaler.MaxReplicas < *autoscaler.MinReplicas { if autoscaler.MinReplicas != nil && autoscaler.MaxReplicas < *autoscaler.MinReplicas {
allErrs = append(allErrs, validation.NewFieldInvalid("maxReplicas", autoscaler.MaxReplicas, `must be bigger or equal to minReplicas`)) allErrs = append(allErrs, validation.NewInvalidError("maxReplicas", autoscaler.MaxReplicas, `must be bigger or equal to minReplicas`))
} }
if autoscaler.CPUUtilization != nil && autoscaler.CPUUtilization.TargetPercentage < 1 { if autoscaler.CPUUtilization != nil && autoscaler.CPUUtilization.TargetPercentage < 1 {
allErrs = append(allErrs, validation.NewFieldInvalid("cpuUtilization.targetPercentage", autoscaler.CPUUtilization.TargetPercentage, `must be bigger or equal to 1`)) allErrs = append(allErrs, validation.NewInvalidError("cpuUtilization.targetPercentage", autoscaler.CPUUtilization.TargetPercentage, `must be bigger or equal to 1`))
} }
if refErrs := ValidateSubresourceReference(autoscaler.ScaleRef); len(refErrs) > 0 { if refErrs := ValidateSubresourceReference(autoscaler.ScaleRef); len(refErrs) > 0 {
allErrs = append(allErrs, refErrs.Prefix("scaleRef")...) allErrs = append(allErrs, refErrs.Prefix("scaleRef")...)
} else if autoscaler.ScaleRef.Subresource != "scale" { } else if autoscaler.ScaleRef.Subresource != "scale" {
allErrs = append(allErrs, validation.NewFieldNotSupported("scaleRef.subresource", autoscaler.ScaleRef.Subresource, []string{"scale"})) allErrs = append(allErrs, validation.NewNotSupportedError("scaleRef.subresource", autoscaler.ScaleRef.Subresource, []string{"scale"}))
} }
return allErrs return allErrs
} }
@ -64,21 +64,21 @@ func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAuto
func ValidateSubresourceReference(ref extensions.SubresourceReference) validation.ErrorList { func ValidateSubresourceReference(ref extensions.SubresourceReference) validation.ErrorList {
allErrs := validation.ErrorList{} allErrs := validation.ErrorList{}
if len(ref.Kind) == 0 { if len(ref.Kind) == 0 {
allErrs = append(allErrs, validation.NewFieldRequired("kind")) allErrs = append(allErrs, validation.NewRequiredError("kind"))
} else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Kind); !ok { } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Kind); !ok {
allErrs = append(allErrs, validation.NewFieldInvalid("kind", ref.Kind, msg)) allErrs = append(allErrs, validation.NewInvalidError("kind", ref.Kind, msg))
} }
if len(ref.Name) == 0 { if len(ref.Name) == 0 {
allErrs = append(allErrs, validation.NewFieldRequired("name")) allErrs = append(allErrs, validation.NewRequiredError("name"))
} else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Name); !ok { } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Name); !ok {
allErrs = append(allErrs, validation.NewFieldInvalid("name", ref.Name, msg)) allErrs = append(allErrs, validation.NewInvalidError("name", ref.Name, msg))
} }
if len(ref.Subresource) == 0 { if len(ref.Subresource) == 0 {
allErrs = append(allErrs, validation.NewFieldRequired("subresource")) allErrs = append(allErrs, validation.NewRequiredError("subresource"))
} else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Subresource); !ok { } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Subresource); !ok {
allErrs = append(allErrs, validation.NewFieldInvalid("subresource", ref.Subresource, msg)) allErrs = append(allErrs, validation.NewInvalidError("subresource", ref.Subresource, msg))
} }
return allErrs return allErrs
} }
@ -126,10 +126,10 @@ func ValidateThirdPartyResource(obj *extensions.ThirdPartyResource) validation.E
for ix := range obj.Versions { for ix := range obj.Versions {
version := &obj.Versions[ix] version := &obj.Versions[ix]
if len(version.Name) == 0 { if len(version.Name) == 0 {
allErrs = append(allErrs, validation.NewFieldInvalid("name", version, "name can not be empty")) allErrs = append(allErrs, validation.NewInvalidError("name", version, "name can not be empty"))
} }
if versions.Has(version.Name) { if versions.Has(version.Name) {
allErrs = append(allErrs, validation.NewFieldDuplicate("version", version)) allErrs = append(allErrs, validation.NewDuplicateError("version", version))
} }
versions.Insert(version.Name) versions.Insert(version.Name)
} }
@ -180,7 +180,7 @@ func ValidateDaemonSetTemplateUpdate(podTemplate, oldPodTemplate *api.PodTemplat
// In particular, we do not allow updates to container images at this point. // In particular, we do not allow updates to container images at this point.
if !api.Semantic.DeepEqual(oldPodTemplate.Spec, podSpec) { if !api.Semantic.DeepEqual(oldPodTemplate.Spec, podSpec) {
// TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff // TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff
allErrs = append(allErrs, validation.NewFieldInvalid("spec", "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than spec.nodeSelector")) allErrs = append(allErrs, validation.NewInvalidError("spec", "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than spec.nodeSelector"))
} }
return allErrs return allErrs
} }
@ -192,13 +192,13 @@ func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec) validation.ErrorList
allErrs = append(allErrs, ValidatePodSelector(spec.Selector)...) allErrs = append(allErrs, ValidatePodSelector(spec.Selector)...)
if spec.Template == nil { if spec.Template == nil {
allErrs = append(allErrs, validation.NewFieldRequired("template")) allErrs = append(allErrs, validation.NewRequiredError("template"))
return allErrs return allErrs
} }
selector, err := extensions.PodSelectorAsSelector(spec.Selector) selector, err := extensions.PodSelectorAsSelector(spec.Selector)
if err == nil && !selector.Matches(labels.Set(spec.Template.Labels)) { if err == nil && !selector.Matches(labels.Set(spec.Template.Labels)) {
allErrs = append(allErrs, validation.NewFieldInvalid("template.metadata.labels", spec.Template.Labels, "selector does not match template")) allErrs = append(allErrs, validation.NewInvalidError("template.metadata.labels", spec.Template.Labels, "selector does not match template"))
} }
allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(spec.Template).Prefix("template")...) allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(spec.Template).Prefix("template")...)
@ -206,7 +206,7 @@ func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec) validation.ErrorList
allErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes).Prefix("template.spec.volumes")...) allErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes).Prefix("template.spec.volumes")...)
// RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec(). // RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec().
if spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways { if spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways {
allErrs = append(allErrs, validation.NewFieldNotSupported("template.spec.restartPolicy", spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) allErrs = append(allErrs, validation.NewNotSupportedError("template.spec.restartPolicy", spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)}))
} }
return allErrs return allErrs
@ -228,7 +228,7 @@ func ValidatePositiveIntOrPercent(intOrPercent intstr.IntOrString, fieldName str
allErrs := validation.ErrorList{} allErrs := validation.ErrorList{}
if intOrPercent.Type == intstr.String { if intOrPercent.Type == intstr.String {
if !validation.IsValidPercent(intOrPercent.StrVal) { if !validation.IsValidPercent(intOrPercent.StrVal) {
allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, intOrPercent, "value should be int(5) or percentage(5%)")) allErrs = append(allErrs, validation.NewInvalidError(fieldName, intOrPercent, "value should be int(5) or percentage(5%)"))
} }
} else if intOrPercent.Type == intstr.Int { } else if intOrPercent.Type == intstr.Int {
allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(intOrPercent.IntVal), fieldName)...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(intOrPercent.IntVal), fieldName)...)
@ -258,7 +258,7 @@ func IsNotMoreThan100Percent(intOrStringValue intstr.IntOrString, fieldName stri
if !isPercent || value <= 100 { if !isPercent || value <= 100 {
return nil return nil
} }
allErrs = append(allErrs, validation.NewFieldInvalid(fieldName, intOrStringValue, "should not be more than 100%")) allErrs = append(allErrs, validation.NewInvalidError(fieldName, intOrStringValue, "should not be more than 100%"))
return allErrs return allErrs
} }
@ -268,7 +268,7 @@ func ValidateRollingUpdateDeployment(rollingUpdate *extensions.RollingUpdateDepl
allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fieldName+".maxSurge")...) allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fieldName+".maxSurge")...)
if getIntOrPercentValue(rollingUpdate.MaxUnavailable) == 0 && getIntOrPercentValue(rollingUpdate.MaxSurge) == 0 { if getIntOrPercentValue(rollingUpdate.MaxUnavailable) == 0 && getIntOrPercentValue(rollingUpdate.MaxSurge) == 0 {
// Both MaxSurge and MaxUnavailable cannot be zero. // Both MaxSurge and MaxUnavailable cannot be zero.
allErrs = append(allErrs, validation.NewFieldInvalid(fieldName+".maxUnavailable", rollingUpdate.MaxUnavailable, "cannot be 0 when maxSurge is 0 as well")) allErrs = append(allErrs, validation.NewInvalidError(fieldName+".maxUnavailable", rollingUpdate.MaxUnavailable, "cannot be 0 when maxSurge is 0 as well"))
} }
// Validate that MaxUnavailable is not more than 100%. // Validate that MaxUnavailable is not more than 100%.
allErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fieldName+".maxUnavailable")...) allErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fieldName+".maxUnavailable")...)
@ -283,7 +283,7 @@ func ValidateDeploymentStrategy(strategy *extensions.DeploymentStrategy, fieldNa
} }
switch strategy.Type { switch strategy.Type {
case extensions.RecreateDeploymentStrategyType: case extensions.RecreateDeploymentStrategyType:
allErrs = append(allErrs, validation.NewFieldForbidden("rollingUpdate", "rollingUpdate should be nil when strategy type is "+extensions.RecreateDeploymentStrategyType)) allErrs = append(allErrs, validation.NewForbiddenError("rollingUpdate", "rollingUpdate should be nil when strategy type is "+extensions.RecreateDeploymentStrategyType))
case extensions.RollingUpdateDeploymentStrategyType: case extensions.RollingUpdateDeploymentStrategyType:
allErrs = append(allErrs, ValidateRollingUpdateDeployment(strategy.RollingUpdate, "rollingUpdate")...) allErrs = append(allErrs, ValidateRollingUpdateDeployment(strategy.RollingUpdate, "rollingUpdate")...)
} }
@ -322,7 +322,7 @@ func ValidateThirdPartyResourceDataUpdate(update, old *extensions.ThirdPartyReso
func ValidateThirdPartyResourceData(obj *extensions.ThirdPartyResourceData) validation.ErrorList { func ValidateThirdPartyResourceData(obj *extensions.ThirdPartyResourceData) validation.ErrorList {
allErrs := validation.ErrorList{} allErrs := validation.ErrorList{}
if len(obj.Name) == 0 { if len(obj.Name) == 0 {
allErrs = append(allErrs, validation.NewFieldInvalid("name", obj.Name, "name must be non-empty")) allErrs = append(allErrs, validation.NewInvalidError("name", obj.Name, "name must be non-empty"))
} }
return allErrs return allErrs
} }
@ -345,7 +345,7 @@ func ValidateJobSpec(spec *extensions.JobSpec) validation.ErrorList {
allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(*spec.Completions), "completions")...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(*spec.Completions), "completions")...)
} }
if spec.Selector == nil { if spec.Selector == nil {
allErrs = append(allErrs, validation.NewFieldRequired("selector")) allErrs = append(allErrs, validation.NewRequiredError("selector"))
} else { } else {
allErrs = append(allErrs, ValidatePodSelector(spec.Selector).Prefix("selector")...) allErrs = append(allErrs, ValidatePodSelector(spec.Selector).Prefix("selector")...)
} }
@ -353,14 +353,14 @@ func ValidateJobSpec(spec *extensions.JobSpec) validation.ErrorList {
if selector, err := extensions.PodSelectorAsSelector(spec.Selector); err == nil { if selector, err := extensions.PodSelectorAsSelector(spec.Selector); err == nil {
labels := labels.Set(spec.Template.Labels) labels := labels.Set(spec.Template.Labels)
if !selector.Matches(labels) { if !selector.Matches(labels) {
allErrs = append(allErrs, validation.NewFieldInvalid("template.metadata.labels", spec.Template.Labels, "selector does not match template")) allErrs = append(allErrs, validation.NewInvalidError("template.metadata.labels", spec.Template.Labels, "selector does not match template"))
} }
} }
allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template).Prefix("template")...) allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template).Prefix("template")...)
if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure && if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure &&
spec.Template.Spec.RestartPolicy != api.RestartPolicyNever { spec.Template.Spec.RestartPolicy != api.RestartPolicyNever {
allErrs = append(allErrs, validation.NewFieldNotSupported("template.spec.restartPolicy", allErrs = append(allErrs, validation.NewNotSupportedError("template.spec.restartPolicy",
spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)})) spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)}))
} }
return allErrs return allErrs
@ -423,7 +423,7 @@ func ValidateIngressSpec(spec *extensions.IngressSpec) validation.ErrorList {
if spec.Backend != nil { if spec.Backend != nil {
allErrs = append(allErrs, validateIngressBackend(spec.Backend).Prefix("backend")...) allErrs = append(allErrs, validateIngressBackend(spec.Backend).Prefix("backend")...)
} else if len(spec.Rules) == 0 { } else if len(spec.Rules) == 0 {
allErrs = append(allErrs, validation.NewFieldInvalid("rules", spec.Rules, "Either a default backend or a set of host rules are required for ingress.")) allErrs = append(allErrs, validation.NewInvalidError("rules", spec.Rules, "Either a default backend or a set of host rules are required for ingress."))
} }
if len(spec.Rules) > 0 { if len(spec.Rules) > 0 {
allErrs = append(allErrs, validateIngressRules(spec.Rules).Prefix("rules")...) allErrs = append(allErrs, validateIngressRules(spec.Rules).Prefix("rules")...)
@ -450,17 +450,17 @@ func ValidateIngressStatusUpdate(ingress, oldIngress *extensions.Ingress) valida
func validateIngressRules(IngressRules []extensions.IngressRule) validation.ErrorList { func validateIngressRules(IngressRules []extensions.IngressRule) validation.ErrorList {
allErrs := validation.ErrorList{} allErrs := validation.ErrorList{}
if len(IngressRules) == 0 { if len(IngressRules) == 0 {
return append(allErrs, validation.NewFieldRequired("IngressRules")) return append(allErrs, validation.NewRequiredError("IngressRules"))
} }
for _, ih := range IngressRules { for _, ih := range IngressRules {
if len(ih.Host) > 0 { if len(ih.Host) > 0 {
// TODO: Ports and ips are allowed in the host part of a url // TODO: Ports and ips are allowed in the host part of a url
// according to RFC 3986, consider allowing them. // according to RFC 3986, consider allowing them.
if valid, errMsg := apivalidation.NameIsDNSSubdomain(ih.Host, false); !valid { if valid, errMsg := apivalidation.NameIsDNSSubdomain(ih.Host, false); !valid {
allErrs = append(allErrs, validation.NewFieldInvalid("host", ih.Host, errMsg)) allErrs = append(allErrs, validation.NewInvalidError("host", ih.Host, errMsg))
} }
if isIP := (net.ParseIP(ih.Host) != nil); isIP { if isIP := (net.ParseIP(ih.Host) != nil); isIP {
allErrs = append(allErrs, validation.NewFieldInvalid("host", ih.Host, "Host must be a DNS name, not ip address")) allErrs = append(allErrs, validation.NewInvalidError("host", ih.Host, "Host must be a DNS name, not ip address"))
} }
} }
allErrs = append(allErrs, validateIngressRuleValue(&ih.IngressRuleValue).Prefix("ingressRule")...) allErrs = append(allErrs, validateIngressRuleValue(&ih.IngressRuleValue).Prefix("ingressRule")...)
@ -479,12 +479,12 @@ func validateIngressRuleValue(ingressRule *extensions.IngressRuleValue) validati
func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue) validation.ErrorList { func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue) validation.ErrorList {
allErrs := validation.ErrorList{} allErrs := validation.ErrorList{}
if len(httpIngressRuleValue.Paths) == 0 { if len(httpIngressRuleValue.Paths) == 0 {
allErrs = append(allErrs, validation.NewFieldRequired("paths")) allErrs = append(allErrs, validation.NewRequiredError("paths"))
} }
for _, rule := range httpIngressRuleValue.Paths { for _, rule := range httpIngressRuleValue.Paths {
if len(rule.Path) > 0 { if len(rule.Path) > 0 {
if !strings.HasPrefix(rule.Path, "/") { if !strings.HasPrefix(rule.Path, "/") {
allErrs = append(allErrs, validation.NewFieldInvalid("path", rule.Path, "path must begin with /")) allErrs = append(allErrs, validation.NewInvalidError("path", rule.Path, "path must begin with /"))
} }
// TODO: More draconian path regex validation. // TODO: More draconian path regex validation.
// Path must be a valid regex. This is the basic requirement. // Path must be a valid regex. This is the basic requirement.
@ -497,7 +497,7 @@ func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRu
// the user is confusing url regexes with path regexes. // the user is confusing url regexes with path regexes.
_, err := regexp.CompilePOSIX(rule.Path) _, err := regexp.CompilePOSIX(rule.Path)
if err != nil { if err != nil {
allErrs = append(allErrs, validation.NewFieldInvalid("path", rule.Path, "httpIngressRuleValue.path must be a valid regex.")) allErrs = append(allErrs, validation.NewInvalidError("path", rule.Path, "httpIngressRuleValue.path must be a valid regex."))
} }
} }
allErrs = append(allErrs, validateIngressBackend(&rule.Backend).Prefix("backend")...) allErrs = append(allErrs, validateIngressBackend(&rule.Backend).Prefix("backend")...)
@ -511,19 +511,19 @@ func validateIngressBackend(backend *extensions.IngressBackend) validation.Error
// All backends must reference a single local service by name, and a single service port by name or number. // All backends must reference a single local service by name, and a single service port by name or number.
if len(backend.ServiceName) == 0 { if len(backend.ServiceName) == 0 {
return append(allErrs, validation.NewFieldRequired("serviceName")) return append(allErrs, validation.NewRequiredError("serviceName"))
} else if ok, errMsg := apivalidation.ValidateServiceName(backend.ServiceName, false); !ok { } else if ok, errMsg := apivalidation.ValidateServiceName(backend.ServiceName, false); !ok {
allErrs = append(allErrs, validation.NewFieldInvalid("serviceName", backend.ServiceName, errMsg)) allErrs = append(allErrs, validation.NewInvalidError("serviceName", backend.ServiceName, errMsg))
} }
if backend.ServicePort.Type == intstr.String { if backend.ServicePort.Type == intstr.String {
if !validation.IsDNS1123Label(backend.ServicePort.StrVal) { if !validation.IsDNS1123Label(backend.ServicePort.StrVal) {
allErrs = append(allErrs, validation.NewFieldInvalid("servicePort", backend.ServicePort.StrVal, apivalidation.DNS1123LabelErrorMsg)) allErrs = append(allErrs, validation.NewInvalidError("servicePort", backend.ServicePort.StrVal, apivalidation.DNS1123LabelErrorMsg))
} }
if !validation.IsValidPortName(backend.ServicePort.StrVal) { if !validation.IsValidPortName(backend.ServicePort.StrVal) {
allErrs = append(allErrs, validation.NewFieldInvalid("servicePort", backend.ServicePort.StrVal, apivalidation.PortNameErrorMsg)) allErrs = append(allErrs, validation.NewInvalidError("servicePort", backend.ServicePort.StrVal, apivalidation.PortNameErrorMsg))
} }
} else if !validation.IsValidPortNum(backend.ServicePort.IntVal) { } else if !validation.IsValidPortNum(backend.ServicePort.IntVal) {
allErrs = append(allErrs, validation.NewFieldInvalid("servicePort", backend.ServicePort, apivalidation.PortRangeErrorMsg)) allErrs = append(allErrs, validation.NewInvalidError("servicePort", backend.ServicePort, apivalidation.PortRangeErrorMsg))
} }
return allErrs return allErrs
} }
@ -531,23 +531,23 @@ func validateIngressBackend(backend *extensions.IngressBackend) validation.Error
func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec) validation.ErrorList { func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec) validation.ErrorList {
allErrs := validation.ErrorList{} allErrs := validation.ErrorList{}
if spec.MinNodes < 0 { if spec.MinNodes < 0 {
allErrs = append(allErrs, validation.NewFieldInvalid("minNodes", spec.MinNodes, `must be non-negative`)) allErrs = append(allErrs, validation.NewInvalidError("minNodes", spec.MinNodes, `must be non-negative`))
} }
if spec.MaxNodes < spec.MinNodes { if spec.MaxNodes < spec.MinNodes {
allErrs = append(allErrs, validation.NewFieldInvalid("maxNodes", spec.MaxNodes, `must be bigger or equal to minNodes`)) allErrs = append(allErrs, validation.NewInvalidError("maxNodes", spec.MaxNodes, `must be bigger or equal to minNodes`))
} }
if len(spec.TargetUtilization) == 0 { if len(spec.TargetUtilization) == 0 {
allErrs = append(allErrs, validation.NewFieldRequired("targetUtilization")) allErrs = append(allErrs, validation.NewRequiredError("targetUtilization"))
} }
for _, target := range spec.TargetUtilization { for _, target := range spec.TargetUtilization {
if len(target.Resource) == 0 { if len(target.Resource) == 0 {
allErrs = append(allErrs, validation.NewFieldRequired("targetUtilization.resource")) allErrs = append(allErrs, validation.NewRequiredError("targetUtilization.resource"))
} }
if target.Value <= 0 { if target.Value <= 0 {
allErrs = append(allErrs, validation.NewFieldInvalid("targetUtilization.value", target.Value, "must be greater than 0")) allErrs = append(allErrs, validation.NewInvalidError("targetUtilization.value", target.Value, "must be greater than 0"))
} }
if target.Value > 1 { if target.Value > 1 {
allErrs = append(allErrs, validation.NewFieldInvalid("targetUtilization.value", target.Value, "must be less or equal 1")) allErrs = append(allErrs, validation.NewInvalidError("targetUtilization.value", target.Value, "must be less or equal 1"))
} }
} }
return allErrs return allErrs
@ -556,10 +556,10 @@ func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec) valida
func ValidateClusterAutoscaler(autoscaler *extensions.ClusterAutoscaler) validation.ErrorList { func ValidateClusterAutoscaler(autoscaler *extensions.ClusterAutoscaler) validation.ErrorList {
allErrs := validation.ErrorList{} allErrs := validation.ErrorList{}
if autoscaler.Name != "ClusterAutoscaler" { if autoscaler.Name != "ClusterAutoscaler" {
allErrs = append(allErrs, validation.NewFieldInvalid("name", autoscaler.Name, `name must be ClusterAutoscaler`)) allErrs = append(allErrs, validation.NewInvalidError("name", autoscaler.Name, `name must be ClusterAutoscaler`))
} }
if autoscaler.Namespace != api.NamespaceDefault { if autoscaler.Namespace != api.NamespaceDefault {
allErrs = append(allErrs, validation.NewFieldInvalid("namespace", autoscaler.Namespace, `namespace must be default`)) allErrs = append(allErrs, validation.NewInvalidError("namespace", autoscaler.Namespace, `namespace must be default`))
} }
allErrs = append(allErrs, validateClusterAutoscalerSpec(autoscaler.Spec)...) allErrs = append(allErrs, validateClusterAutoscalerSpec(autoscaler.Spec)...)
return allErrs return allErrs
@ -582,14 +582,14 @@ func ValidatePodSelectorRequirement(sr extensions.PodSelectorRequirement) valida
switch sr.Operator { switch sr.Operator {
case extensions.PodSelectorOpIn, extensions.PodSelectorOpNotIn: case extensions.PodSelectorOpIn, extensions.PodSelectorOpNotIn:
if len(sr.Values) == 0 { if len(sr.Values) == 0 {
allErrs = append(allErrs, validation.NewFieldInvalid("values", sr.Values, "must be non-empty when operator is In or NotIn")) allErrs = append(allErrs, validation.NewInvalidError("values", sr.Values, "must be non-empty when operator is In or NotIn"))
} }
case extensions.PodSelectorOpExists, extensions.PodSelectorOpDoesNotExist: case extensions.PodSelectorOpExists, extensions.PodSelectorOpDoesNotExist:
if len(sr.Values) > 0 { if len(sr.Values) > 0 {
allErrs = append(allErrs, validation.NewFieldInvalid("values", sr.Values, "must be empty when operator is Exists or DoesNotExist")) allErrs = append(allErrs, validation.NewInvalidError("values", sr.Values, "must be empty when operator is Exists or DoesNotExist"))
} }
default: default:
allErrs = append(allErrs, validation.NewFieldInvalid("operator", sr.Operator, "not a valid pod selector operator")) allErrs = append(allErrs, validation.NewInvalidError("operator", sr.Operator, "not a valid pod selector operator"))
} }
allErrs = append(allErrs, apivalidation.ValidateLabelName(sr.Key, "key")...) allErrs = append(allErrs, apivalidation.ValidateLabelName(sr.Key, "key")...)
return allErrs return allErrs
@ -600,7 +600,7 @@ func ValidateScale(scale *extensions.Scale) validation.ErrorList {
allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&scale.ObjectMeta, true, apivalidation.NameIsDNSSubdomain).Prefix("metadata")...) allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&scale.ObjectMeta, true, apivalidation.NameIsDNSSubdomain).Prefix("metadata")...)
if scale.Spec.Replicas < 0 { if scale.Spec.Replicas < 0 {
allErrs = append(allErrs, validation.NewFieldInvalid("spec.replicas", scale.Spec.Replicas, "must be non-negative")) allErrs = append(allErrs, validation.NewInvalidError("spec.replicas", scale.Spec.Replicas, "must be non-negative"))
} }
return allErrs return allErrs

View File

@ -274,11 +274,11 @@ func TestCheckInvalidErr(t *testing.T) {
expected string expected string
}{ }{
{ {
errors.NewInvalid("Invalid1", "invalidation", validation.ErrorList{validation.NewFieldInvalid("Cause", "single", "details")}), errors.NewInvalid("Invalid1", "invalidation", validation.ErrorList{validation.NewInvalidError("Cause", "single", "details")}),
`Error from server: Invalid1 "invalidation" is invalid: Cause: invalid value 'single', Details: details`, `Error from server: Invalid1 "invalidation" is invalid: Cause: invalid value 'single', Details: details`,
}, },
{ {
errors.NewInvalid("Invalid2", "invalidation", validation.ErrorList{validation.NewFieldInvalid("Cause", "multi1", "details"), validation.NewFieldInvalid("Cause", "multi2", "details")}), errors.NewInvalid("Invalid2", "invalidation", validation.ErrorList{validation.NewInvalidError("Cause", "multi1", "details"), validation.NewInvalidError("Cause", "multi2", "details")}),
`Error from server: Invalid2 "invalidation" is invalid: [Cause: invalid value 'multi1', Details: details, Cause: invalid value 'multi2', Details: details]`, `Error from server: Invalid2 "invalidation" is invalid: [Cause: invalid value 'multi1', Details: details, Cause: invalid value 'multi2', Details: details]`,
}, },
{ {

View File

@ -317,7 +317,7 @@ func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventReco
} else { } else {
name := kubecontainer.GetPodFullName(pod) name := kubecontainer.GetPodFullName(pod)
if names.Has(name) { if names.Has(name) {
errlist = append(errlist, utilvalidation.NewFieldDuplicate("name", pod.Name)) errlist = append(errlist, utilvalidation.NewDuplicateError("name", pod.Name))
} else { } else {
names.Insert(name) names.Insert(name)
} }

View File

@ -701,14 +701,14 @@ const qualifiedNameErrorMsg string = "must match regex [" + validation.DNS1123Su
func validateLabelKey(k string) error { func validateLabelKey(k string) error {
if !validation.IsQualifiedName(k) { if !validation.IsQualifiedName(k) {
return validation.NewFieldInvalid("label key", k, qualifiedNameErrorMsg) return validation.NewInvalidError("label key", k, qualifiedNameErrorMsg)
} }
return nil return nil
} }
func validateLabelValue(v string) error { func validateLabelValue(v string) error {
if !validation.IsValidLabelValue(v) { if !validation.IsValidLabelValue(v) {
return validation.NewFieldInvalid("label value", v, qualifiedNameErrorMsg) return validation.NewInvalidError("label value", v, qualifiedNameErrorMsg)
} }
return nil return nil
} }

View File

@ -129,10 +129,10 @@ func (r *BindingREST) Create(ctx api.Context, obj runtime.Object) (out runtime.O
binding := obj.(*api.Binding) binding := obj.(*api.Binding)
// TODO: move me to a binding strategy // TODO: move me to a binding strategy
if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" { if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" {
return nil, errors.NewInvalid("binding", binding.Name, validation.ErrorList{validation.NewFieldInvalid("to.kind", binding.Target.Kind, "must be empty or 'Node'")}) return nil, errors.NewInvalid("binding", binding.Name, validation.ErrorList{validation.NewInvalidError("to.kind", binding.Target.Kind, "must be empty or 'Node'")})
} }
if len(binding.Target.Name) == 0 { if len(binding.Target.Name) == 0 {
return nil, errors.NewInvalid("binding", binding.Name, validation.ErrorList{validation.NewFieldRequired("to.name")}) return nil, errors.NewInvalid("binding", binding.Name, validation.ErrorList{validation.NewRequiredError("to.name")})
} }
err = r.assignPod(ctx, binding.Name, binding.Target.Name, binding.Annotations) err = r.assignPod(ctx, binding.Name, binding.Target.Name, binding.Annotations)
out = &unversioned.Status{Status: unversioned.StatusSuccess} out = &unversioned.Status{Status: unversioned.StatusSuccess}

View File

@ -84,7 +84,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err
// Allocate next available. // Allocate next available.
ip, err := rs.serviceIPs.AllocateNext() ip, err := rs.serviceIPs.AllocateNext()
if err != nil { if err != nil {
el := utilvalidation.ErrorList{utilvalidation.NewFieldInvalid("spec.clusterIP", service.Spec.ClusterIP, err.Error())} el := utilvalidation.ErrorList{utilvalidation.NewInvalidError("spec.clusterIP", service.Spec.ClusterIP, err.Error())}
return nil, errors.NewInvalid("Service", service.Name, el) return nil, errors.NewInvalid("Service", service.Name, el)
} }
service.Spec.ClusterIP = ip.String() service.Spec.ClusterIP = ip.String()
@ -92,7 +92,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err
} else if api.IsServiceIPSet(service) { } else if api.IsServiceIPSet(service) {
// Try to respect the requested IP. // Try to respect the requested IP.
if err := rs.serviceIPs.Allocate(net.ParseIP(service.Spec.ClusterIP)); err != nil { if err := rs.serviceIPs.Allocate(net.ParseIP(service.Spec.ClusterIP)); err != nil {
el := utilvalidation.ErrorList{utilvalidation.NewFieldInvalid("spec.clusterIP", service.Spec.ClusterIP, err.Error())} el := utilvalidation.ErrorList{utilvalidation.NewInvalidError("spec.clusterIP", service.Spec.ClusterIP, err.Error())}
return nil, errors.NewInvalid("Service", service.Name, el) return nil, errors.NewInvalid("Service", service.Name, el)
} }
releaseServiceIP = true releaseServiceIP = true
@ -104,13 +104,13 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err
if servicePort.NodePort != 0 { if servicePort.NodePort != 0 {
err := nodePortOp.Allocate(servicePort.NodePort) err := nodePortOp.Allocate(servicePort.NodePort)
if err != nil { if err != nil {
el := utilvalidation.ErrorList{utilvalidation.NewFieldInvalid("nodePort", servicePort.NodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") el := utilvalidation.ErrorList{utilvalidation.NewInvalidError("nodePort", servicePort.NodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports")
return nil, errors.NewInvalid("Service", service.Name, el) return nil, errors.NewInvalid("Service", service.Name, el)
} }
} else if assignNodePorts { } else if assignNodePorts {
nodePort, err := nodePortOp.AllocateNext() nodePort, err := nodePortOp.AllocateNext()
if err != nil { if err != nil {
el := utilvalidation.ErrorList{utilvalidation.NewFieldInvalid("nodePort", servicePort.NodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") el := utilvalidation.ErrorList{utilvalidation.NewInvalidError("nodePort", servicePort.NodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports")
return nil, errors.NewInvalid("Service", service.Name, el) return nil, errors.NewInvalid("Service", service.Name, el)
} }
servicePort.NodePort = nodePort servicePort.NodePort = nodePort
@ -223,14 +223,14 @@ func (rs *REST) Update(ctx api.Context, obj runtime.Object) (runtime.Object, boo
if !contains(oldNodePorts, nodePort) { if !contains(oldNodePorts, nodePort) {
err := nodePortOp.Allocate(nodePort) err := nodePortOp.Allocate(nodePort)
if err != nil { if err != nil {
el := utilvalidation.ErrorList{utilvalidation.NewFieldInvalid("nodePort", nodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") el := utilvalidation.ErrorList{utilvalidation.NewInvalidError("nodePort", nodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports")
return nil, false, errors.NewInvalid("Service", service.Name, el) return nil, false, errors.NewInvalid("Service", service.Name, el)
} }
} }
} else { } else {
nodePort, err = nodePortOp.AllocateNext() nodePort, err = nodePortOp.AllocateNext()
if err != nil { if err != nil {
el := utilvalidation.ErrorList{utilvalidation.NewFieldInvalid("nodePort", nodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports") el := utilvalidation.ErrorList{utilvalidation.NewInvalidError("nodePort", nodePort, err.Error())}.PrefixIndex(i).Prefix("spec.ports")
return nil, false, errors.NewInvalid("Service", service.Name, el) return nil, false, errors.NewInvalid("Service", service.Name, el)
} }
servicePort.NodePort = nodePort servicePort.NodePort = nodePort

View File

@ -48,7 +48,7 @@ func ParseWatchResourceVersion(resourceVersion, kind string) (uint64, error) {
version, err := strconv.ParseUint(resourceVersion, 10, 64) version, err := strconv.ParseUint(resourceVersion, 10, 64)
if err != nil { if err != nil {
// TODO: Does this need to be a ErrorList? I can't convince myself it does. // TODO: Does this need to be a ErrorList? I can't convince myself it does.
return 0, errors.NewInvalid(kind, "", utilvalidation.ErrorList{utilvalidation.NewFieldInvalid("resourceVersion", resourceVersion, err.Error())}) return 0, errors.NewInvalid(kind, "", utilvalidation.ErrorList{utilvalidation.NewInvalidError("resourceVersion", resourceVersion, err.Error())})
} }
return version + 1, nil return version + 1, nil
} }

View File

@ -65,29 +65,29 @@ type ErrorType string
// TODO: These values are duplicated in api/types.go, but there's a circular dep. Fix it. // TODO: These values are duplicated in api/types.go, but there's a circular dep. Fix it.
const ( const (
// ErrorTypeNotFound is used to report failure to find a requested value // ErrorTypeNotFound is used to report failure to find a requested value
// (e.g. looking up an ID). See NewFieldNotFound. // (e.g. looking up an ID). See NewNotFoundError.
ErrorTypeNotFound ErrorType = "FieldValueNotFound" ErrorTypeNotFound ErrorType = "FieldValueNotFound"
// ErrorTypeRequired is used to report required values that are not // ErrorTypeRequired is used to report required values that are not
// provided (e.g. empty strings, null values, or empty arrays). See // provided (e.g. empty strings, null values, or empty arrays). See
// NewFieldRequired. // NewRequiredError.
ErrorTypeRequired ErrorType = "FieldValueRequired" ErrorTypeRequired ErrorType = "FieldValueRequired"
// ErrorTypeDuplicate is used to report collisions of values that must be // ErrorTypeDuplicate is used to report collisions of values that must be
// unique (e.g. unique IDs). See NewFieldDuplicate. // unique (e.g. unique IDs). See NewDuplicateError.
ErrorTypeDuplicate ErrorType = "FieldValueDuplicate" ErrorTypeDuplicate ErrorType = "FieldValueDuplicate"
// ErrorTypeInvalid is used to report malformed values (e.g. failed regex // ErrorTypeInvalid is used to report malformed values (e.g. failed regex
// match, too long, out of bounds). See NewFieldInvalid. // match, too long, out of bounds). See NewInvalidError.
ErrorTypeInvalid ErrorType = "FieldValueInvalid" ErrorTypeInvalid ErrorType = "FieldValueInvalid"
// ErrorTypeNotSupported is used to report unknown values for enumerated // ErrorTypeNotSupported is used to report unknown values for enumerated
// fields (e.g. a list of valid values). See NewFieldNotSupported. // fields (e.g. a list of valid values). See NewNotSupportedError.
ErrorTypeNotSupported ErrorType = "FieldValueNotSupported" ErrorTypeNotSupported ErrorType = "FieldValueNotSupported"
// ErrorTypeForbidden is used to report valid (as per formatting rules) // ErrorTypeForbidden is used to report valid (as per formatting rules)
// values which would be accepted under some conditions, but which are not // values which would be accepted under some conditions, but which are not
// permitted by the current conditions (such as security policy). See // permitted by the current conditions (such as security policy). See
// NewFieldForbidden. // NewForbiddenError.
ErrorTypeForbidden ErrorType = "FieldValueForbidden" ErrorTypeForbidden ErrorType = "FieldValueForbidden"
// ErrorTypeTooLong is used to report that the given value is too long. // ErrorTypeTooLong is used to report that the given value is too long.
// This is similar to ErrorTypeInvalid, but the error will not include the // This is similar to ErrorTypeInvalid, but the error will not include the
// too-long value. See NewFieldTooLong. // too-long value. See NewTooLongError.
ErrorTypeTooLong ErrorType = "FieldValueTooLong" ErrorTypeTooLong ErrorType = "FieldValueTooLong"
// ErrorTypeInternal is used to report other errors that are not related // ErrorTypeInternal is used to report other errors that are not related
// to user input. // to user input.
@ -119,35 +119,35 @@ func (t ErrorType) String() string {
} }
} }
// NewFieldNotFound returns a *Error indicating "value not found". This is // NewNotFoundError returns a *Error indicating "value not found". This is
// used to report failure to find a requested value (e.g. looking up an ID). // used to report failure to find a requested value (e.g. looking up an ID).
func NewFieldNotFound(field string, value interface{}) *Error { func NewNotFoundError(field string, value interface{}) *Error {
return &Error{ErrorTypeNotFound, field, value, ""} return &Error{ErrorTypeNotFound, field, value, ""}
} }
// NewFieldRequired returns a *Error indicating "value required". This is used // NewRequiredError returns a *Error indicating "value required". This is used
// to report required values that are not provided (e.g. empty strings, null // to report required values that are not provided (e.g. empty strings, null
// values, or empty arrays). // values, or empty arrays).
func NewFieldRequired(field string) *Error { func NewRequiredError(field string) *Error {
return &Error{ErrorTypeRequired, field, "", ""} return &Error{ErrorTypeRequired, field, "", ""}
} }
// NewFieldDuplicate returns a *Error indicating "duplicate value". This is // NewDuplicateError returns a *Error indicating "duplicate value". This is
// used to report collisions of values that must be unique (e.g. names or IDs). // used to report collisions of values that must be unique (e.g. names or IDs).
func NewFieldDuplicate(field string, value interface{}) *Error { func NewDuplicateError(field string, value interface{}) *Error {
return &Error{ErrorTypeDuplicate, field, value, ""} return &Error{ErrorTypeDuplicate, field, value, ""}
} }
// NewFieldInvalid returns a *Error indicating "invalid value". This is used // NewInvalidError returns a *Error indicating "invalid value". This is used
// to report malformed values (e.g. failed regex match, too long, out of bounds). // to report malformed values (e.g. failed regex match, too long, out of bounds).
func NewFieldInvalid(field string, value interface{}, detail string) *Error { func NewInvalidError(field string, value interface{}, detail string) *Error {
return &Error{ErrorTypeInvalid, field, value, detail} return &Error{ErrorTypeInvalid, field, value, detail}
} }
// NewFieldNotSupported returns a *Error indicating "unsupported value". // NewNotSupportedError returns a *Error indicating "unsupported value".
// This is used to report unknown values for enumerated fields (e.g. a list of // This is used to report unknown values for enumerated fields (e.g. a list of
// valid values). // valid values).
func NewFieldNotSupported(field string, value interface{}, validValues []string) *Error { func NewNotSupportedError(field string, value interface{}, validValues []string) *Error {
detail := "" detail := ""
if validValues != nil && len(validValues) > 0 { if validValues != nil && len(validValues) > 0 {
detail = "supported values: " + strings.Join(validValues, ", ") detail = "supported values: " + strings.Join(validValues, ", ")
@ -155,19 +155,19 @@ func NewFieldNotSupported(field string, value interface{}, validValues []string)
return &Error{ErrorTypeNotSupported, field, value, detail} return &Error{ErrorTypeNotSupported, field, value, detail}
} }
// NewFieldForbidden returns a *Error indicating "forbidden". This is used to // NewForbiddenError returns a *Error indicating "forbidden". This is used to
// report valid (as per formatting rules) values which would be accepted under // report valid (as per formatting rules) values which would be accepted under
// some conditions, but which are not permitted by current conditions (e.g. // some conditions, but which are not permitted by current conditions (e.g.
// security policy). // security policy).
func NewFieldForbidden(field string, value interface{}) *Error { func NewForbiddenError(field string, value interface{}) *Error {
return &Error{ErrorTypeForbidden, field, value, ""} return &Error{ErrorTypeForbidden, field, value, ""}
} }
// NewFieldTooLong returns a *Error indicating "too long". This is used to // NewTooLongError returns a *Error indicating "too long". This is used to
// report that the given value is too long. This is similar to // report that the given value is too long. This is similar to
// NewFieldInvalid, but the returned error will not include the too-long // NewInvalidError, but the returned error will not include the too-long
// value. // value.
func NewFieldTooLong(field string, value interface{}, maxLength int) *Error { func NewTooLongError(field string, value interface{}, maxLength int) *Error {
return &Error{ErrorTypeTooLong, field, value, fmt.Sprintf("must have at most %d characters", maxLength)} return &Error{ErrorTypeTooLong, field, value, fmt.Sprintf("must have at most %d characters", maxLength)}
} }

View File

@ -28,23 +28,23 @@ func TestMakeFuncs(t *testing.T) {
expected ErrorType expected ErrorType
}{ }{
{ {
func() *Error { return NewFieldInvalid("f", "v", "d") }, func() *Error { return NewInvalidError("f", "v", "d") },
ErrorTypeInvalid, ErrorTypeInvalid,
}, },
{ {
func() *Error { return NewFieldNotSupported("f", "v", nil) }, func() *Error { return NewNotSupportedError("f", "v", nil) },
ErrorTypeNotSupported, ErrorTypeNotSupported,
}, },
{ {
func() *Error { return NewFieldDuplicate("f", "v") }, func() *Error { return NewDuplicateError("f", "v") },
ErrorTypeDuplicate, ErrorTypeDuplicate,
}, },
{ {
func() *Error { return NewFieldNotFound("f", "v") }, func() *Error { return NewNotFoundError("f", "v") },
ErrorTypeNotFound, ErrorTypeNotFound,
}, },
{ {
func() *Error { return NewFieldRequired("f") }, func() *Error { return NewRequiredError("f") },
ErrorTypeRequired, ErrorTypeRequired,
}, },
{ {
@ -62,7 +62,7 @@ func TestMakeFuncs(t *testing.T) {
} }
func TestErrorUsefulMessage(t *testing.T) { func TestErrorUsefulMessage(t *testing.T) {
s := NewFieldInvalid("foo", "bar", "deet").Error() s := NewInvalidError("foo", "bar", "deet").Error()
t.Logf("message: %v", s) t.Logf("message: %v", s)
for _, part := range []string{"foo", "bar", "deet", ErrorTypeInvalid.String()} { for _, part := range []string{"foo", "bar", "deet", ErrorTypeInvalid.String()} {
if !strings.Contains(s, part) { if !strings.Contains(s, part) {
@ -76,7 +76,7 @@ func TestErrorUsefulMessage(t *testing.T) {
Inner interface{} Inner interface{}
KV map[string]int KV map[string]int
} }
s = NewFieldInvalid( s = NewInvalidError(
"foo", "foo",
&complicated{ &complicated{
Baz: 1, Baz: 1,
@ -102,8 +102,8 @@ func TestToAggregate(t *testing.T) {
testCases := []ErrorList{ testCases := []ErrorList{
nil, nil,
{}, {},
{NewFieldInvalid("f", "v", "d")}, {NewInvalidError("f", "v", "d")},
{NewFieldInvalid("f", "v", "d"), NewInternalError("", fmt.Errorf("e"))}, {NewInvalidError("f", "v", "d"), NewInternalError("", fmt.Errorf("e"))},
} }
for i, tc := range testCases { for i, tc := range testCases {
agg := tc.ToAggregate() agg := tc.ToAggregate()
@ -121,9 +121,9 @@ func TestToAggregate(t *testing.T) {
func TestErrListFilter(t *testing.T) { func TestErrListFilter(t *testing.T) {
list := ErrorList{ list := ErrorList{
NewFieldInvalid("test.field", "", ""), NewInvalidError("test.field", "", ""),
NewFieldInvalid("field.test", "", ""), NewInvalidError("field.test", "", ""),
NewFieldDuplicate("test", "value"), NewDuplicateError("test", "value"),
} }
if len(list.Filter(NewErrorTypeMatcher(ErrorTypeDuplicate))) != 2 { if len(list.Filter(NewErrorTypeMatcher(ErrorTypeDuplicate))) != 2 {
t.Errorf("should not filter") t.Errorf("should not filter")
@ -139,15 +139,15 @@ func TestErrListPrefix(t *testing.T) {
Expected string Expected string
}{ }{
{ {
NewFieldNotFound("[0].bar", "value"), NewNotFoundError("[0].bar", "value"),
"foo[0].bar", "foo[0].bar",
}, },
{ {
NewFieldInvalid("field", "value", ""), NewInvalidError("field", "value", ""),
"foo.field", "foo.field",
}, },
{ {
NewFieldDuplicate("", "value"), NewDuplicateError("", "value"),
"foo", "foo",
}, },
} }
@ -169,15 +169,15 @@ func TestErrListPrefixIndex(t *testing.T) {
Expected string Expected string
}{ }{
{ {
NewFieldNotFound("[0].bar", "value"), NewNotFoundError("[0].bar", "value"),
"[1][0].bar", "[1][0].bar",
}, },
{ {
NewFieldInvalid("field", "value", ""), NewInvalidError("field", "value", ""),
"[1].field", "[1].field",
}, },
{ {
NewFieldDuplicate("", "value"), NewDuplicateError("", "value"),
"[1]", "[1]",
}, },
} }