diff --git a/pkg/devfile/generator/generators_test.go b/pkg/devfile/generator/generators_test.go index b390c5e4..f311d975 100644 --- a/pkg/devfile/generator/generators_test.go +++ b/pkg/devfile/generator/generators_test.go @@ -2,6 +2,7 @@ package generator import ( "fmt" + "github.com/stretchr/testify/assert" "reflect" "strings" "testing" @@ -47,6 +48,8 @@ func TestGetContainers(t *testing.T) { }, } + errMatches := "an expetced error" + tests := []struct { name string containerComponents []v1.Component @@ -56,7 +59,7 @@ func TestGetContainers(t *testing.T) { wantContainerImage string wantContainerEnv []corev1.EnvVar wantContainerVolMount []corev1.VolumeMount - wantErr bool + wantErr *string }{ { name: "Container with default project root", @@ -202,6 +205,10 @@ func TestGetContainers(t *testing.T) { }, }, }, + { + name: "Simulating error case, check if error matches", + wantErr: &errMatches, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -221,6 +228,9 @@ func TestGetContainers(t *testing.T) { } else { mockGetComponents.Return(tt.filteredComponents, nil).AnyTimes() } + if tt.wantErr != nil { + mockGetComponents.Return(nil, fmt.Errorf(*tt.wantErr)) + } mockDevfileData.EXPECT().GetProjects(common.DevfileOptions{}).Return(projects, nil).AnyTimes() devObj := parser.DevfileObj{ @@ -229,23 +239,25 @@ func TestGetContainers(t *testing.T) { containers, err := GetContainers(devObj, tt.filterOptions) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestGetContainers() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestGetContainers() error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { for _, container := range containers { if container.Name != tt.wantContainerName { - t.Errorf("TestGetContainers error: Name mismatch - got: %s, wanted: %s", container.Name, tt.wantContainerName) + t.Errorf("TestGetContainers() error: Name mismatch - got: %s, wanted: %s", container.Name, tt.wantContainerName) } if container.Image != tt.wantContainerImage { - t.Errorf("TestGetContainers error: Image mismatch - got: %s, wanted: %s", container.Image, tt.wantContainerImage) + t.Errorf("TestGetContainers() error: Image mismatch - got: %s, wanted: %s", container.Image, tt.wantContainerImage) } if len(container.Env) > 0 && !reflect.DeepEqual(container.Env, tt.wantContainerEnv) { - t.Errorf("TestGetContainers error: Env mismatch - got: %+v, wanted: %+v", container.Env, tt.wantContainerEnv) + t.Errorf("TestGetContainers() error: Env mismatch - got: %+v, wanted: %+v", container.Env, tt.wantContainerEnv) } if len(container.VolumeMounts) > 0 && !reflect.DeepEqual(container.VolumeMounts, tt.wantContainerVolMount) { - t.Errorf("TestGetContainers error: Vol Mount mismatch - got: %+v, wanted: %+v", container.VolumeMounts, tt.wantContainerVolMount) + t.Errorf("TestGetContainers() error: Vol Mount mismatch - got: %+v, wanted: %+v", container.VolumeMounts, tt.wantContainerVolMount) } } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestGetContainers(): Error message does not match") } }) } @@ -259,12 +271,14 @@ func TestGetVolumesAndVolumeMounts(t *testing.T) { volumeName string } + errMatches := "an expetced error" + tests := []struct { name string components []v1.Component volumeNameToVolInfo map[string]VolumeInfo wantContainerToVol map[string][]testVolumeMountInfo - wantErr bool + wantErr *string }{ { name: "One volume mounted", @@ -289,7 +303,6 @@ func TestGetVolumesAndVolumeMounts(t *testing.T) { }, }, }, - wantErr: false, }, { name: "One volume mounted at diff locations", @@ -332,7 +345,6 @@ func TestGetVolumesAndVolumeMounts(t *testing.T) { }, }, }, - wantErr: false, }, { name: "One volume mounted at diff container components", @@ -388,12 +400,10 @@ func TestGetVolumesAndVolumeMounts(t *testing.T) { }, }, }, - wantErr: false, }, { - name: "Invalid case simulating no container components", - components: nil, - wantErr: true, + name: "Simulating error case, check if error matches", + wantErr: &errMatches, }, } @@ -424,9 +434,9 @@ func TestGetVolumesAndVolumeMounts(t *testing.T) { return } - if tt.wantErr { + if tt.wantErr != nil { // simulate error condition - mockGetComponents.Return(nil, fmt.Errorf("mock error")) + mockGetComponents.Return(nil, fmt.Errorf(*tt.wantErr)) } @@ -436,8 +446,8 @@ func TestGetVolumesAndVolumeMounts(t *testing.T) { } pvcVols, err := GetVolumesAndVolumeMounts(devObj, volumeParams, common.DevfileOptions{}) - if tt.wantErr == (err == nil) { - t.Errorf("TestGetVolumesAndVolumeMounts() error = %v, wantErr %v", err, tt.wantErr) + if (tt.wantErr == nil) != (err == nil) { + t.Errorf("TestGetVolumesAndVolumeMounts() error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { // check if the pvc volumes returned are correct for _, volInfo := range tt.volumeNameToVolInfo { @@ -449,14 +459,14 @@ func TestGetVolumesAndVolumeMounts(t *testing.T) { } if !matched { - t.Errorf("TestGetVolumesAndVolumeMounts error - could not find volume details %s in the actual result", volInfo.VolumeName) + t.Errorf("TestGetVolumesAndVolumeMounts() error: could not find volume details %s in the actual result", volInfo.VolumeName) } } // check the volume mounts of the containers for _, container := range containers { if volMounts, ok := tt.wantContainerToVol[container.Name]; !ok { - t.Errorf("TestGetVolumesAndVolumeMounts error - did not find the expected container %s", container.Name) + t.Errorf("TestGetVolumesAndVolumeMounts() error: did not find the expected container %s", container.Name) return } else { for _, expectedVolMount := range volMounts { @@ -468,11 +478,13 @@ func TestGetVolumesAndVolumeMounts(t *testing.T) { } if !matched { - t.Errorf("TestGetVolumesAndVolumeMounts error - could not find volume mount details for path %s in the actual result for container %s", expectedVolMount.mountPath, container.Name) + t.Errorf("TestGetVolumesAndVolumeMounts() error: could not find volume mount details for path %s in the actual result for container %s", expectedVolMount.mountPath, container.Name) } } } } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestGetVolumesAndVolumeMounts(): Error message does not match") } }) } @@ -506,7 +518,7 @@ func TestGetVolumeMountPath(t *testing.T) { path := GetVolumeMountPath(tt.volumeMount) if path != tt.wantPath { - t.Errorf("TestGetVolumeMountPath error: mount path mismatch, expected: %v got: %v", tt.wantPath, path) + t.Errorf("TestGetVolumeMountPath() error: mount path mismatch, expected: %v got: %v", tt.wantPath, path) } }) } @@ -584,12 +596,14 @@ func TestGetInitContainers(t *testing.T) { longContainerName := "thisisaverylongcontainerandkuberneteshasalimitforanamesize-exec2" trimmedLongContainerName := util.TruncateString(longContainerName, containerNameMaxLen) + errMatches := "an expetced error" + tests := []struct { name string eventCommands []string wantInitContainer map[string]corev1.Container longName bool - wantErr bool + wantErr *string }{ { name: "Composite and Exec events", @@ -611,13 +625,13 @@ func TestGetInitContainers(t *testing.T) { }, }, { - name: "Simulate error condition", + name: "Simulate error case, check if error matches", eventCommands: []string{ "apply1", "apply3", "apply2", }, - wantErr: true, + wantErr: &errMatches, }, { name: "Long Container Name", @@ -662,8 +676,8 @@ func TestGetInitContainers(t *testing.T) { mockDevfileData.EXPECT().GetEvents().Return(preStartEvents).AnyTimes() mockGetCommands.Return(append(applyCommands, compCommands...), nil).AnyTimes() - if tt.wantErr { - mockGetCommands.Return(nil, fmt.Errorf("mock error")).AnyTimes() + if tt.wantErr != nil { + mockGetCommands.Return(nil, fmt.Errorf(*tt.wantErr)).AnyTimes() } devObj := parser.DevfileObj{ @@ -671,9 +685,10 @@ func TestGetInitContainers(t *testing.T) { } initContainers, err := GetInitContainers(devObj) - if (err != nil) != tt.wantErr { - t.Errorf("TestGetInitContainers() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestGetInitContainers() error: %v, wantErr %v", err, tt.wantErr) } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestGetInitContainers: Error message does not match") return } diff --git a/pkg/devfile/generator/utils_test.go b/pkg/devfile/generator/utils_test.go index a73f83bf..9b83984e 100644 --- a/pkg/devfile/generator/utils_test.go +++ b/pkg/devfile/generator/utils_test.go @@ -1,6 +1,7 @@ package generator import ( + "github.com/stretchr/testify/assert" "path/filepath" "reflect" "strings" @@ -86,7 +87,7 @@ func TestConvertEnvs(t *testing.T) { t.Run(tt.name, func(t *testing.T) { envVars := convertEnvs(tt.envVars) if !reflect.DeepEqual(tt.want, envVars) { - t.Errorf("expected %v, wanted %v", envVars, tt.want) + t.Errorf("TestConvertEnvs() error: expected %v, wanted %v", envVars, tt.want) } }) } @@ -152,7 +153,7 @@ func TestConvertPorts(t *testing.T) { t.Run(tt.name, func(t *testing.T) { ports := convertPorts(tt.endpoints) if !reflect.DeepEqual(tt.want, ports) { - t.Errorf("expected %v, wanted %v", ports, tt.want) + t.Errorf("TestConvertPorts() error: expected %v, wanted %v", ports, tt.want) } }) } @@ -162,7 +163,7 @@ func TestGetResourceReqs(t *testing.T) { limit := "1024Mi" quantity, err := resource.ParseQuantity(limit) if err != nil { - t.Errorf("expected %v", err) + t.Errorf("TestGetResourceReqs() unexpected error: %v", err) } tests := []struct { name string @@ -212,7 +213,7 @@ func TestGetResourceReqs(t *testing.T) { t.Run(tt.name, func(t *testing.T) { req := getResourceReqs(tt.component) if !reflect.DeepEqual(tt.want, req) { - t.Errorf("expected %v, wanted %v", req, tt.want) + t.Errorf("TestGetResourceReqs() error: expected %v, wanted %v", req, tt.want) } }) } @@ -243,12 +244,12 @@ func TestAddSyncRootFolder(t *testing.T) { syncRootFolder := addSyncRootFolder(&container, tt.sourceMapping) if syncRootFolder != tt.wantSyncRootFolder { - t.Errorf("TestAddSyncRootFolder sync root folder error - expected %v got %v", tt.wantSyncRootFolder, syncRootFolder) + t.Errorf("TestAddSyncRootFolder() sync root folder error: expected %v got %v", tt.wantSyncRootFolder, syncRootFolder) } for _, env := range container.Env { if env.Name == EnvProjectsRoot && env.Value != tt.wantSyncRootFolder { - t.Errorf("PROJECT_ROOT error expected %s, actual %s", tt.wantSyncRootFolder, env.Value) + t.Errorf("TestAddSyncRootFolder() PROJECT_ROOT error: expected %s, actual %s", tt.wantSyncRootFolder, env.Value) } } }) @@ -262,17 +263,19 @@ func TestAddSyncFolder(t *testing.T) { invalidClonePaths := []string{"/var", "../var", "pkg/../../var"} sourceVolumePath := "/projects/app" + absoluteClonePathErr := "the clonePath .* in the devfile project .* must be a relative path" + escapeClonePathErr := "the clonePath .* in the devfile project .* cannot escape the value defined by [$]PROJECTS_ROOT. Please avoid using \"..\" in clonePath" + tests := []struct { name string projects []v1.Project want string - wantErr bool + wantErr *string }{ { name: "No projects", projects: []v1.Project{}, want: sourceVolumePath, - wantErr: false, }, { name: "One project", @@ -288,8 +291,7 @@ func TestAddSyncFolder(t *testing.T) { }, }, }, - want: filepath.ToSlash(filepath.Join(sourceVolumePath, projectNames[0])), - wantErr: false, + want: filepath.ToSlash(filepath.Join(sourceVolumePath, projectNames[0])), }, { name: "Multiple projects", @@ -313,8 +315,7 @@ func TestAddSyncFolder(t *testing.T) { }, }, }, - want: filepath.ToSlash(filepath.Join(sourceVolumePath, projectNames[0])), - wantErr: false, + want: filepath.ToSlash(filepath.Join(sourceVolumePath, projectNames[0])), }, { name: "Clone path set", @@ -329,8 +330,7 @@ func TestAddSyncFolder(t *testing.T) { }, }, }, - want: filepath.ToSlash(filepath.Join(sourceVolumePath, projectClonePath)), - wantErr: false, + want: filepath.ToSlash(filepath.Join(sourceVolumePath, projectClonePath)), }, { name: "Invalid clone path, set with absolute path", @@ -348,7 +348,7 @@ func TestAddSyncFolder(t *testing.T) { }, }, want: "", - wantErr: true, + wantErr: &absoluteClonePathErr, }, { name: "Invalid clone path, starts with ..", @@ -366,7 +366,7 @@ func TestAddSyncFolder(t *testing.T) { }, }, want: "", - wantErr: true, + wantErr: &escapeClonePathErr, }, { name: "Invalid clone path, contains ..", @@ -382,7 +382,7 @@ func TestAddSyncFolder(t *testing.T) { }, }, want: "", - wantErr: true, + wantErr: &escapeClonePathErr, }, } for _, tt := range tests { @@ -391,14 +391,16 @@ func TestAddSyncFolder(t *testing.T) { err := addSyncFolder(&container, sourceVolumePath, tt.projects) - if !tt.wantErr == (err != nil) { - t.Errorf("expected %v, actual %v", tt.wantErr, err) + if (tt.wantErr != nil) != (err != nil) { + t.Errorf("TestAddSyncFolder() error: unexpected error %v, want %v", err, tt.wantErr) } else if err == nil { for _, env := range container.Env { if env.Name == EnvProjectsSrc && env.Value != tt.want { - t.Errorf("expected %s, actual %s", tt.want, env.Value) + t.Errorf("TestAddSyncFolder() error: expected %s, actual %s", tt.want, env.Value) } } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestAddSyncFolder(): Error message should match") } }) } @@ -466,63 +468,63 @@ func TestGetContainer(t *testing.T) { container := getContainer(containerParams) if container.Name != tt.containerName { - t.Errorf("expected %s, actual %s", tt.containerName, container.Name) + t.Errorf("TestGetContainer() error: expected containerName %s, actual %s", tt.containerName, container.Name) } if container.Image != tt.image { - t.Errorf("expected %s, actual %s", tt.image, container.Image) + t.Errorf("TestGetContainer() error: expected image %s, actual %s", tt.image, container.Image) } if tt.isPrivileged { if *container.SecurityContext.Privileged != tt.isPrivileged { - t.Errorf("expected %t, actual %t", tt.isPrivileged, *container.SecurityContext.Privileged) + t.Errorf("TestGetContainer() error: expected isPrivileged %t, actual %t", tt.isPrivileged, *container.SecurityContext.Privileged) } } else if tt.isPrivileged == false && container.SecurityContext != nil { t.Errorf("expected security context to be nil but it was defined") } if len(container.Command) != len(tt.command) { - t.Errorf("expected %d, actual %d", len(tt.command), len(container.Command)) + t.Errorf("TestGetContainer() error: expected command length %d, actual %d", len(tt.command), len(container.Command)) } else { for i := range container.Command { if container.Command[i] != tt.command[i] { - t.Errorf("expected %s, actual %s", tt.command[i], container.Command[i]) + t.Errorf("TestGetContainer() error: expected command %s, actual %s", tt.command[i], container.Command[i]) } } } if len(container.Args) != len(tt.args) { - t.Errorf("expected %d, actual %d", len(tt.args), len(container.Args)) + t.Errorf("TestGetContainer() error: expected container args length %d, actual %d", len(tt.args), len(container.Args)) } else { for i := range container.Args { if container.Args[i] != tt.args[i] { - t.Errorf("expected %s, actual %s", tt.args[i], container.Args[i]) + t.Errorf("TestGetContainer() error: expected container args %s, actual %s", tt.args[i], container.Args[i]) } } } if len(container.Env) != len(tt.envVars) { - t.Errorf("expected %d, actual %d", len(tt.envVars), len(container.Env)) + t.Errorf("TestGetContainer() error: expected container env length %d, actual %d", len(tt.envVars), len(container.Env)) } else { for i := range container.Env { if container.Env[i].Name != tt.envVars[i].Name { - t.Errorf("expected name %s, actual name %s", tt.envVars[i].Name, container.Env[i].Name) + t.Errorf("TestGetContainer() error: expected env name %s, actual %s", tt.envVars[i].Name, container.Env[i].Name) } if container.Env[i].Value != tt.envVars[i].Value { - t.Errorf("expected value %s, actual value %s", tt.envVars[i].Value, container.Env[i].Value) + t.Errorf("TestGetContainer() error: expected env value %s, actual %s", tt.envVars[i].Value, container.Env[i].Value) } } } if len(container.Ports) != len(tt.ports) { - t.Errorf("expected %d, actual %d", len(tt.ports), len(container.Ports)) + t.Errorf("TestGetContainer() error: expected container port length %d, actual %d", len(tt.ports), len(container.Ports)) } else { for i := range container.Ports { if container.Ports[i].Name != tt.ports[i].Name { - t.Errorf("expected name %s, actual name %s", tt.ports[i].Name, container.Ports[i].Name) + t.Errorf("TestGetContainer() error: expected port name %s, actual %s", tt.ports[i].Name, container.Ports[i].Name) } if container.Ports[i].ContainerPort != tt.ports[i].ContainerPort { - t.Errorf("expected port number is %v, actual %v", tt.ports[i].ContainerPort, container.Ports[i].ContainerPort) + t.Errorf("TestGetContainer() error: expected port number %v, actual %v", tt.ports[i].ContainerPort, container.Ports[i].ContainerPort) } } } @@ -581,22 +583,22 @@ func TestGetPodTemplateSpec(t *testing.T) { podTemplateSpec := getPodTemplateSpec(podTemplateSpecParams) if podTemplateSpec.Name != tt.podName { - t.Errorf("expected %s, actual %s", tt.podName, podTemplateSpec.Name) + t.Errorf("TestGetPodTemplateSpec() error: expected podName %s, actual %s", tt.podName, podTemplateSpec.Name) } if podTemplateSpec.Namespace != tt.namespace { - t.Errorf("expected %s, actual %s", tt.namespace, podTemplateSpec.Namespace) + t.Errorf("TestGetPodTemplateSpec() error: expected namespace %s, actual %s", tt.namespace, podTemplateSpec.Namespace) } if !hasVolumeWithName("vol1", podTemplateSpec.Spec.Volumes) { - t.Errorf("volume with name: %s not found", "vol1") + t.Errorf("TestGetPodTemplateSpec() error: volume with name: %s not found", "vol1") } if !reflect.DeepEqual(podTemplateSpec.Labels, tt.labels) { - t.Errorf("expected %+v, actual %+v", tt.labels, podTemplateSpec.Labels) + t.Errorf("TestGetPodTemplateSpec() error: expected labels %+v, actual %+v", tt.labels, podTemplateSpec.Labels) } if !reflect.DeepEqual(podTemplateSpec.Spec.Containers, container) { - t.Errorf("expected %+v, actual %+v", container, podTemplateSpec.Spec.Containers) + t.Errorf("TestGetPodTemplateSpec() error: expected container %+v, actual %+v", container, podTemplateSpec.Spec.Containers) } if !reflect.DeepEqual(podTemplateSpec.Spec.InitContainers, container) { - t.Errorf("expected %+v, actual %+v", container, podTemplateSpec.Spec.InitContainers) + t.Errorf("TestGetPodTemplateSpec() error: expected InitContainers %+v, actual %+v", container, podTemplateSpec.Spec.InitContainers) } }) } @@ -613,7 +615,6 @@ func TestGetServiceSpec(t *testing.T) { labels map[string]string filterOptions common.DevfileOptions wantPorts []corev1.ServicePort - wantErr bool }{ { name: "multiple endpoints share the same port", @@ -644,7 +645,6 @@ func TestGetServiceSpec(t *testing.T) { TargetPort: intstr.FromInt(8080), }, }, - wantErr: false, }, { name: "multiple endpoints have different ports", @@ -682,7 +682,6 @@ func TestGetServiceSpec(t *testing.T) { TargetPort: intstr.FromInt(9090), }, }, - wantErr: false, }, { name: "filter components", @@ -728,7 +727,6 @@ func TestGetServiceSpec(t *testing.T) { TargetPort: intstr.FromInt(9090), }, }, - wantErr: false, filteredComponents: []v1.Component{ { Name: "testcontainer2", @@ -782,21 +780,21 @@ func TestGetServiceSpec(t *testing.T) { serviceSpec, err := getServiceSpec(devObj, tt.labels, tt.filterOptions) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestGetServiceSpec() error = %v, wantErr %v", err, tt.wantErr) - } else if err == nil { + if err != nil { + t.Errorf("TestGetServiceSpec() unexpected error: %v", err) + } else { if !reflect.DeepEqual(serviceSpec.Selector, tt.labels) { - t.Errorf("expected service selector is %v, actual %v", tt.labels, serviceSpec.Selector) + t.Errorf("TestGetServiceSpec() error: expected service selector is %v, actual %v", tt.labels, serviceSpec.Selector) } if len(serviceSpec.Ports) != len(tt.wantPorts) { - t.Errorf("expected service ports length is %v, actual %v", len(tt.wantPorts), len(serviceSpec.Ports)) + t.Errorf("TestGetServiceSpec() error: expected service ports length is %v, actual %v", len(tt.wantPorts), len(serviceSpec.Ports)) } else { for i := range serviceSpec.Ports { if serviceSpec.Ports[i].Name != tt.wantPorts[i].Name { - t.Errorf("expected name %s, actual name %s", tt.wantPorts[i].Name, serviceSpec.Ports[i].Name) + t.Errorf("TestGetServiceSpec() error: expected name %s, actual name %s", tt.wantPorts[i].Name, serviceSpec.Ports[i].Name) } if serviceSpec.Ports[i].Port != tt.wantPorts[i].Port { - t.Errorf("expected port number is %v, actual %v", tt.wantPorts[i].Port, serviceSpec.Ports[i].Port) + t.Errorf("TestGetServiceSpec() error: expected port number is %v, actual %v", tt.wantPorts[i].Port, serviceSpec.Ports[i].Port) } } } @@ -814,7 +812,6 @@ func TestGetPortExposure(t *testing.T) { filteredComponents []v1.Component filterOptions common.DevfileOptions wantMap map[int]v1.EndpointExposure - wantErr bool }{ { name: "devfile has single container with single endpoint", @@ -1120,7 +1117,6 @@ func TestGetPortExposure(t *testing.T) { "firstStringWrong": "firstStringValue", }, }, - wantErr: false, }, } for _, tt := range tests { @@ -1147,10 +1143,10 @@ func TestGetPortExposure(t *testing.T) { mapCreated, err := getPortExposure(devObj, tt.filterOptions) // Checks for unexpected error cases - if !tt.wantErr == (err != nil) { - t.Errorf("TestGetPortExposure unexpected error %v, wantErr %v", err, tt.wantErr) - } else if err == nil && !reflect.DeepEqual(mapCreated, tt.wantMap) { - t.Errorf("TestGetPortExposure Expected: %v, got %v", tt.wantMap, mapCreated) + if err != nil { + t.Errorf("TestGetPortExposure() unexpected error: %v", err) + } else if !reflect.DeepEqual(mapCreated, tt.wantMap) { + t.Errorf("TestGetPortExposure() error: expected: %v, got %v", tt.wantMap, mapCreated) } }) @@ -1183,19 +1179,19 @@ func TestGetIngressSpec(t *testing.T) { ingressSpec := getIngressSpec(tt.parameter) if ingressSpec.Rules[0].Host != tt.parameter.IngressDomain { - t.Errorf("expected %s, actual %s", tt.parameter.IngressDomain, ingressSpec.Rules[0].Host) + t.Errorf("TestGetIngressSpec() error: expected ingressDomain %s, actual %s", tt.parameter.IngressDomain, ingressSpec.Rules[0].Host) } if ingressSpec.Rules[0].HTTP.Paths[0].Backend.ServicePort != tt.parameter.PortNumber { - t.Errorf("expected %v, actual %v", tt.parameter.PortNumber, ingressSpec.Rules[0].HTTP.Paths[0].Backend.ServicePort) + t.Errorf("TestGetIngressSpec() error: expected portNumber %v, actual %v", tt.parameter.PortNumber, ingressSpec.Rules[0].HTTP.Paths[0].Backend.ServicePort) } if ingressSpec.Rules[0].HTTP.Paths[0].Backend.ServiceName != tt.parameter.ServiceName { - t.Errorf("expected %s, actual %s", tt.parameter.ServiceName, ingressSpec.Rules[0].HTTP.Paths[0].Backend.ServiceName) + t.Errorf("TestGetIngressSpec() error: expected serviceName %s, actual %s", tt.parameter.ServiceName, ingressSpec.Rules[0].HTTP.Paths[0].Backend.ServiceName) } if ingressSpec.TLS[0].SecretName != tt.parameter.TLSSecretName { - t.Errorf("expected %s, actual %s", tt.parameter.TLSSecretName, ingressSpec.TLS[0].SecretName) + t.Errorf("TestGetIngressSpec() error: expected TLSSecretName %s, actual %s", tt.parameter.TLSSecretName, ingressSpec.TLS[0].SecretName) } }) @@ -1227,19 +1223,19 @@ func TestGetNetworkingV1IngressSpec(t *testing.T) { ingressSpec := getNetworkingV1IngressSpec(tt.parameter) if ingressSpec.Rules[0].Host != tt.parameter.IngressDomain { - t.Errorf("expected %s, actual %s", tt.parameter.IngressDomain, ingressSpec.Rules[0].Host) + t.Errorf("TestGetNetworkingV1IngressSpec() error: expected IngressDomain %s, actual %s", tt.parameter.IngressDomain, ingressSpec.Rules[0].Host) } if ingressSpec.Rules[0].HTTP.Paths[0].Backend.Service.Port.Number != tt.parameter.PortNumber.IntVal { - t.Errorf("expected %v, actual %v", tt.parameter.PortNumber, ingressSpec.Rules[0].HTTP.Paths[0].Backend.Service.Port.Number) + t.Errorf("TestGetNetworkingV1IngressSpec() error: expected PortNumber %v, actual %v", tt.parameter.PortNumber, ingressSpec.Rules[0].HTTP.Paths[0].Backend.Service.Port.Number) } if ingressSpec.Rules[0].HTTP.Paths[0].Backend.Service.Name != tt.parameter.ServiceName { - t.Errorf("expected %s, actual %s", tt.parameter.ServiceName, ingressSpec.Rules[0].HTTP.Paths[0].Backend.Service.Name) + t.Errorf("TestGetNetworkingV1IngressSpec() error: expected ServiceName %s, actual %s", tt.parameter.ServiceName, ingressSpec.Rules[0].HTTP.Paths[0].Backend.Service.Name) } if ingressSpec.TLS[0].SecretName != tt.parameter.TLSSecretName { - t.Errorf("expected %s, actual %s", tt.parameter.TLSSecretName, ingressSpec.TLS[0].SecretName) + t.Errorf("TestGetNetworkingV1IngressSpec() error: expected TLSSecretName %s, actual %s", tt.parameter.TLSSecretName, ingressSpec.TLS[0].SecretName) } }) @@ -1282,19 +1278,19 @@ func TestGetRouteSpec(t *testing.T) { routeSpec := getRouteSpec(tt.parameter) if routeSpec.Port.TargetPort != tt.parameter.PortNumber { - t.Errorf("expected %v, actual %v", tt.parameter.PortNumber, routeSpec.Port.TargetPort) + t.Errorf("TestGetRouteSpec() error: expected PortNumber %v, actual %v", tt.parameter.PortNumber, routeSpec.Port.TargetPort) } if routeSpec.To.Name != tt.parameter.ServiceName { - t.Errorf("expected %s, actual %s", tt.parameter.ServiceName, routeSpec.To.Name) + t.Errorf("TestGetRouteSpec() error: expected ServiceName %s, actual %s", tt.parameter.ServiceName, routeSpec.To.Name) } if routeSpec.Path != tt.parameter.Path { - t.Errorf("expected %s, actual %s", tt.parameter.Path, routeSpec.Path) + t.Errorf("TestGetRouteSpec() error: expected Path %s, actual %s", tt.parameter.Path, routeSpec.Path) } if (routeSpec.TLS != nil) != tt.parameter.Secure { - t.Errorf("the route TLS does not match secure level %v", tt.parameter.Secure) + t.Errorf("TestGetRouteSpec() error: the route TLS does not match secure level %v", tt.parameter.Secure) } }) @@ -1326,16 +1322,16 @@ func TestGetPVCSpec(t *testing.T) { quantity, err := resource.ParseQuantity(tt.size) // Checks for unexpected error cases if !tt.wantErr == (err != nil) { - t.Errorf("resource.ParseQuantity unexpected error %v, wantErr %v", err, tt.wantErr) + t.Errorf("TestGetPVCSpec() error: resource.ParseQuantity unexpected error %v, wantErr %v", err, tt.wantErr) } else if err == nil { pvcSpec := getPVCSpec(quantity) if pvcSpec.AccessModes[0] != corev1.ReadWriteOnce { - t.Errorf("AccessMode Error: expected %s, actual %s", corev1.ReadWriteMany, pvcSpec.AccessModes[0]) + t.Errorf("TestGetPVCSpec() error: AccessMode Error: expected %s, actual %s", corev1.ReadWriteMany, pvcSpec.AccessModes[0]) } pvcSpecQuantity := pvcSpec.Resources.Requests["storage"] if pvcSpecQuantity.String() != quantity.String() { - t.Errorf("pvcSpec.Resources.Requests Error: expected %v, actual %v", pvcSpecQuantity.String(), quantity.String()) + t.Errorf("TestGetPVCSpec() error: pvcSpec.Resources.Requests Error: expected %v, actual %v", pvcSpecQuantity.String(), quantity.String()) } } }) @@ -1390,15 +1386,15 @@ func TestGetBuildConfigSpec(t *testing.T) { buildConfigSpec := getBuildConfigSpec(params) if !strings.Contains(buildConfigSpec.CommonSpec.Output.To.Name, image) { - t.Error("TestGetBuildConfigSpec error - build config output name does not match") + t.Error("TestGetBuildConfigSpec() error: build config output name does not match") } if buildConfigSpec.Source.Git.Ref != tt.GitRef || buildConfigSpec.Source.Git.URI != tt.GitURL { - t.Error("TestGetBuildConfigSpec error - build config git source does not match") + t.Error("TestGetBuildConfigSpec() error: build config git source does not match") } if buildConfigSpec.CommonSpec.Source.ContextDir != tt.ContextDir { - t.Error("TestGetBuildConfigSpec error - context dir does not match") + t.Error("TestGetBuildConfigSpec() error: context dir does not match") } }) } @@ -1424,11 +1420,11 @@ func TestGetPVC(t *testing.T) { volume := getPVC(tt.volumeName, tt.pvc) if volume.Name != tt.volumeName { - t.Errorf("TestGetPVC error: volume name does not match; expected %s got %s", tt.volumeName, volume.Name) + t.Errorf("TestGetPVC() error: volume name does not match; expected %s got %s", tt.volumeName, volume.Name) } if volume.PersistentVolumeClaim.ClaimName != tt.pvc { - t.Errorf("TestGetPVC error: pvc name does not match; expected %s got %s", tt.pvc, volume.PersistentVolumeClaim.ClaimName) + t.Errorf("TestGetPVC() error: pvc name does not match; expected %s got %s", tt.pvc, volume.PersistentVolumeClaim.ClaimName) } }) } @@ -1489,7 +1485,7 @@ func TestAddVolumeMountToContainers(t *testing.T) { } if mountPathCount != len(tt.containerMountPathsMap[tt.container.Name]) { - t.Errorf("Volume Mounts for %s have not been properly mounted to the container", tt.volumeName) + t.Errorf("TestAddVolumeMountToContainers() error: Volume Mounts for %s have not been properly mounted to the container", tt.volumeName) } }) } diff --git a/pkg/devfile/parser/configurables_test.go b/pkg/devfile/parser/configurables_test.go index c6ab652a..899a869e 100644 --- a/pkg/devfile/parser/configurables_test.go +++ b/pkg/devfile/parser/configurables_test.go @@ -130,17 +130,17 @@ func TestAddAndRemoveEnvVars(t *testing.T) { err := tt.currentDevfile.AddEnvVars(tt.listToAdd) if err != nil { - t.Errorf("error while adding env vars %+v", err.Error()) + t.Errorf("TestAddAndRemoveEnvVars() unexpected error while adding env vars %+v", err.Error()) } err = tt.currentDevfile.RemoveEnvVars(tt.listToRemove) if err != nil { - t.Errorf("error while removing env vars %+v", err.Error()) + t.Errorf("TestAddAndRemoveEnvVars() unexpected error while removing env vars %+v", err.Error()) } if !reflect.DeepEqual(tt.currentDevfile.Data, tt.wantDevFile.Data) { - t.Errorf("wanted: %v, got: %v, difference at %v", tt.wantDevFile, tt.currentDevfile, pretty.Compare(tt.currentDevfile.Data, tt.wantDevFile.Data)) + t.Errorf("TestAddAndRemoveEnvVars() error: wanted: %v, got: %v, difference at %v", tt.wantDevFile, tt.currentDevfile, pretty.Compare(tt.currentDevfile.Data, tt.wantDevFile.Data)) } }) diff --git a/pkg/devfile/parser/context/apiVersion_test.go b/pkg/devfile/parser/context/apiVersion_test.go index 36eb8be4..aef49747 100644 --- a/pkg/devfile/parser/context/apiVersion_test.go +++ b/pkg/devfile/parser/context/apiVersion_test.go @@ -55,11 +55,11 @@ func TestSetDevfileAPIVersion(t *testing.T) { got := d.apiVersion if !reflect.DeepEqual(gotErr, tt.wantErr) { - t.Errorf("unexpected error: '%v', wantErr: '%v'", gotErr, tt.wantErr) + t.Errorf("TestSetDevfileAPIVersion() unexpected error: '%v', wantErr: '%v'", gotErr, tt.wantErr) } if got != tt.want { - t.Errorf("want: '%v', got: '%v'", tt.want, got) + t.Errorf("TestSetDevfileAPIVersion() want: '%v', got: '%v'", tt.want, got) } }) } @@ -80,7 +80,7 @@ func TestGetApiVersion(t *testing.T) { ) if got != want { - t.Errorf("want: '%v', got: '%v'", want, got) + t.Errorf("TestGetApiVersion() want: '%v', got: '%v'", want, got) } }) } diff --git a/pkg/devfile/parser/context/context_test.go b/pkg/devfile/parser/context/context_test.go index 0ceb8a35..02eb88f5 100644 --- a/pkg/devfile/parser/context/context_test.go +++ b/pkg/devfile/parser/context/context_test.go @@ -1,26 +1,28 @@ package parser import ( + "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" "testing" ) func TestPopulateFromBytes(t *testing.T) { + failedToConvertYamlErr := "failed to convert devfile yaml to json: yaml: mapping values are not allowed in this context" + tests := []struct { name string dataFunc func() []byte - expectError bool + expectError *string }{ { - name: "valid data passed", - dataFunc: validJsonRawContent200, - expectError: false, + name: "valid data passed", + dataFunc: validJsonRawContent200, }, { name: "invalid data passed", dataFunc: invalidJsonRawContent200, - expectError: true, + expectError: &failedToConvertYamlErr, }, } for _, tt := range tests { @@ -38,16 +40,17 @@ func TestPopulateFromBytes(t *testing.T) { ) defer testServer.Close() err := d.PopulateFromURL() - if tt.expectError && err == nil { - t.Errorf("expected error, didn't get one") - } else if !tt.expectError && err != nil { - t.Errorf("unexpected error '%v'", err) + if (tt.expectError != nil) != (err != nil) { + t.Errorf("TestPopulateFromBytes(): unexpected error: %v, wantErr: %v", err, tt.expectError) + } else if tt.expectError != nil { + assert.Regexp(t, *tt.expectError, err.Error(), "TestPopulateFromBytes(): Error message should match") } }) } } func TestPopulateFromInvalidURL(t *testing.T) { + expectError := ".*invalid URI for request" t.Run("Populate from invalid URL", func(t *testing.T) { var ( d = DevfileCtx{ @@ -58,7 +61,9 @@ func TestPopulateFromInvalidURL(t *testing.T) { err := d.PopulateFromURL() if err == nil { - t.Errorf("expected an error, didn't get one") + t.Errorf("TestPopulateFromInvalidURL(): expected an error, didn't get one") + } else { + assert.Regexp(t, expectError, err.Error(), "TestPopulateFromInvalidURL(): Error message should match") } }) } diff --git a/pkg/devfile/parser/context/schema_test.go b/pkg/devfile/parser/context/schema_test.go index 9e45007a..3d0710fb 100644 --- a/pkg/devfile/parser/context/schema_test.go +++ b/pkg/devfile/parser/context/schema_test.go @@ -1,6 +1,7 @@ package parser import ( + "github.com/stretchr/testify/assert" "testing" v200 "github.com/devfile/library/pkg/devfile/parser/data/v2/2.0.0" @@ -130,10 +131,11 @@ func TestValidateDevfileSchema(t *testing.T) { err := d.ValidateDevfileSchema() if err != nil { - t.Errorf("unexpected error: '%v'", err) + t.Errorf("TestValidateDevfileSchema() unexpected error: '%v'", err) } }) + expectedErr := "invalid devfile schema. errors :\n*.*schemaVersion is required" t.Run("invalid 2.0.0 json schema", func(t *testing.T) { var ( @@ -145,7 +147,9 @@ func TestValidateDevfileSchema(t *testing.T) { err := d.ValidateDevfileSchema() if err == nil { - t.Errorf("expected error, didn't get one") + t.Errorf("TestValidateDevfileSchema() expected error, didn't get one") + } else { + assert.Regexp(t, expectedErr, err.Error(), "TestValidateDevfileSchema(): Error message should match") } }) } diff --git a/pkg/devfile/parser/data/v2/attributes_test.go b/pkg/devfile/parser/data/v2/attributes_test.go index 133bb7a1..d6be2dbe 100644 --- a/pkg/devfile/parser/data/v2/attributes_test.go +++ b/pkg/devfile/parser/data/v2/attributes_test.go @@ -1,6 +1,7 @@ package v2 import ( + "github.com/stretchr/testify/assert" "reflect" "testing" @@ -11,12 +12,13 @@ import ( ) func TestGetAttributes(t *testing.T) { + schema200NoAttributeErr := "top-level attributes is not supported in devfile schema version 2.0.0" tests := []struct { name string devfilev2 *DevfileV2 wantAttributes attributes.Attributes - wantErr bool + wantErr *string }{ { name: "Schema 2.0.0 does not have attributes", @@ -27,7 +29,7 @@ func TestGetAttributes(t *testing.T) { }, }, }, - wantErr: true, + wantErr: &schema200NoAttributeErr, }, { name: "Schema 2.1.0 has attributes", @@ -45,16 +47,34 @@ func TestGetAttributes(t *testing.T) { }, wantAttributes: attributes.Attributes{}.PutString("key1", "value1").PutString("key2", "value2"), }, + { + name: "Schema 2.2.0 has attributes", + devfilev2: &DevfileV2{ + v1alpha2.Devfile{ + DevfileHeader: devfilepkg.DevfileHeader{ + SchemaVersion: "2.2.0", + }, + DevWorkspaceTemplateSpec: v1alpha2.DevWorkspaceTemplateSpec{ + DevWorkspaceTemplateSpecContent: v1alpha2.DevWorkspaceTemplateSpecContent{ + Attributes: attributes.Attributes{}.PutString("key1", "value1").PutString("key2", "value2"), + }, + }, + }, + }, + wantAttributes: attributes.Attributes{}.PutString("key1", "value1").PutString("key2", "value2"), + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { attributes, err := tt.devfilev2.GetAttributes() - if tt.wantErr == (err == nil) { - t.Errorf("TestGetAttributes error - %v, wantErr %v", err, tt.wantErr) + if (tt.wantErr == nil) != (err == nil) { + t.Errorf("TestGetAttributes() error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { if !reflect.DeepEqual(attributes, tt.wantAttributes) { - t.Errorf("TestGetAttributes error - actual does not equal expected, difference at %+v", pretty.Compare(attributes, tt.wantAttributes)) + t.Errorf("TestGetAttributes() error: actual does not equal expected, difference at %+v", pretty.Compare(attributes, tt.wantAttributes)) } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestGetAttributes(): Error message should match") } }) } @@ -68,13 +88,16 @@ func TestUpdateAttributes(t *testing.T) { }, } + schema200NoAttributeErr := "top-level attributes is not supported in devfile schema version 2.0.0" + invalidKeyErr := "cannot update top-level attribute, key .* is not present" + tests := []struct { name string devfilev2 *DevfileV2 key string value interface{} wantAttributes attributes.Attributes - wantErr bool + wantErr *string }{ { name: "Schema 2.0.0 does not have attributes", @@ -85,7 +108,7 @@ func TestUpdateAttributes(t *testing.T) { }, }, }, - wantErr: true, + wantErr: &schema200NoAttributeErr, }, { name: "Schema 2.1.0 has the top-level key attribute", @@ -121,23 +144,25 @@ func TestUpdateAttributes(t *testing.T) { }, key: "key_invalid", value: nestedValue, - wantErr: true, + wantErr: &invalidKeyErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.devfilev2.UpdateAttributes(tt.key, tt.value) - if tt.wantErr == (err == nil) { - t.Errorf("TestUpdateAttributes error - %v, wantErr %v", err, tt.wantErr) + if (tt.wantErr == nil) != (err == nil) { + t.Errorf("TestUpdateAttributes() error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { attributes, err := tt.devfilev2.GetAttributes() if err != nil { - t.Errorf("TestUpdateAttributes error - %+v", err) + t.Errorf("TestUpdateAttributes() error: %+v", err) return } if !reflect.DeepEqual(attributes, tt.wantAttributes) { - t.Errorf("TestUpdateAttributes mismatch error - expected %+v, actual %+v", tt.wantAttributes, attributes) + t.Errorf("TestUpdateAttributes() mismatch error: expected %+v, actual %+v", tt.wantAttributes, attributes) } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestUpdateAttributes(): Error message should match") } }) } @@ -151,13 +176,15 @@ func TestAddAttributes(t *testing.T) { }, } + schema200NoAttributeErr := "top-level attributes is not supported in devfile schema version 2.0.0" + tests := []struct { name string devfilev2 *DevfileV2 key string value interface{} wantAttributes attributes.Attributes - wantErr bool + wantErr *string }{ { name: "Schema 2.0.0 does not have attributes", @@ -168,7 +195,7 @@ func TestAddAttributes(t *testing.T) { }, }, }, - wantErr: true, + wantErr: &schema200NoAttributeErr, }, { name: "Schema 2.1.0 has attributes", @@ -210,17 +237,19 @@ func TestAddAttributes(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.devfilev2.AddAttributes(tt.key, tt.value) - if tt.wantErr == (err == nil) { - t.Errorf("TestAddAttributes error - %v, wantErr %v", err, tt.wantErr) + if (tt.wantErr == nil) != (err == nil) { + t.Errorf("TestAddAttributes() error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { attributes, err := tt.devfilev2.GetAttributes() if err != nil { - t.Errorf("TestAddAttributes error - %+v", err) + t.Errorf("TestAddAttributes() error: %+v", err) return } if !reflect.DeepEqual(attributes, tt.wantAttributes) { - t.Errorf("TestAddAttributes mismatch error - expected %+v, actual %+v", tt.wantAttributes, attributes) + t.Errorf("TestAddAttributes() mismatch error: expected %+v, actual %+v", tt.wantAttributes, attributes) } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestAddAttributes(): Error message should match") } }) } diff --git a/pkg/devfile/parser/data/v2/commands_test.go b/pkg/devfile/parser/data/v2/commands_test.go index d0bf9002..e0012a34 100644 --- a/pkg/devfile/parser/data/v2/commands_test.go +++ b/pkg/devfile/parser/data/v2/commands_test.go @@ -14,12 +14,14 @@ import ( func TestDevfile200_GetCommands(t *testing.T) { + invalidCmdTypeErr := "unknown command type" + tests := []struct { name string currentCommands []v1.Command filterOptions common.DevfileOptions wantCommands []string - wantErr bool + wantErr *string }{ { name: "Get all the commands", @@ -38,7 +40,6 @@ func TestDevfile200_GetCommands(t *testing.T) { }, }, wantCommands: []string{"command1", "command2"}, - wantErr: false, }, { name: "Get the filtered commands", @@ -135,7 +136,6 @@ func TestDevfile200_GetCommands(t *testing.T) { }, }, wantCommands: []string{"command3"}, - wantErr: false, }, { name: "Wrong filter for commands", @@ -166,7 +166,6 @@ func TestDevfile200_GetCommands(t *testing.T) { "firstStringIsWrong": "firstStringValue", }, }, - wantErr: false, }, { name: "Invalid command type", @@ -184,7 +183,7 @@ func TestDevfile200_GetCommands(t *testing.T) { "firstString": "firstStringValue", }, }, - wantErr: true, + wantErr: &invalidCmdTypeErr, }, } for _, tt := range tests { @@ -200,12 +199,12 @@ func TestDevfile200_GetCommands(t *testing.T) { } commands, err := d.GetCommands(tt.filterOptions) - if (err != nil) != tt.wantErr { - t.Errorf("TestDevfile200_GetCommands() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_GetCommands() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { // confirm the length of actual vs expected if len(commands) != len(tt.wantCommands) { - t.Errorf("TestDevfile200_GetCommands() error - length of expected commands is not the same as the length of actual commands") + t.Errorf("TestDevfile200_GetCommands() error: length of expected commands is not the same as the length of actual commands") return } @@ -219,9 +218,11 @@ func TestDevfile200_GetCommands(t *testing.T) { } if !matched { - t.Errorf("TestDevfile200_GetCommands() error - command %s not found in the devfile", wantCommand) + t.Errorf("TestDevfile200_GetCommands() error: command %s not found in the devfile", wantCommand) } } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_GetCommands(): Error message should match") } }) } @@ -316,9 +317,9 @@ func TestDevfile200_AddCommands(t *testing.T) { err := d.AddCommands(tt.newCommands) // Unexpected error if (err != nil) != (tt.wantErr != nil) { - t.Errorf("TestDevfile200_AddCommands() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("TestDevfile200_AddCommands() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if tt.wantErr != nil { - assert.Regexp(t, *tt.wantErr, err.Error(), "Error message should match") + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_AddCommands(): Error message should match") } else { wantCommands := append(tt.currentCommands, tt.newCommands...) if !reflect.DeepEqual(d.Commands, wantCommands) { @@ -331,15 +332,13 @@ func TestDevfile200_AddCommands(t *testing.T) { } func TestDevfile200_UpdateCommands(t *testing.T) { + invalidCmdErr := "update command failed: command .* not found" - type args struct { - name string - } tests := []struct { name string currentCommands []v1.Command newCommand v1.Command - wantErr bool + wantErr *string }{ { name: "successfully update the command", @@ -367,7 +366,6 @@ func TestDevfile200_UpdateCommands(t *testing.T) { }, }, }, - wantErr: false, }, { name: "fail to update the command if not exist", @@ -389,7 +387,7 @@ func TestDevfile200_UpdateCommands(t *testing.T) { }, }, }, - wantErr: true, + wantErr: &invalidCmdErr, }, } for _, tt := range tests { @@ -406,12 +404,12 @@ func TestDevfile200_UpdateCommands(t *testing.T) { err := d.UpdateCommand(tt.newCommand) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestDevfile200_UpdateCommands() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_UpdateCommands() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { commands, err := d.GetCommands(common.DevfileOptions{}) if err != nil { - t.Errorf("TestDevfile200_UpdateCommands() unxpected error %v", err) + t.Errorf("TestDevfile200_UpdateCommands() unxpected error: %v", err) return } @@ -420,20 +418,23 @@ func TestDevfile200_UpdateCommands(t *testing.T) { if tt.newCommand.Id == devfileCommand.Id { matched = true if !reflect.DeepEqual(devfileCommand, tt.newCommand) { - t.Errorf("TestDevfile200_UpdateCommands() command mismatch - wanted %+v, got %+v", tt.newCommand, devfileCommand) + t.Errorf("TestDevfile200_UpdateCommands() error: command mismatch, wanted %+v, got %+v", tt.newCommand, devfileCommand) } } } if !matched { - t.Errorf("TestDevfile200_UpdateCommands() command mismatch - did not find command with id %s", tt.newCommand.Id) + t.Errorf("TestDevfile200_UpdateCommands() error: command mismatch, did not find command with id %s", tt.newCommand.Id) } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_UpdateCommands(): Error message should match") } }) } } func TestDeleteCommands(t *testing.T) { + missingCmdErr := "command .* is not found in the devfile" d := &DevfileV2{ v1.Devfile{ @@ -470,7 +471,7 @@ func TestDeleteCommands(t *testing.T) { name string commandToDelete string wantCommands []v1.Command - wantErr bool + wantErr *string }{ { name: "Successfully delete command", @@ -491,21 +492,22 @@ func TestDeleteCommands(t *testing.T) { }, }, }, - wantErr: false, }, { name: "Missing Command", commandToDelete: "command34", - wantErr: true, + wantErr: &missingCmdErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := d.DeleteCommand(tt.commandToDelete) - if (err != nil) != tt.wantErr { - t.Errorf("DeleteCommand() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDeleteCommands() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { - assert.Equal(t, tt.wantCommands, d.Commands, "The two values should be the same.") + assert.Equal(t, tt.wantCommands, d.Commands, "TestDeleteCommands(): The two values should be the same.") + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDeleteCommands(): Error message should match") } }) } diff --git a/pkg/devfile/parser/data/v2/common/command_helper_test.go b/pkg/devfile/parser/data/v2/common/command_helper_test.go index 62688929..4f262e2e 100644 --- a/pkg/devfile/parser/data/v2/common/command_helper_test.go +++ b/pkg/devfile/parser/data/v2/common/command_helper_test.go @@ -1,6 +1,7 @@ package common import ( + "github.com/stretchr/testify/assert" "reflect" "testing" @@ -112,7 +113,7 @@ func TestGetGroup(t *testing.T) { t.Run(tt.name, func(t *testing.T) { commandGroup := GetGroup(tt.command) if !reflect.DeepEqual(commandGroup, tt.want) { - t.Errorf("expected %v, actual %v", tt.want, commandGroup) + t.Errorf("TestGetGroup() error: expected %v, actual %v", tt.want, commandGroup) } }) } @@ -158,7 +159,7 @@ func TestGetExecComponent(t *testing.T) { t.Run(tt.name, func(t *testing.T) { component := GetExecComponent(tt.command) if component != tt.want { - t.Errorf("expected %v, actual %v", tt.want, component) + t.Errorf("TestGetExecComponent() error: expected %v, actual %v", tt.want, component) } }) } @@ -204,7 +205,7 @@ func TestGetExecCommandLine(t *testing.T) { t.Run(tt.name, func(t *testing.T) { commandLine := GetExecCommandLine(tt.command) if commandLine != tt.want { - t.Errorf("expected %v, actual %v", tt.want, commandLine) + t.Errorf("TestGetExecCommandLine() error: expected %v, actual %v", tt.want, commandLine) } }) } @@ -250,7 +251,7 @@ func TestGetExecWorkingDir(t *testing.T) { t.Run(tt.name, func(t *testing.T) { workingDir := GetExecWorkingDir(tt.command) if workingDir != tt.want { - t.Errorf("expected %v, actual %v", tt.want, workingDir) + t.Errorf("TestGetExecWorkingDir() error: expected %v, actual %v", tt.want, workingDir) } }) } @@ -259,10 +260,12 @@ func TestGetExecWorkingDir(t *testing.T) { func TestGetCommandType(t *testing.T) { + cmdTypeErr := "unknown command type" + tests := []struct { name string command v1.Command - wantErr bool + wantErr *string commandType v1.CommandType }{ { @@ -274,7 +277,6 @@ func TestGetCommandType(t *testing.T) { }, }, commandType: v1.ExecCommandType, - wantErr: false, }, { name: "Composite command", @@ -285,7 +287,6 @@ func TestGetCommandType(t *testing.T) { }, }, commandType: v1.CompositeCommandType, - wantErr: false, }, { name: "Apply command", @@ -296,7 +297,6 @@ func TestGetCommandType(t *testing.T) { }, }, commandType: v1.ApplyCommandType, - wantErr: false, }, { name: "Custom command", @@ -307,7 +307,6 @@ func TestGetCommandType(t *testing.T) { }, }, commandType: v1.CustomCommandType, - wantErr: false, }, { name: "Unknown command", @@ -315,17 +314,19 @@ func TestGetCommandType(t *testing.T) { Id: "unknown", CommandUnion: v1.CommandUnion{}, }, - wantErr: true, + wantErr: &cmdTypeErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := GetCommandType(tt.command) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestGetCommandType() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestGetCommandType() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && got != tt.commandType { - t.Errorf("TestGetCommandType error: command type mismatch, expected: %v got: %v", tt.commandType, got) + t.Errorf("TestGetCommandType() error: command type mismatch, expected: %v got: %v", tt.commandType, got) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestGetCommandType(): Error message should match") } }) } @@ -401,7 +402,7 @@ func TestGetCommandsFromEvent(t *testing.T) { t.Run(tt.name, func(t *testing.T) { commands := GetCommandsFromEvent(commandsMap, tt.eventName) if !reflect.DeepEqual(tt.wantCommands, commands) { - t.Errorf("TestGetCommandsFromEvent error - got %v expected %v", commands, tt.wantCommands) + t.Errorf("TestGetCommandsFromEvent() error: got %v expected %v", commands, tt.wantCommands) } }) } diff --git a/pkg/devfile/parser/data/v2/common/component_helper_test.go b/pkg/devfile/parser/data/v2/common/component_helper_test.go index 5266509b..4607c70b 100644 --- a/pkg/devfile/parser/data/v2/common/component_helper_test.go +++ b/pkg/devfile/parser/data/v2/common/component_helper_test.go @@ -1,6 +1,7 @@ package common import ( + "github.com/stretchr/testify/assert" "testing" v1 "github.com/devfile/api/v2/pkg/apis/workspaces/v1alpha2" @@ -89,11 +90,12 @@ func TestIsVolume(t *testing.T) { } func TestGetComponentType(t *testing.T) { + cmpTypeErr := "unknown component type" tests := []struct { name string component v1.Component - wantErr bool + wantErr *string componentType v1.ComponentType }{ { @@ -107,7 +109,6 @@ func TestGetComponentType(t *testing.T) { }, }, componentType: v1.VolumeComponentType, - wantErr: false, }, { name: "Openshift component", @@ -118,7 +119,6 @@ func TestGetComponentType(t *testing.T) { }, }, componentType: v1.OpenshiftComponentType, - wantErr: false, }, { name: "Kubernetes component", @@ -129,7 +129,6 @@ func TestGetComponentType(t *testing.T) { }, }, componentType: v1.KubernetesComponentType, - wantErr: false, }, { name: "Container component", @@ -140,7 +139,6 @@ func TestGetComponentType(t *testing.T) { }, }, componentType: v1.ContainerComponentType, - wantErr: false, }, { name: "Plugin component", @@ -151,7 +149,6 @@ func TestGetComponentType(t *testing.T) { }, }, componentType: v1.PluginComponentType, - wantErr: false, }, { name: "Custom component", @@ -162,7 +159,6 @@ func TestGetComponentType(t *testing.T) { }, }, componentType: v1.CustomComponentType, - wantErr: false, }, { name: "Unknown component", @@ -170,17 +166,19 @@ func TestGetComponentType(t *testing.T) { Name: "name", ComponentUnion: v1.ComponentUnion{}, }, - wantErr: true, + wantErr: &cmpTypeErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := GetComponentType(tt.component) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestGetComponentType() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestGetComponentType() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && got != tt.componentType { t.Errorf("TestGetComponentType error: component type mismatch, expected: %v got: %v", tt.componentType, got) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestGetComponentType(): Error message should match") } }) } diff --git a/pkg/devfile/parser/data/v2/common/options_test.go b/pkg/devfile/parser/data/v2/common/options_test.go index 9a6147fa..0b8451e4 100644 --- a/pkg/devfile/parser/data/v2/common/options_test.go +++ b/pkg/devfile/parser/data/v2/common/options_test.go @@ -13,7 +13,6 @@ func TestFilterDevfileObject(t *testing.T) { attributes attributes.Attributes options DevfileOptions wantFilter bool - wantErr bool }{ { name: "Filter with one key", @@ -27,7 +26,6 @@ func TestFilterDevfileObject(t *testing.T) { }, }, wantFilter: true, - wantErr: false, }, { name: "Filter with two keys", @@ -42,7 +40,6 @@ func TestFilterDevfileObject(t *testing.T) { }, }, wantFilter: true, - wantErr: false, }, { name: "Filter with missing key", @@ -56,7 +53,6 @@ func TestFilterDevfileObject(t *testing.T) { }, }, wantFilter: false, - wantErr: false, }, } @@ -64,10 +60,10 @@ func TestFilterDevfileObject(t *testing.T) { t.Run(tt.name, func(t *testing.T) { filterIn, err := FilterDevfileObject(tt.attributes, tt.options) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestFilterDevfileObject() error = %v, wantErr %v", err, tt.wantErr) - } else if err == nil && filterIn != tt.wantFilter { - t.Errorf("TestFilterDevfileObject error - expected %v got %v", tt.wantFilter, filterIn) + if err != nil { + t.Errorf("TestFilterDevfileObject() unexpected error: %v", err) + } else if filterIn != tt.wantFilter { + t.Errorf("TestFilterDevfileObject() error: expected %v got %v", tt.wantFilter, filterIn) } }) } diff --git a/pkg/devfile/parser/data/v2/common/project_helper_test.go b/pkg/devfile/parser/data/v2/common/project_helper_test.go index 490def51..fe92cd23 100644 --- a/pkg/devfile/parser/data/v2/common/project_helper_test.go +++ b/pkg/devfile/parser/data/v2/common/project_helper_test.go @@ -1,12 +1,15 @@ package common import ( + "github.com/stretchr/testify/assert" "testing" v1 "github.com/devfile/api/v2/pkg/apis/workspaces/v1alpha2" ) func TestGitLikeProjectSource_GetDefaultSource(t *testing.T) { + checkoutFromRemoteUndefinedErr := "checkoutFrom.Remote is not defined in Remotes" + missingCheckoutFromErr := "there are multiple git remotes but no checkoutFrom information" tests := []struct { name string @@ -14,7 +17,7 @@ func TestGitLikeProjectSource_GetDefaultSource(t *testing.T) { want1 string want2 string want3 string - wantErr bool + wantErr *string }{ { name: "only one remote", @@ -23,10 +26,9 @@ func TestGitLikeProjectSource_GetDefaultSource(t *testing.T) { "origin": "url", }, }, - want1: "origin", - want2: "url", - want3: "", - wantErr: false, + want1: "origin", + want2: "url", + want3: "", }, { name: "multiple remotes, checkoutFrom with only branch", @@ -36,10 +38,9 @@ func TestGitLikeProjectSource_GetDefaultSource(t *testing.T) { }, CheckoutFrom: &v1.CheckoutFrom{Revision: "dev"}, }, - want1: "origin", - want2: "urlO", - want3: "dev", - wantErr: false, + want1: "origin", + want2: "urlO", + want3: "dev", }, { name: "multiple remotes, checkoutFrom without revision", @@ -50,10 +51,9 @@ func TestGitLikeProjectSource_GetDefaultSource(t *testing.T) { }, CheckoutFrom: &v1.CheckoutFrom{Remote: "upstream"}, }, - want1: "upstream", - want2: "urlU", - want3: "", - wantErr: false, + want1: "upstream", + want2: "urlU", + want3: "", }, { name: "multiple remotes, checkoutFrom with revision", @@ -64,10 +64,9 @@ func TestGitLikeProjectSource_GetDefaultSource(t *testing.T) { }, CheckoutFrom: &v1.CheckoutFrom{Remote: "upstream", Revision: "v1"}, }, - want1: "upstream", - want2: "urlU", - want3: "v1", - wantErr: false, + want1: "upstream", + want2: "urlU", + want3: "v1", }, { name: "multiple remotes, checkoutFrom with unknown remote", @@ -81,7 +80,7 @@ func TestGitLikeProjectSource_GetDefaultSource(t *testing.T) { want1: "", want2: "", want3: "", - wantErr: true, + wantErr: &checkoutFromRemoteUndefinedErr, }, { name: "multiple remotes, no checkoutFrom", @@ -94,36 +93,39 @@ func TestGitLikeProjectSource_GetDefaultSource(t *testing.T) { want1: "", want2: "", want3: "", - wantErr: true, + wantErr: &missingCheckoutFromErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got1, got2, got3, err := GetDefaultSource(tt.gitLikeProjectSource) - if (err != nil) != tt.wantErr { - t.Errorf("GitLikeProjectSource.GetDefaultSource() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestGitLikeProjectSource_GetDefaultSource() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { if got1 != tt.want1 { - t.Errorf("GitLikeProjectSource.GetDefaultSource() got1 = %v, want %v", got1, tt.want1) + t.Errorf("TestGitLikeProjectSource_GetDefaultSource() error: got1 = %v, want %v", got1, tt.want1) } if got2 != tt.want2 { - t.Errorf("GitLikeProjectSource.GetDefaultSource() got2 = %v, want %v", got2, tt.want2) + t.Errorf("TestGitLikeProjectSource_GetDefaultSource() error: got2 = %v, want %v", got2, tt.want2) } if got3 != tt.want3 { - t.Errorf("GitLikeProjectSource.GetDefaultSource() got2 = %v, want %v", got3, tt.want3) + t.Errorf("TestGitLikeProjectSource_GetDefaultSource() error: got3 = %v, want %v", got3, tt.want3) } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestGitLikeProjectSource_GetDefaultSource(): Error message should match") } }) } } func TestGetProjectSrcType(t *testing.T) { + projectSrcTypeErr := "unknown project source type" tests := []struct { name string projectSrc v1.ProjectSource - wantErr bool + wantErr *string projectSrcType v1.ProjectSourceType }{ { @@ -132,7 +134,6 @@ func TestGetProjectSrcType(t *testing.T) { Git: &v1.GitProjectSource{}, }, projectSrcType: v1.GitProjectSourceType, - wantErr: false, }, { name: "Zip project", @@ -140,7 +141,6 @@ func TestGetProjectSrcType(t *testing.T) { Zip: &v1.ZipProjectSource{}, }, projectSrcType: v1.ZipProjectSourceType, - wantErr: false, }, { name: "Custom project", @@ -148,22 +148,23 @@ func TestGetProjectSrcType(t *testing.T) { Custom: &v1.CustomProjectSource{}, }, projectSrcType: v1.CustomProjectSourceType, - wantErr: false, }, { name: "Unknown project", projectSrc: v1.ProjectSource{}, - wantErr: true, + wantErr: &projectSrcTypeErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := GetProjectSourceType(tt.projectSrc) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestGetProjectSrcType() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestGetProjectSrcType() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && got != tt.projectSrcType { - t.Errorf("TestGetProjectSrcType error: project src type mismatch, expected: %v got: %v", tt.projectSrcType, got) + t.Errorf("TestGetProjectSrcType() error: project src type mismatch, expected: %v got: %v", tt.projectSrcType, got) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestGetProjectSrcType(): Error message should match") } }) } diff --git a/pkg/devfile/parser/data/v2/components_test.go b/pkg/devfile/parser/data/v2/components_test.go index 001f680e..9de43fc1 100644 --- a/pkg/devfile/parser/data/v2/components_test.go +++ b/pkg/devfile/parser/data/v2/components_test.go @@ -102,9 +102,9 @@ func TestDevfile200_AddComponent(t *testing.T) { err := d.AddComponents(tt.newComponents) // Unexpected error if (err != nil) != (tt.wantErr != nil) { - t.Errorf("TestDevfile200_AddComponents() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("TestDevfile200_AddComponents() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if tt.wantErr != nil { - assert.Regexp(t, *tt.wantErr, err.Error(), "Error message should match") + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_AddComponents(): Error message should match") } else { wantComponents := append(tt.currentComponents, tt.newComponents...) if !reflect.DeepEqual(d.Components, wantComponents) { @@ -116,12 +116,13 @@ func TestDevfile200_AddComponent(t *testing.T) { } func TestDevfile200_UpdateComponent(t *testing.T) { + invalidCmpErr := "update component failed: component .* not found" tests := []struct { name string currentComponents []v1.Component newComponent v1.Component - wantErr bool + wantErr *string }{ { name: "successfully update the component", @@ -153,7 +154,6 @@ func TestDevfile200_UpdateComponent(t *testing.T) { }, }, }, - wantErr: false, }, { name: "fail to update the component if not exist", @@ -179,7 +179,7 @@ func TestDevfile200_UpdateComponent(t *testing.T) { }, }, }, - wantErr: true, + wantErr: &invalidCmpErr, }, } for _, tt := range tests { @@ -196,12 +196,12 @@ func TestDevfile200_UpdateComponent(t *testing.T) { err := d.UpdateComponent(tt.newComponent) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestDevfile200_UpdateComponent() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_UpdateComponent() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { components, err := d.GetComponents(common.DevfileOptions{}) if err != nil { - t.Errorf("TestDevfile200_UpdateComponent() unxpected error %v", err) + t.Errorf("TestDevfile200_UpdateComponent() unexpected error: %v", err) return } @@ -216,19 +216,22 @@ func TestDevfile200_UpdateComponent(t *testing.T) { if !matched { t.Error("TestDevfile200_UpdateComponent() error updating the component") } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_UpdateComponent(): Error message should match") } }) } } func TestGetDevfileComponents(t *testing.T) { + invalidCmpType := "unknown component type" tests := []struct { name string component []v1.Component wantComponents []string filterOptions common.DevfileOptions - wantErr bool + wantErr *string }{ { name: "Invalid devfile", @@ -349,7 +352,6 @@ func TestGetDevfileComponents(t *testing.T) { ComponentType: v1.ContainerComponentType, }, }, - wantErr: false, }, { name: "Invalid component type", @@ -367,7 +369,7 @@ func TestGetDevfileComponents(t *testing.T) { "firstString": "firstStringValue", }, }, - wantErr: true, + wantErr: &invalidCmpType, }, } for _, tt := range tests { @@ -383,12 +385,12 @@ func TestGetDevfileComponents(t *testing.T) { } components, err := d.GetComponents(tt.filterOptions) - if (err != nil) != tt.wantErr { - t.Errorf("TestGetDevfileComponents() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestGetDevfileComponents() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { // confirm the length of actual vs expected if len(components) != len(tt.wantComponents) { - t.Errorf("TestGetDevfileComponents() error - length of expected components is not the same as the length of actual components") + t.Errorf("TestGetDevfileComponents() error: length of expected components is not the same as the length of actual components") return } @@ -402,9 +404,11 @@ func TestGetDevfileComponents(t *testing.T) { } if !matched { - t.Errorf("TestGetDevfileComponents() error - component %s not found in the devfile", wantComponent) + t.Errorf("TestGetDevfileComponents() error: component %s not found in the devfile", wantComponent) } } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestGetDevfileComponents(): Error message should match") } }) } @@ -418,7 +422,6 @@ func TestGetDevfileContainerComponents(t *testing.T) { component []v1.Component expectedMatchesCount int filterOptions common.DevfileOptions - wantErr bool }{ { name: "Invalid devfile", @@ -507,7 +510,6 @@ func TestGetDevfileContainerComponents(t *testing.T) { }, }, expectedMatchesCount: 0, - wantErr: false, }, } for _, tt := range tests { @@ -523,9 +525,9 @@ func TestGetDevfileContainerComponents(t *testing.T) { } devfileComponents, err := d.GetDevfileContainerComponents(tt.filterOptions) - if (err != nil) != tt.wantErr { - t.Errorf("TestGetDevfileContainerComponents() error = %v, wantErr %v", err, tt.wantErr) - } else if err == nil && len(devfileComponents) != tt.expectedMatchesCount { + if err != nil { + t.Errorf("TestGetDevfileContainerComponents() unexpected error: %v", err) + } else if len(devfileComponents) != tt.expectedMatchesCount { t.Errorf("TestGetDevfileContainerComponents error: wrong number of components matched: expected %v, actual %v", tt.expectedMatchesCount, len(devfileComponents)) } }) @@ -540,7 +542,6 @@ func TestGetDevfileVolumeComponents(t *testing.T) { component []v1.Component expectedMatchesCount int filterOptions common.DevfileOptions - wantErr bool }{ { name: "Invalid devfile", @@ -617,7 +618,6 @@ func TestGetDevfileVolumeComponents(t *testing.T) { }, }, expectedMatchesCount: 0, - wantErr: false, }, } for _, tt := range tests { @@ -632,10 +632,10 @@ func TestGetDevfileVolumeComponents(t *testing.T) { }, } devfileComponents, err := d.GetDevfileVolumeComponents(tt.filterOptions) - if (err != nil) != tt.wantErr { - t.Errorf("TestGetDevfileVolumeComponents() error = %v, wantErr %v", err, tt.wantErr) - } else if err == nil && len(devfileComponents) != tt.expectedMatchesCount { - t.Errorf("TestGetDevfileVolumeComponents error: wrong number of components matched: expected %v, actual %v", tt.expectedMatchesCount, len(devfileComponents)) + if err != nil { + t.Errorf("TestGetDevfileVolumeComponents() unexpected error: %v", err) + } else if len(devfileComponents) != tt.expectedMatchesCount { + t.Errorf("TestGetDevfileVolumeComponents() error: wrong number of components matched: expected %v, actual %v", tt.expectedMatchesCount, len(devfileComponents)) } }) } @@ -644,6 +644,8 @@ func TestGetDevfileVolumeComponents(t *testing.T) { func TestDeleteComponents(t *testing.T) { + missingCmpErr := "component .* is not found in the devfile" + d := &DevfileV2{ v1.Devfile{ DevWorkspaceTemplateSpec: v1.DevWorkspaceTemplateSpec{ @@ -685,7 +687,7 @@ func TestDeleteComponents(t *testing.T) { name string componentToDelete string wantComponents []v1.Component - wantErr bool + wantErr *string }{ { name: "Successfully delete a Component", @@ -712,21 +714,22 @@ func TestDeleteComponents(t *testing.T) { }, }, }, - wantErr: false, }, { name: "Missing Component", componentToDelete: "comp12", - wantErr: true, + wantErr: &missingCmpErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := d.DeleteComponent(tt.componentToDelete) - if (err != nil) != tt.wantErr { - t.Errorf("DeleteComponent() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDeleteComponents() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { - assert.Equal(t, tt.wantComponents, d.Components, "The two values should be the same.") + assert.Equal(t, tt.wantComponents, d.Components, "TestDeleteComponents(): The two values should be the same.") + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDeleteComponents(): Error message should match") } }) } diff --git a/pkg/devfile/parser/data/v2/events_test.go b/pkg/devfile/parser/data/v2/events_test.go index 58b0ed3f..d60b940a 100644 --- a/pkg/devfile/parser/data/v2/events_test.go +++ b/pkg/devfile/parser/data/v2/events_test.go @@ -38,11 +38,9 @@ func TestDevfile200_AddEvents(t *testing.T) { PostStart: []string{"postStart1"}, }, }, - wantErr: nil, }, { - name: "successfully add the events to empty devfile event", - currentEvents: nil, + name: "successfully add the events to empty devfile event", newEvents: v1.Events{ DevWorkspaceEvents: v1.DevWorkspaceEvents{ PostStart: []string{"postStart1"}, @@ -53,7 +51,6 @@ func TestDevfile200_AddEvents(t *testing.T) { PostStart: []string{"postStart1"}, }, }, - wantErr: nil, }, { name: "event already present", @@ -88,9 +85,9 @@ func TestDevfile200_AddEvents(t *testing.T) { err := d.AddEvents(tt.newEvents) if (err != nil) != (tt.wantErr != nil) { - t.Errorf("TestDevfile200_AddEvents() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("TestDevfile200_AddEvents() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if tt.wantErr != nil { - assert.Regexp(t, *tt.wantErr, err.Error(), "Error message should match") + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_AddEvents(): Error message should match") } else { if !reflect.DeepEqual(*d.Events, tt.wantEvents) { t.Errorf("TestDevfile200_AddEvents() wanted: %v, got: %v, difference at %v", tt.wantEvents, *d.Events, pretty.Compare(tt.wantEvents, *d.Events)) @@ -162,7 +159,7 @@ func TestDevfile200_UpdateEvents(t *testing.T) { events := d.GetEvents() if !reflect.DeepEqual(events, tt.newEvents) { - t.Errorf("TestDevfile200_UpdateEvents events did not get updated. got - %+v, wanted - %+v", events, tt.newEvents) + t.Errorf("TestDevfile200_UpdateEvents() error: events did not get updated. got - %+v, wanted - %+v", events, tt.newEvents) } }) diff --git a/pkg/devfile/parser/data/v2/header_test.go b/pkg/devfile/parser/data/v2/header_test.go index a116f344..19fc6ecb 100644 --- a/pkg/devfile/parser/data/v2/header_test.go +++ b/pkg/devfile/parser/data/v2/header_test.go @@ -21,18 +21,18 @@ func TestDevfile200_GetSchemaVersion(t *testing.T) { devfilev2: &DevfileV2{ v1.Devfile{ DevfileHeader: devfilepkg.DevfileHeader{ - SchemaVersion: "1.0.0", + SchemaVersion: "2.0.0", }, }, }, - expectedSchemaVersion: "1.0.0", + expectedSchemaVersion: "2.0.0", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { version := tt.devfilev2.GetSchemaVersion() if version != tt.expectedSchemaVersion { - t.Errorf("TestDevfile200_GetSchemaVersion error - schema version did not match. Expected %s, got %s", tt.expectedSchemaVersion, version) + t.Errorf("TestDevfile200_GetSchemaVersion() error: schema version did not match. Expected %s, got %s", tt.expectedSchemaVersion, version) } }) } @@ -85,7 +85,7 @@ func TestDevfile200_SetSchemaVersion(t *testing.T) { t.Run(tt.name, func(t *testing.T) { tt.devfilev2.SetSchemaVersion(tt.schemaVersion) if !reflect.DeepEqual(tt.devfilev2, tt.expectedDevfilev2) { - t.Errorf("TestDevfile200_SetSchemaVersion() expected %v, got %v", tt.expectedDevfilev2, tt.devfilev2) + t.Errorf("TestDevfile200_SetSchemaVersion() error: expected %v, got %v", tt.expectedDevfilev2, tt.devfilev2) } }) } @@ -125,13 +125,13 @@ func TestDevfile200_GetMetadata(t *testing.T) { t.Run(tt.name, func(t *testing.T) { metadata := tt.devfilev2.GetMetadata() if metadata.Name != tt.expectedName { - t.Errorf("TestDevfile200_GetMetadata() expected %v, got %v", tt.expectedName, metadata.Name) + t.Errorf("TestDevfile200_GetMetadata() error: name mismatch, expected %v, got %v", tt.expectedName, metadata.Name) } if metadata.Version != tt.expectedVersion { - t.Errorf("TestDevfile200_GetMetadata() expected %v, got %v", tt.expectedVersion, metadata.Version) + t.Errorf("TestDevfile200_GetMetadata() error: version mismatch, expected %v, got %v", tt.expectedVersion, metadata.Version) } if metadata.Attributes.GetString("alpha.build-dockerfile", nil) != tt.expectedDockerfilePath { - t.Errorf("TestDevfile200_GetMetadata() expected %v, got %v", tt.expectedDockerfilePath, metadata.Attributes.GetString("alpha.build-dockerfile", nil)) + t.Errorf("TestDevfile200_GetMetadata() error: dockor file path mismatch, expected %v, got %v", tt.expectedDockerfilePath, metadata.Attributes.GetString("alpha.build-dockerfile", nil)) } }) } @@ -219,7 +219,7 @@ func TestDevfile200_SetSetMetadata(t *testing.T) { t.Run(tt.name, func(t *testing.T) { tt.devfilev2.SetMetadata(tt.metadata) if !reflect.DeepEqual(tt.devfilev2, tt.expectedDevfilev2) { - t.Errorf("TestDevfile200_SetSchemaVersion() expected %v, got %v", tt.expectedDevfilev2, tt.devfilev2) + t.Errorf("TestDevfile200_SetSchemaVersion() error: expected %v, got %v", tt.expectedDevfilev2, tt.devfilev2) } }) } diff --git a/pkg/devfile/parser/data/v2/parent_test.go b/pkg/devfile/parser/data/v2/parent_test.go index 9592f18c..171cb9e3 100644 --- a/pkg/devfile/parser/data/v2/parent_test.go +++ b/pkg/devfile/parser/data/v2/parent_test.go @@ -9,9 +9,6 @@ import ( func TestDevfile200_SetParent(t *testing.T) { - type args struct { - name string - } tests := []struct { name string parent *v1.Parent @@ -47,7 +44,7 @@ func TestDevfile200_SetParent(t *testing.T) { t.Run(tt.name, func(t *testing.T) { tt.devfilev2.SetParent(tt.parent) if !reflect.DeepEqual(tt.devfilev2, tt.expectedDevfilev2) { - t.Errorf("TestDevfile200_SetParent() expected %v, got %v", tt.expectedDevfilev2, tt.devfilev2) + t.Errorf("TestDevfile200_SetParent() error: expected %v, got %v", tt.expectedDevfilev2, tt.devfilev2) } }) } diff --git a/pkg/devfile/parser/data/v2/projects_test.go b/pkg/devfile/parser/data/v2/projects_test.go index 2f85c95a..c45f4a2f 100644 --- a/pkg/devfile/parser/data/v2/projects_test.go +++ b/pkg/devfile/parser/data/v2/projects_test.go @@ -13,13 +13,14 @@ import ( ) func TestDevfile200_GetProjects(t *testing.T) { + invalidProjectSrcType := "unknown project source type" tests := []struct { name string currentProjects []v1.Project filterOptions common.DevfileOptions wantProjects []string - wantErr bool + wantErr *string }{ { name: "Get all the projects", @@ -39,7 +40,6 @@ func TestDevfile200_GetProjects(t *testing.T) { }, filterOptions: common.DevfileOptions{}, wantProjects: []string{"project1", "project2"}, - wantErr: false, }, { name: "Get the filtered projects", @@ -76,7 +76,6 @@ func TestDevfile200_GetProjects(t *testing.T) { }, }, wantProjects: []string{"project1"}, - wantErr: false, }, { name: "Wrong filter for projects", @@ -109,7 +108,6 @@ func TestDevfile200_GetProjects(t *testing.T) { "firstStringIsWrong": "firstStringValue", }, }, - wantErr: false, }, { name: "Invalid project src type", @@ -127,7 +125,7 @@ func TestDevfile200_GetProjects(t *testing.T) { "firstString": "firstStringValue", }, }, - wantErr: true, + wantErr: &invalidProjectSrcType, }, } for _, tt := range tests { @@ -143,12 +141,12 @@ func TestDevfile200_GetProjects(t *testing.T) { } projects, err := d.GetProjects(tt.filterOptions) - if (err != nil) != tt.wantErr { - t.Errorf("TestDevfile200_GetProjects() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_GetProjects() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { // confirm the length of actual vs expected if len(projects) != len(tt.wantProjects) { - t.Errorf("TestDevfile200_GetProjects() error - length of expected projects is not the same as the length of actual projects") + t.Errorf("TestDevfile200_GetProjects() error: length of expected projects is not the same as the length of actual projects") return } @@ -162,9 +160,11 @@ func TestDevfile200_GetProjects(t *testing.T) { } if !matched { - t.Errorf("TestDevfile200_GetProjects() error - project %s not found in the devfile", wantProject) + t.Errorf("TestDevfile200_GetProjects() error: project %s not found in the devfile", wantProject) } } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_GetProjects(): Error message should match") } }) } @@ -230,14 +230,14 @@ func TestDevfile200_AddProjects(t *testing.T) { t.Run(tt.name, func(t *testing.T) { err := d.AddProjects(tt.args) if (err != nil) != (tt.wantErr != nil) { - t.Errorf("TestDevfile200_AddProjects() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("TestDevfile200_AddProjects() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if tt.wantErr != nil { - assert.Regexp(t, *tt.wantErr, err.Error(), "Error message should match") + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_AddProjects(): Error message should match") } else if err == nil { wantProjects := append(currentProject, tt.args...) if !reflect.DeepEqual(d.Projects, wantProjects) { - t.Errorf("wanted: %v, got: %v, difference at %v", wantProjects, d.Projects, pretty.Compare(wantProjects, d.Projects)) + t.Errorf("TestDevfile200_AddProjects() error: wanted: %v, got: %v, difference at %v", wantProjects, d.Projects, pretty.Compare(wantProjects, d.Projects)) } } }) @@ -246,12 +246,15 @@ func TestDevfile200_AddProjects(t *testing.T) { } func TestDevfile200_UpdateProject(t *testing.T) { + + missingProjectErr := "update project failed: project .* not found" + tests := []struct { name string args v1.Project devfilev2 *DevfileV2 expectedDevfilev2 *DevfileV2 - wantErr bool + wantErr *string }{ { name: "It should update project for existing project", @@ -295,7 +298,6 @@ func TestDevfile200_UpdateProject(t *testing.T) { }, }, }, - wantErr: false, }, { name: "It should fail to update project for non existing project", @@ -321,7 +323,7 @@ func TestDevfile200_UpdateProject(t *testing.T) { }, }, }, - wantErr: true, + wantErr: &missingProjectErr, }, } @@ -329,16 +331,19 @@ func TestDevfile200_UpdateProject(t *testing.T) { t.Run(tt.name, func(t *testing.T) { err := tt.devfilev2.UpdateProject(tt.args) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestDevfile200_UpdateProject() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_UpdateProject() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && !reflect.DeepEqual(tt.devfilev2, tt.expectedDevfilev2) { - t.Errorf("TestDevfile200_UpdateProject() - wanted: %v, got: %v, difference at %v", tt.expectedDevfilev2, tt.devfilev2, pretty.Compare(tt.expectedDevfilev2, tt.devfilev2)) + t.Errorf("TestDevfile200_UpdateProject() error: wanted: %v, got: %v, difference at %v", tt.expectedDevfilev2, tt.devfilev2, pretty.Compare(tt.expectedDevfilev2, tt.devfilev2)) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_UpdateProject(): Error message should match") } }) } } func TestDevfile200_DeleteProject(t *testing.T) { + missingProjectErr := "project .* is not found in the devfile" d := &DevfileV2{ v1.Devfile{ @@ -363,7 +368,7 @@ func TestDevfile200_DeleteProject(t *testing.T) { name string projectToDelete string wantProjects []v1.Project - wantErr bool + wantErr *string }{ { name: "Project successfully deleted", @@ -374,21 +379,22 @@ func TestDevfile200_DeleteProject(t *testing.T) { ClonePath: "/project2", }, }, - wantErr: false, }, { name: "Project not found", projectToDelete: "nodejs1", - wantErr: true, + wantErr: &missingProjectErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := d.DeleteProject(tt.projectToDelete) - if (err != nil) != tt.wantErr { - t.Errorf("DeleteProject() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_DeleteProject() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { - assert.Equal(t, tt.wantProjects, d.Projects, "The two values should be the same.") + assert.Equal(t, tt.wantProjects, d.Projects, "TestDevfile200_DeleteProject(): The two values should be the same.") + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_DeleteProject(): Error message should match") } }) } @@ -397,12 +403,14 @@ func TestDevfile200_DeleteProject(t *testing.T) { func TestDevfile200_GetStarterProjects(t *testing.T) { + invalidStarterProjectSrcTypeErr := "unknown project source type" + tests := []struct { name string currentStarterProjects []v1.StarterProject filterOptions common.DevfileOptions wantStarterProjects []string - wantErr bool + wantErr *string }{ { name: "Get all the starter projects", @@ -422,7 +430,6 @@ func TestDevfile200_GetStarterProjects(t *testing.T) { }, filterOptions: common.DevfileOptions{}, wantStarterProjects: []string{"project1", "project2"}, - wantErr: false, }, { name: "Get the filtered starter projects", @@ -460,7 +467,6 @@ func TestDevfile200_GetStarterProjects(t *testing.T) { }, }, wantStarterProjects: []string{"project1", "project3"}, - wantErr: false, }, { name: "Wrong filter for starter projects", @@ -491,7 +497,6 @@ func TestDevfile200_GetStarterProjects(t *testing.T) { "firstStringIsWrong": "firstStringValue", }, }, - wantErr: false, }, { name: "Invalid starter project src type", @@ -509,7 +514,7 @@ func TestDevfile200_GetStarterProjects(t *testing.T) { "firstString": "firstStringValue", }, }, - wantErr: true, + wantErr: &invalidStarterProjectSrcTypeErr, }, } for _, tt := range tests { @@ -525,12 +530,12 @@ func TestDevfile200_GetStarterProjects(t *testing.T) { } starterProjects, err := d.GetStarterProjects(tt.filterOptions) - if (err != nil) != tt.wantErr { - t.Errorf("TestDevfile200_GetStarterProjects() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_GetStarterProjects() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { // confirm the length of actual vs expected if len(starterProjects) != len(tt.wantStarterProjects) { - t.Errorf("TestDevfile200_GetStarterProjects() error - length of expected starter projects is not the same as the length of actual starter projects") + t.Errorf("TestDevfile200_GetStarterProjects() error: length of expected starter projects is not the same as the length of actual starter projects") return } @@ -545,9 +550,11 @@ func TestDevfile200_GetStarterProjects(t *testing.T) { } if !matched { - t.Errorf("TestDevfile200_GetStarterProjects() error - starter project %s not found in the devfile", wantProject) + t.Errorf("TestDevfile200_GetStarterProjects() error: starter project %s not found in the devfile", wantProject) } } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_GetStarterProjects(): Error message should match") } }) } @@ -593,7 +600,6 @@ func TestDevfile200_AddStarterProjects(t *testing.T) { Description: "starter project for springboot", }, }, - wantErr: nil, }, { @@ -616,14 +622,14 @@ func TestDevfile200_AddStarterProjects(t *testing.T) { t.Run(tt.name, func(t *testing.T) { err := d.AddStarterProjects(tt.args) if (err != nil) != (tt.wantErr != nil) { - t.Errorf("TestDevfile200_AddStarterProjects() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("TestDevfile200_AddStarterProjects() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if tt.wantErr != nil { - assert.Regexp(t, *tt.wantErr, err.Error(), "Error message should match") + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_AddStarterProjects(): Error message should match") } else if err == nil { wantProjects := append(currentProject, tt.args...) if !reflect.DeepEqual(d.StarterProjects, wantProjects) { - t.Errorf("wanted: %v, got: %v, difference at %v", wantProjects, d.StarterProjects, pretty.Compare(wantProjects, d.StarterProjects)) + t.Errorf("TestDevfile200_AddStarterProjects() error: wanted: %v, got: %v, difference at %v", wantProjects, d.StarterProjects, pretty.Compare(wantProjects, d.StarterProjects)) } } }) @@ -632,12 +638,15 @@ func TestDevfile200_AddStarterProjects(t *testing.T) { } func TestDevfile200_UpdateStarterProject(t *testing.T) { + + missingStarterProjectErr := "update starter project failed: starter project .* not found" + tests := []struct { name string args v1.StarterProject devfilev2 *DevfileV2 expectedDevfilev2 *DevfileV2 - wantErr bool + wantErr *string }{ { name: "It should update project for existing project", @@ -681,7 +690,6 @@ func TestDevfile200_UpdateStarterProject(t *testing.T) { }, }, }, - wantErr: false, }, { name: "It should fail to update project for non existing project", @@ -707,7 +715,7 @@ func TestDevfile200_UpdateStarterProject(t *testing.T) { }, }, }, - wantErr: true, + wantErr: &missingStarterProjectErr, }, } @@ -715,10 +723,12 @@ func TestDevfile200_UpdateStarterProject(t *testing.T) { t.Run(tt.name, func(t *testing.T) { err := tt.devfilev2.UpdateStarterProject(tt.args) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("TestDevfile200_UpdateStarterProject() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_UpdateStarterProject() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && !reflect.DeepEqual(tt.devfilev2, tt.expectedDevfilev2) { - t.Errorf("TestDevfile200_UpdateStarterProject() - wanted: %v, got: %v, difference at %v", tt.expectedDevfilev2, tt.devfilev2, pretty.Compare(tt.expectedDevfilev2, tt.devfilev2)) + t.Errorf("TestDevfile200_UpdateStarterProject() error: wanted: %v, got: %v, difference at %v", tt.expectedDevfilev2, tt.devfilev2, pretty.Compare(tt.expectedDevfilev2, tt.devfilev2)) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_UpdateStarterProject(): Error message should match") } }) } @@ -745,11 +755,13 @@ func TestDevfile200_DeleteStarterProject(t *testing.T) { }, } + missingStarterProjectErr := "starter project .* is not found in the devfile" + tests := []struct { name string starterProjectToDelete string wantStarterProjects []v1.StarterProject - wantErr bool + wantErr *string }{ { name: "Starter Project successfully deleted", @@ -760,21 +772,22 @@ func TestDevfile200_DeleteStarterProject(t *testing.T) { SubDir: "/project2", }, }, - wantErr: false, }, { name: "Starter Project not found", starterProjectToDelete: "nodejs1", - wantErr: true, + wantErr: &missingStarterProjectErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := d.DeleteStarterProject(tt.starterProjectToDelete) - if (err != nil) != tt.wantErr { - t.Errorf("DeleteStarterProject() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_DeleteStarterProject() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { - assert.Equal(t, tt.wantStarterProjects, d.StarterProjects, "The two values should be the same.") + assert.Equal(t, tt.wantStarterProjects, d.StarterProjects, "TestDevfile200_DeleteStarterProject(): The two values should be the same.") + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_DeleteStarterProject(): Error message should match") } }) } diff --git a/pkg/devfile/parser/data/v2/volumes_test.go b/pkg/devfile/parser/data/v2/volumes_test.go index 0e3c4588..9f0e84c5 100644 --- a/pkg/devfile/parser/data/v2/volumes_test.go +++ b/pkg/devfile/parser/data/v2/volumes_test.go @@ -17,6 +17,9 @@ func TestDevfile200_AddVolumeMount(t *testing.T) { volume0 := "volume0" volume1 := "volume1" + samePathPresentErr := "unable to mount volume .*, as another volume .* is mounted to the same path .* in the container .*" + missingContainerErr := "container component .* is not found in the devfile" + type args struct { componentName string volumeMounts []v1.VolumeMount @@ -26,7 +29,7 @@ func TestDevfile200_AddVolumeMount(t *testing.T) { currentComponents []v1.Component wantComponents []v1.Component args args - wantErr bool + wantErr *string }{ { name: "add the volume mount when other mounts are present", @@ -119,7 +122,7 @@ func TestDevfile200_AddVolumeMount(t *testing.T) { }, componentName: container0, }, - wantErr: true, + wantErr: &samePathPresentErr, }, { name: "error out when the specified container is not found", @@ -144,7 +147,7 @@ func TestDevfile200_AddVolumeMount(t *testing.T) { }, componentName: container1, }, - wantErr: true, + wantErr: &missingContainerErr, }, } for _, tt := range tests { @@ -160,10 +163,12 @@ func TestDevfile200_AddVolumeMount(t *testing.T) { } err := d.AddVolumeMounts(tt.args.componentName, tt.args.volumeMounts) - if (err != nil) != tt.wantErr { - t.Errorf("AddVolumeMounts() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_AddVolumeMount() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { - assert.Equal(t, tt.wantComponents, d.Components, "The two values should be the same.") + assert.Equal(t, tt.wantComponents, d.Components, "TestDevfile200_AddVolumeMount(): The two values should be the same.") + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_AddVolumeMount(): Error message should match") } }) } @@ -209,11 +214,13 @@ func TestDevfile200_DeleteVolumeMounts(t *testing.T) { }, } + missingMountErr := "volume mount .* is not found in the devfile" + tests := []struct { name string volMountToDelete string wantComponents []v1.Component - wantErr bool + wantErr *string }{ { name: "Volume Component with mounts", @@ -242,21 +249,22 @@ func TestDevfile200_DeleteVolumeMounts(t *testing.T) { }, }, }, - wantErr: false, }, { name: "Missing mount name", volMountToDelete: "comp1", - wantErr: true, + wantErr: &missingMountErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := d.DeleteVolumeMount(tt.volMountToDelete) - if (err != nil) != tt.wantErr { - t.Errorf("DeleteVolumeMount() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_DeleteVolumeMounts() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { - assert.Equal(t, tt.wantComponents, d.Components, "The two values should be the same.") + assert.Equal(t, tt.wantComponents, d.Components, "TestDevfile200_DeleteVolumeMounts(): The two values should be the same.") + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_DeleteVolumeMounts(): Error message should match") } }) } @@ -265,13 +273,16 @@ func TestDevfile200_DeleteVolumeMounts(t *testing.T) { func TestDevfile200_GetVolumeMountPaths(t *testing.T) { + volumeNotMountedErr := "volume .* not mounted to component .*" + missingContainerErr := "container component .* is not found in the devfile" + tests := []struct { name string currentComponents []v1.Component mountName string componentName string wantPaths []string - wantErr bool + wantErr *string }{ { name: "vol is mounted on the specified container component", @@ -293,7 +304,6 @@ func TestDevfile200_GetVolumeMountPaths(t *testing.T) { wantPaths: []string{"/path", "/path2"}, mountName: "volume1", componentName: "component1", - wantErr: false, }, { name: "vol is not mounted on the specified container component", @@ -313,7 +323,7 @@ func TestDevfile200_GetVolumeMountPaths(t *testing.T) { }, mountName: "volume2", componentName: "component1", - wantErr: true, + wantErr: &volumeNotMountedErr, }, { name: "invalid specified container", @@ -333,7 +343,7 @@ func TestDevfile200_GetVolumeMountPaths(t *testing.T) { }, mountName: "volume1", componentName: "component2", - wantErr: true, + wantErr: &missingContainerErr, }, } for _, tt := range tests { @@ -348,11 +358,11 @@ func TestDevfile200_GetVolumeMountPaths(t *testing.T) { }, } gotPaths, err := d.GetVolumeMountPaths(tt.mountName, tt.componentName) - if (err != nil) != tt.wantErr { - t.Errorf("GetVolumeMountPath() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("TestDevfile200_GetVolumeMountPaths() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil { if len(gotPaths) != len(tt.wantPaths) { - t.Error("expected mount paths length not the same as actual mount paths length") + t.Errorf("TestDevfile200_GetVolumeMountPaths() error: mount paths length mismatch, expected %v, actual %v", len(tt.wantPaths), len(gotPaths)) } for _, wantPath := range tt.wantPaths { @@ -364,9 +374,11 @@ func TestDevfile200_GetVolumeMountPaths(t *testing.T) { } if !matched { - t.Errorf("unable to find the wanted mount path %s in the actual mount paths slice", wantPath) + t.Errorf("TestDevfile200_GetVolumeMountPaths() error: unable to find the wanted mount path %s in the actual mount paths slice", wantPath) } } + } else { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestDevfile200_DeleteVolumeMounts(): Error message should match") } }) } diff --git a/pkg/devfile/parser/data/v2/workspace_test.go b/pkg/devfile/parser/data/v2/workspace_test.go index 96957149..52f88d00 100644 --- a/pkg/devfile/parser/data/v2/workspace_test.go +++ b/pkg/devfile/parser/data/v2/workspace_test.go @@ -51,7 +51,7 @@ func TestDevfile200_SetDevfileWorkspaceSpecContent(t *testing.T) { t.Run(tt.name, func(t *testing.T) { devfilev2.SetDevfileWorkspaceSpecContent(tt.workspaceSpecContent) if !reflect.DeepEqual(devfilev2, tt.expectedDevfilev2) { - t.Errorf("TestDevfile200_SetDevfileWorkspaceSpecContent() expected %v, got %v", tt.expectedDevfilev2, devfilev2) + t.Errorf("TestDevfile200_SetDevfileWorkspaceSpecContent() error: expected %v, got %v", tt.expectedDevfilev2, devfilev2) } }) } @@ -100,7 +100,7 @@ func TestDevfile200_SetDevfileWorkspaceSpec(t *testing.T) { t.Run(tt.name, func(t *testing.T) { devfilev2.SetDevfileWorkspaceSpec(tt.workspaceSpec) if !reflect.DeepEqual(devfilev2, tt.expectedDevfilev2) { - t.Errorf("TestDevfile200_SetDevfileWorkspaceSpec() expected %v, got %v", tt.expectedDevfilev2, devfilev2) + t.Errorf("TestDevfile200_SetDevfileWorkspaceSpec() error: expected %v, got %v", tt.expectedDevfilev2, devfilev2) } }) } diff --git a/pkg/devfile/parser/parse_test.go b/pkg/devfile/parser/parse_test.go index 57baa81c..e9680cbe 100644 --- a/pkg/devfile/parser/parse_test.go +++ b/pkg/devfile/parser/parse_test.go @@ -3,6 +3,7 @@ package parser import ( "context" "fmt" + "github.com/stretchr/testify/assert" "io/ioutil" "net" "net/http" @@ -93,6 +94,18 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { }, } + parentCmdAlreadyDefinedErr := "Some Commands are already defined in parent.* If you want to override them, you should do it in the parent scope." + parentCmpAlreadyDefinedErr := "Some Components are already defined in parent.* If you want to override them, you should do it in the parent scope." + parentProjectAlreadyDefinedErr := "Some Projects are already defined in parent.* If you want to override them, you should do it in the parent scope." + pluginCmdAlreadyDefinedErr := "Some Commands are already defined in plugin.* If you want to override them, you should do it in the plugin scope." + pluginCmpAlreadyDefinedErr := "Some Components are already defined in plugin.* If you want to override them, you should do it in the plugin scope." + pluginProjectAlreadyDefinedErr := "Some Projects are already defined in plugin.* If you want to override them, you should do it in the plugin scope." + newCmdErr := "Some Commands do not override any existing element.* They should be defined in the main body, as new elements, not in the overriding section" + newCmpErr := "Some Components do not override any existing element.* They should be defined in the main body, as new elements, not in the overriding section" + newProjectErr := "Some Projects do not override any existing element.* They should be defined in the main body, as new elements, not in the overriding section" + importCycleErr := "devfile has an cycle in references: main devfile -> .*" + overrideInvalidErr := fmt.Sprintf(".*\n.*%s\n.*%s\n.*%s", newCmpErr, newProjectErr, newCmdErr) + type args struct { devFileObj DevfileObj } @@ -103,7 +116,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { pluginDevfile DevfileObj pluginOverride v1.PluginOverrides wantDevFile DevfileObj - wantErr bool + wantErr *string testRecursiveReference bool }{ { @@ -464,7 +477,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &overrideInvalidErr, }, { name: "error out if the same parent command is defined again in the local devfile", @@ -517,7 +530,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &parentCmdAlreadyDefinedErr, }, { name: "error out if the same parent component is defined again in the local devfile", @@ -574,7 +587,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &parentCmpAlreadyDefinedErr, }, { name: "should not have error if the same event is defined again in the local devfile", @@ -646,6 +659,15 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { { ClonePath: "/projects", Name: "nodejs-starter-build", + ProjectSource: v1.ProjectSource{ + Git: &v1.GitProjectSource{ + GitLikeProjectSource: v1.GitLikeProjectSource{ + Remotes: map[string]string{ + "origin": "url", + }, + }, + }, + }, }, }, }, @@ -666,6 +688,15 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { { ClonePath: "/projects", Name: "nodejs-starter-build", + ProjectSource: v1.ProjectSource{ + Git: &v1.GitProjectSource{ + GitLikeProjectSource: v1.GitLikeProjectSource{ + Remotes: map[string]string{ + "origin": "url", + }, + }, + }, + }, }, }, }, @@ -676,7 +707,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &parentProjectAlreadyDefinedErr, }, { name: "it should merge the plugin's uri data and add the local devfile's data", @@ -1120,7 +1151,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &newCmdErr, }, { name: "error out if the same plugin command is defined again in the local devfile", @@ -1173,7 +1204,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &pluginCmdAlreadyDefinedErr, }, { name: "error out if the same plugin component is defined again in the local devfile", @@ -1230,7 +1261,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &pluginCmpAlreadyDefinedErr, }, { name: "error out if the plugin project is defined again in the local devfile", @@ -1245,6 +1276,15 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { { ClonePath: "/projects", Name: "nodejs-starter-build", + ProjectSource: v1.ProjectSource{ + Git: &v1.GitProjectSource{ + GitLikeProjectSource: v1.GitLikeProjectSource{ + Remotes: map[string]string{ + "origin": "url", + }, + }, + }, + }, }, }, }, @@ -1265,6 +1305,15 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { { ClonePath: "/projects", Name: "nodejs-starter-build", + ProjectSource: v1.ProjectSource{ + Git: &v1.GitProjectSource{ + GitLikeProjectSource: v1.GitLikeProjectSource{ + Remotes: map[string]string{ + "origin": "url", + }, + }, + }, + }, }, }, }, @@ -1275,7 +1324,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &pluginProjectAlreadyDefinedErr, }, { name: "error out if the same project is defined in the both plugin devfile and parent", @@ -1290,6 +1339,15 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { { ClonePath: "/projects", Name: "nodejs-starter-build", + ProjectSource: v1.ProjectSource{ + Git: &v1.GitProjectSource{ + GitLikeProjectSource: v1.GitLikeProjectSource{ + Remotes: map[string]string{ + "origin": "url", + }, + }, + }, + }, }, }, }, @@ -1310,6 +1368,15 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { { ClonePath: "/projects", Name: "nodejs-starter", + ProjectSource: v1.ProjectSource{ + Git: &v1.GitProjectSource{ + GitLikeProjectSource: v1.GitLikeProjectSource{ + Remotes: map[string]string{ + "origin": "url", + }, + }, + }, + }, }, }, }, @@ -1329,6 +1396,15 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { { ClonePath: "/projects", Name: "nodejs-starter", + ProjectSource: v1.ProjectSource{ + Git: &v1.GitProjectSource{ + GitLikeProjectSource: v1.GitLikeProjectSource{ + Remotes: map[string]string{ + "origin": "url", + }, + }, + }, + }, }, }, }, @@ -1339,7 +1415,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &pluginProjectAlreadyDefinedErr, }, { name: "error out if the same command is defined in both plugin devfile and parent devfile", @@ -1415,7 +1491,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &pluginCmdAlreadyDefinedErr, }, { name: "error out if the same component is defined in both plugin devfile and parent devfile", @@ -1497,7 +1573,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &pluginCmpAlreadyDefinedErr, }, { name: "it should override the requested parent's data and plugin's data, and add the local devfile's data", @@ -1813,7 +1889,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &pluginCmpAlreadyDefinedErr, }, { name: "it should override with no errors if the plugin component is defined with a different component type in the plugin override", @@ -1887,7 +1963,6 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { }, }, }, - wantErr: false, }, { name: "error out if the parent component is defined with a different component type in the local devfile", @@ -1944,7 +2019,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &parentCmpAlreadyDefinedErr, }, { name: "it should override with no errors if the parent component is defined with a different component type in the parent override", @@ -2023,7 +2098,6 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { }, }, }, - wantErr: false, }, { name: "error out if the URI is recursively referenced", @@ -2070,7 +2144,7 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { wantDevFile: DevfileObj{ Data: &v2.DevfileV2{}, }, - wantErr: true, + wantErr: &importCycleErr, testRecursiveReference: true, }, } @@ -2082,17 +2156,17 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { parentTestServer = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { data, err := yaml.Marshal(tt.parentDevfile.Data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPluginFromURI() unexpected error while doing yaml marshal: %v", err) } _, err = w.Write(data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPluginFromURI() unexpected error while writing data: %v", err) } })) // create a listener with the desired port. l1, err := net.Listen("tcp", uri1) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPluginFromURI() unexpected error while creating listener: %v", err) } // NewUnstartedServer creates a listener. Close that listener and replace @@ -2116,16 +2190,16 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { pluginTestServer = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { data, err := yaml.Marshal(tt.pluginDevfile.Data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPluginFromURI() unexpected error while doing yaml marshal: %v", err) } _, err = w.Write(data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPluginFromURI() unexpected error while writing data: %v", err) } })) l, err := net.Listen("tcp", uri2) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPluginFromURI() unexpected error while creating listener: %v", err) } // NewUnstartedServer creates a listener. Close that listener and replace @@ -2157,10 +2231,12 @@ func Test_parseParentAndPluginFromURI(t *testing.T) { err := parseParentAndPlugin(tt.args.devFileObj, &resolutionContextTree{}, resolverTools{}) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("parseParentAndPlugin() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("Test_parseParentAndPluginFromURI() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && !reflect.DeepEqual(tt.args.devFileObj.Data, tt.wantDevFile.Data) { - t.Errorf("wanted: %v, got: %v, difference at %v", tt.wantDevFile.Data, tt.args.devFileObj.Data, pretty.Compare(tt.args.devFileObj.Data, tt.wantDevFile.Data)) + t.Errorf("Test_parseParentAndPluginFromURI() error: wanted: %v, got: %v, difference at %v", tt.wantDevFile.Data, tt.args.devFileObj.Data, pretty.Compare(tt.args.devFileObj.Data, tt.wantDevFile.Data)) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "Test_parseParentAndPluginFromURI(): Error message should match") } }) } @@ -2278,17 +2354,17 @@ func Test_parseParentAndPlugin_RecursivelyReference(t *testing.T) { testServer1 := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { data, err := yaml.Marshal(parentDevfile1.Data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPlugin_RecursivelyReference() unexpected error while doing yaml marshal: %v", err) } _, err = w.Write(data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPlugin_RecursivelyReference() unexpected error while writing data: %v", err) } })) // create a listener with the desired port. l1, err := net.Listen("tcp", uri1) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPlugin_RecursivelyReference() unexpected error while creating listener: %v", err) } // NewUnstartedServer creates a listener. Close that listener and replace @@ -2308,17 +2384,17 @@ func Test_parseParentAndPlugin_RecursivelyReference(t *testing.T) { return } if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPlugin_RecursivelyReference() unexpected error while writing data: %v", err) } _, err = w.Write(data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPlugin_RecursivelyReference() unexpected error while writing data: %v", err) } })) // create a listener with the desired port. l3, err := net.Listen("tcp", uri2) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentAndPlugin_RecursivelyReference() unexpected error while creating listener: %v", err) } // NewUnstartedServer creates a listener. Close that listener and replace @@ -2378,7 +2454,7 @@ func Test_parseParentAndPlugin_RecursivelyReference(t *testing.T) { httpPrefix, uri2, httpPrefix, uri1) // Unexpected error if err == nil || !reflect.DeepEqual(expectedErr, err.Error()) { - t.Errorf("Test_parseParentAndPlugin_RecursivelyReference unexpected error = %v", err) + t.Errorf("Test_parseParentAndPlugin_RecursivelyReference() unexpected error: %v", err) return } @@ -2393,6 +2469,9 @@ func Test_parseParentFromRegistry(t *testing.T) { registryURLs: []string{"http://" + validRegistry}, } + invalidURLErr := "the provided registryURL: .* is not a valid URL" + idNotFoundErr := "failed to get id: .* from registry URLs provided" + parentDevfile := DevfileObj{ Data: &v2.DevfileV2{ Devfile: v1.Devfile{ @@ -2429,18 +2508,18 @@ func Test_parseParentFromRegistry(t *testing.T) { return } if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentFromRegistry() unexpected error while doing yaml marshal: %v", err) return } _, err = w.Write(data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentFromRegistry() unexpected error while writing data: %v", err) } })) // create a listener with the desired port. l, err := net.Listen("tcp", validRegistry) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseParentFromRegistry() unexpected error while creating listener: %v", err) return } @@ -2577,7 +2656,7 @@ func Test_parseParentFromRegistry(t *testing.T) { mainDevfile DevfileObj registryURI string wantDevFile DevfileObj - wantErr bool + wantErr *string testRecursiveReference bool }{ { @@ -2713,7 +2792,7 @@ func Test_parseParentFromRegistry(t *testing.T) { }, }, }, - wantErr: true, + wantErr: &invalidURLErr, }, { name: "it should error out with non-exist registry id provided", @@ -2734,7 +2813,7 @@ func Test_parseParentFromRegistry(t *testing.T) { }, }, }, - wantErr: true, + wantErr: &idNotFoundErr, }, } for _, tt := range tests { @@ -2743,10 +2822,12 @@ func Test_parseParentFromRegistry(t *testing.T) { err := parseParentAndPlugin(tt.mainDevfile, &resolutionContextTree{}, tool) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("parseParentAndPlugin() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("Test_parseParentFromRegistry() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && !reflect.DeepEqual(tt.mainDevfile.Data, tt.wantDevFile.Data) { - t.Errorf("wanted: %v, got: %v, difference at %v", tt.wantDevFile.Data, tt.mainDevfile.Data, pretty.Compare(tt.mainDevfile.Data, tt.wantDevFile.Data)) + t.Errorf("Test_parseParentFromRegistry() error: wanted: %v, got: %v, difference at %v", tt.wantDevFile.Data, tt.mainDevfile.Data, pretty.Compare(tt.mainDevfile.Data, tt.wantDevFile.Data)) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "Test_parseParentFromRegistry(): Error message should match") } }) @@ -2791,13 +2872,15 @@ func Test_parseParentFromKubeCRD(t *testing.T) { }, } + crdNotFoundErr := "not found" + tests := []struct { name string devWorkspaceResources map[string]v1.DevWorkspaceTemplate errors map[string]string mainDevfile DevfileObj wantDevFile DevfileObj - wantErr bool + wantErr *string }{ { name: "should successfully override the parent data", @@ -2904,7 +2987,6 @@ func Test_parseParentFromKubeCRD(t *testing.T) { Spec: parentSpec, }, }, - wantErr: false, }, { name: "should successfully merge the parent data without override defined", @@ -2997,7 +3079,6 @@ func Test_parseParentFromKubeCRD(t *testing.T) { Spec: parentSpec, }, }, - wantErr: false, }, { name: "should fail if kclient get returns error", @@ -3016,9 +3097,9 @@ func Test_parseParentFromKubeCRD(t *testing.T) { }, devWorkspaceResources: map[string]v1.DevWorkspaceTemplate{}, errors: map[string]string{ - name: "not found", + name: crdNotFoundErr, }, - wantErr: true, + wantErr: &crdNotFoundErr, }, } @@ -3035,10 +3116,12 @@ func Test_parseParentFromKubeCRD(t *testing.T) { err := parseParentAndPlugin(tt.mainDevfile, &resolutionContextTree{}, tool) // Unexpected error - if (err != nil) != tt.wantErr { - t.Errorf("parseParentAndPlugin() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != (tt.wantErr != nil) { + t.Errorf("Test_parseParentFromKubeCRD() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && !reflect.DeepEqual(tt.mainDevfile.Data, tt.wantDevFile.Data) { - t.Errorf("wanted: %v, got: %v, difference at %v", tt.wantDevFile.Data, tt.mainDevfile.Data, pretty.Compare(tt.mainDevfile.Data, tt.wantDevFile.Data)) + t.Errorf("Test_parseParentFromKubeCRD() error: wanted: %v, got: %v, difference at %v", tt.wantDevFile.Data, tt.mainDevfile.Data, pretty.Compare(tt.mainDevfile.Data, tt.wantDevFile.Data)) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "Test_parseParentFromKubeCRD(): Error message should match") } }) @@ -3046,11 +3129,13 @@ func Test_parseParentFromKubeCRD(t *testing.T) { } func Test_parseFromURI(t *testing.T) { - const uri1 = "127.0.0.1:8080" - const httpPrefix = "http://" - const localRelativeURI = "testTmp/dir/devfile.yaml" - const notExistURI = "notexist/devfile.yaml" - const invalidURL = "http//invalid.com" + const ( + uri1 = "127.0.0.1:8080" + httpPrefix = "http://" + localRelativeURI = "testTmp/dir/devfile.yaml" + notExistURI = "notexist/devfile.yaml" + invalidURL = "http//invalid.com" + ) uri2 := path.Join(uri1, localRelativeURI) localDevfile := DevfileObj{ @@ -3080,20 +3165,25 @@ func Test_parseFromURI(t *testing.T) { }, } + invalidFilePathErr := "the provided path is not a valid yaml filepath, and devfile.yaml or .devfile.yaml not found in the provided path.*" + readDevfileErr := "failed to read devfile from path.*" + URLNotFoundErr := "error getting devfile info from url: failed to retrieve .*, 404: Not Found" + invalidURLErr := "parse .* invalid URI for request" + // prepare for local file err := os.MkdirAll(path.Dir(localRelativeURI), 0755) if err != nil { - t.Errorf("failed to create folder: %v, error: %v", path.Dir(localRelativeURI), err) + t.Errorf("Test_parseFromURI() error: failed to create folder: %v, error: %v", path.Dir(localRelativeURI), err) return } yamlData, err := yaml.Marshal(localDevfile.Data) if err != nil { - t.Errorf("failed to marshall devfile data: %v", err) + t.Errorf("Test_parseFromURI() error: failed to marshall devfile data: %v", err) return } err = ioutil.WriteFile(localRelativeURI, yamlData, 0644) if err != nil { - t.Errorf("fail to write to file: %v", err) + t.Errorf("Test_parseFromURI() error: fail to write to file: %v", err) return } defer os.RemoveAll("testTmp/") @@ -3171,18 +3261,18 @@ func Test_parseFromURI(t *testing.T) { data, err = yaml.Marshal(parentDevfile.Data) } if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseFromURI() unexpected while doing yaml marshal: %v", err) return } _, err = w.Write(data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseFromURI() unexpected error while writing data: %v", err) } })) // create a listener with the desired port. l, err := net.Listen("tcp", uri1) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseFromURI() unexpected error while creating listener: %v", err) return } @@ -3199,7 +3289,7 @@ func Test_parseFromURI(t *testing.T) { curDevfileCtx devfileCtx.DevfileCtx importReference v1.ImportReference wantDevFile DevfileObj - wantErr bool + wantErr *string }{ { name: "should be able to parse from relative uri on local disk", @@ -3224,7 +3314,7 @@ func Test_parseFromURI(t *testing.T) { { name: "should fail if no path or url has been set for devfile ctx", curDevfileCtx: devfileCtx.DevfileCtx{}, - wantErr: true, + wantErr: &invalidFilePathErr, }, { name: "should fail if file not exist", @@ -3234,7 +3324,7 @@ func Test_parseFromURI(t *testing.T) { Uri: notExistURI, }, }, - wantErr: true, + wantErr: &readDevfileErr, }, { name: "should fail if url not exist", @@ -3244,7 +3334,7 @@ func Test_parseFromURI(t *testing.T) { Uri: notExistURI, }, }, - wantErr: true, + wantErr: &URLNotFoundErr, }, { name: "should fail if with invalid URI format", @@ -3254,7 +3344,7 @@ func Test_parseFromURI(t *testing.T) { Uri: invalidURL, }, }, - wantErr: true, + wantErr: &invalidURLErr, }, } for _, tt := range tests { @@ -3263,15 +3353,17 @@ func Test_parseFromURI(t *testing.T) { if tt.curDevfileCtx.GetURL() == "" { err := tt.curDevfileCtx.SetAbsPath() if err != nil { - t.Errorf("Test_parseFromURI() unexpected error = %v", err) + t.Errorf("Test_parseFromURI() unexpected error: %v", err) return } } got, err := parseFromURI(tt.importReference, tt.curDevfileCtx, &resolutionContextTree{}, resolverTools{}) - if tt.wantErr == (err == nil) { - t.Errorf("Test_parseFromURI() error = %v, wantErr %v", err, tt.wantErr) + if (tt.wantErr == nil) != (err == nil) { + t.Errorf("Test_parseFromURI() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && !reflect.DeepEqual(got.Data, tt.wantDevFile.Data) { - t.Errorf("wanted: %v, got: %v, difference at %v", tt.wantDevFile, got, pretty.Compare(tt.wantDevFile, got)) + t.Errorf("Test_parseFromURI() error: wanted: %v, got: %v, difference at %v", tt.wantDevFile, got, pretty.Compare(tt.wantDevFile, got)) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "Test_parseFromURI(): Error message should match") } }) } @@ -3312,6 +3404,11 @@ func Test_parseFromRegistry(t *testing.T) { }, } + invalidURLErr := "the provided registryURL: .* is not a valid URL" + URLNotFoundErr := "failed to retrieve .*, 404: Not Found" + missingRegistryURLErr := "failed to fetch from registry, registry URL is not provided" + invalidRegistryURLErr := "Get .* dial tcp: lookup http: no such host" + testServer := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var data []byte var err error @@ -3322,18 +3419,18 @@ func Test_parseFromRegistry(t *testing.T) { return } if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseFromRegistry() unexpected error while doing yaml marshal: %v", err) return } _, err = w.Write(data) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseFromRegistry() unexpected error while writing data: %v", err) } })) // create a listener with the desired port. l, err := net.Listen("tcp", registry) if err != nil { - t.Errorf("unexpected error: %v", err) + t.Errorf("Test_parseFromRegistry() unexpected error while creating listener: %v", err) return } @@ -3351,7 +3448,7 @@ func Test_parseFromRegistry(t *testing.T) { importReference v1.ImportReference tool resolverTools wantDevFile DevfileObj - wantErr bool + wantErr *string }{ { name: "should fail if provided registryUrl does not have protocol prefix", @@ -3362,7 +3459,7 @@ func Test_parseFromRegistry(t *testing.T) { }, RegistryUrl: registry, }, - wantErr: true, + wantErr: &invalidURLErr, }, { name: "should be able to parse from provided registryUrl with prefix", @@ -3394,7 +3491,7 @@ func Test_parseFromRegistry(t *testing.T) { }, RegistryUrl: httpPrefix + registry, }, - wantErr: true, + wantErr: &URLNotFoundErr, }, { name: "should fail if registryUrl is not provided, and no registry URLs has been set in tool", @@ -3403,7 +3500,7 @@ func Test_parseFromRegistry(t *testing.T) { Id: registryId, }, }, - wantErr: true, + wantErr: &missingRegistryURLErr, }, { name: "should fail if registryUrl is invalid", @@ -3413,16 +3510,18 @@ func Test_parseFromRegistry(t *testing.T) { }, RegistryUrl: httpPrefix + invalidRegistry, }, - wantErr: true, + wantErr: &invalidRegistryURLErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := parseFromRegistry(tt.importReference, &resolutionContextTree{}, tt.tool) - if tt.wantErr == (err == nil) { - t.Errorf("Test_parseFromRegistry() error = %v, wantErr %v", err, tt.wantErr) + if (tt.wantErr == nil) != (err == nil) { + t.Errorf("Test_parseFromRegistry() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && !reflect.DeepEqual(got.Data, tt.wantDevFile.Data) { - t.Errorf("wanted: %v, got: %v, difference at %v", tt.wantDevFile, got, pretty.Compare(tt.wantDevFile, got)) + t.Errorf("Test_parseFromRegistry() error: wanted: %v, got: %v, difference at %v", tt.wantDevFile, got, pretty.Compare(tt.wantDevFile, got)) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "Test_parseFromRegistry(): Error message should match") } }) } @@ -3458,6 +3557,8 @@ func Test_parseFromKubeCRD(t *testing.T) { }, } + crdNotFoundErr := "not found" + tests := []struct { name string curDevfileCtx devfileCtx.DevfileCtx @@ -3465,7 +3566,7 @@ func Test_parseFromKubeCRD(t *testing.T) { devWorkspaceResources map[string]v1.DevWorkspaceTemplate errors map[string]string wantDevFile DevfileObj - wantErr bool + wantErr *string }{ { name: "should successfully parse the parent with namespace specified in devfile", @@ -3487,7 +3588,6 @@ func Test_parseFromKubeCRD(t *testing.T) { Spec: parentSpec, }, }, - wantErr: false, }, { name: "should fail if kclient get returns error", @@ -3502,9 +3602,9 @@ func Test_parseFromKubeCRD(t *testing.T) { }, devWorkspaceResources: map[string]v1.DevWorkspaceTemplate{}, errors: map[string]string{ - name: "not found", + name: crdNotFoundErr, }, - wantErr: true, + wantErr: &crdNotFoundErr, }, } for _, tt := range tests { @@ -3518,10 +3618,12 @@ func Test_parseFromKubeCRD(t *testing.T) { context: context.Background(), } got, err := parseFromKubeCRD(tt.importReference, &resolutionContextTree{}, tool) - if tt.wantErr == (err == nil) { - t.Errorf("Test_parseFromKubeCRD() error = %v, wantErr %v", err, tt.wantErr) + if (tt.wantErr == nil) != (err == nil) { + t.Errorf("Test_parseFromKubeCRD() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && !reflect.DeepEqual(got.Data, tt.wantDevFile.Data) { - t.Errorf("wanted: %v, got: %v, difference at %v", tt.wantDevFile, got, pretty.Compare(tt.wantDevFile, got)) + t.Errorf("Test_parseFromKubeCRD() error: wanted: %v, got: %v, difference at %v", tt.wantDevFile, got, pretty.Compare(tt.wantDevFile, got)) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "Test_parseFromKubeCRD(): Error message should match") } }) } diff --git a/pkg/devfile/parser/sourceAttribute_test.go b/pkg/devfile/parser/sourceAttribute_test.go index 2f977451..f55ca54d 100644 --- a/pkg/devfile/parser/sourceAttribute_test.go +++ b/pkg/devfile/parser/sourceAttribute_test.go @@ -4,6 +4,7 @@ import ( v1 "github.com/devfile/api/v2/pkg/apis/workspaces/v1alpha2" "github.com/devfile/api/v2/pkg/attributes" "github.com/kylelemons/godebug/pretty" + "github.com/stretchr/testify/assert" "reflect" "testing" ) @@ -18,9 +19,12 @@ func TestAddSourceAttributesForOverrideAndMerge(t *testing.T) { pluginOverrideImportAttribute := attributes.Attributes{}.PutString(pluginOverrideAttribute, "main devfile") parentOverrideImportAttribute := attributes.Attributes{}.PutString(parentOverrideAttribute, "main devfile") + nilTemplateErr := "cannot add source attributes to nil" + invalidTemplateTypeErr := "unknown template type" + tests := []struct { name string - wantErr bool + wantErr *string importReference v1.ImportReference template interface{} wantResult interface{} @@ -28,12 +32,12 @@ func TestAddSourceAttributesForOverrideAndMerge(t *testing.T) { { name: "should fail if template is nil", template: nil, - wantErr: true, + wantErr: &nilTemplateErr, }, { name: "should fail if template is a not support type", template: "invalid template", - wantErr: true, + wantErr: &invalidTemplateTypeErr, }, { name: "template is with type *DevWorkspaceTemplateSpecContent", @@ -67,7 +71,6 @@ func TestAddSourceAttributesForOverrideAndMerge(t *testing.T) { }, }, }, - wantErr: false, }, { name: "template is with type *PluginOverrides", @@ -101,7 +104,6 @@ func TestAddSourceAttributesForOverrideAndMerge(t *testing.T) { }, }, }, - wantErr: false, }, { name: "template is with type *ParentOverrides", @@ -135,7 +137,6 @@ func TestAddSourceAttributesForOverrideAndMerge(t *testing.T) { }, }, }, - wantErr: false, }, } @@ -143,10 +144,12 @@ func TestAddSourceAttributesForOverrideAndMerge(t *testing.T) { t.Run(tt.name, func(t *testing.T) { err := addSourceAttributesForOverrideAndMerge(tt.importReference, tt.template) - if tt.wantErr == (err == nil) { - t.Errorf("Test_AddSourceAttributesForOverrideAndMerge() error = %v, wantErr %v", err, tt.wantErr) + if (tt.wantErr == nil) != (err == nil) { + t.Errorf("Test_AddSourceAttributesForOverrideAndMerge() unexpected error: %v, wantErr %v", err, tt.wantErr) } else if err == nil && !reflect.DeepEqual(tt.template, tt.wantResult) { - t.Errorf("wanted: %v, got: %v, difference at %v", tt.wantResult, tt.template, pretty.Compare(tt.template, tt.wantResult)) + t.Errorf("TestAddSourceAttributesForOverrideAndMerge() error: wanted: %v, got: %v, difference at %v", tt.wantResult, tt.template, pretty.Compare(tt.template, tt.wantResult)) + } else if err != nil { + assert.Regexp(t, *tt.wantErr, err.Error(), "TestAddSourceAttributesForOverrideAndMerge(): Error message should match") } }) diff --git a/pkg/devfile/parser/writer_test.go b/pkg/devfile/parser/writer_test.go index a77f3f7a..9601a253 100644 --- a/pkg/devfile/parser/writer_test.go +++ b/pkg/devfile/parser/writer_test.go @@ -40,11 +40,11 @@ func TestWriteYamlDevfile(t *testing.T) { // test func() err := devfileObj.WriteYamlDevfile() if err != nil { - t.Errorf("unexpected error: '%v'", err) + t.Errorf("TestWriteYamlDevfile() unexpected error: '%v'", err) } if _, err := fs.Stat(OutputDevfileYamlPath); err != nil { - t.Errorf("unexpected error: '%v'", err) + t.Errorf("TestWriteYamlDevfile() unexpected error: '%v'", err) } }) }