1
16
17 package validation
18
19 import (
20 "testing"
21
22 "k8s.io/apimachinery/pkg/api/resource"
23 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
24 api "k8s.io/kubernetes/pkg/apis/core"
25 )
26
27 func TestValidatePersistentVolumes(t *testing.T) {
28 scenarios := map[string]struct {
29 isExpectedFailure bool
30 volume *api.PersistentVolume
31 }{
32 "volume with valid mount option for nfs": {
33 isExpectedFailure: false,
34 volume: testVolumeWithMountOption("good-nfs-mount-volume", "", "ro,nfsvers=3", api.PersistentVolumeSpec{
35 Capacity: api.ResourceList{
36 api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
37 },
38 AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
39 PersistentVolumeSource: api.PersistentVolumeSource{
40 NFS: &api.NFSVolumeSource{Server: "localhost", Path: "/srv", ReadOnly: false},
41 },
42 }),
43 },
44 "volume with mount option for host path": {
45 isExpectedFailure: true,
46 volume: testVolumeWithMountOption("bad-hostpath-mount-volume", "", "ro,nfsvers=3", api.PersistentVolumeSpec{
47 Capacity: api.ResourceList{
48 api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
49 },
50 AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
51 PersistentVolumeSource: api.PersistentVolumeSource{
52 HostPath: &api.HostPathVolumeSource{Path: "/a/.."},
53 },
54 }),
55 },
56 }
57
58 for name, scenario := range scenarios {
59 errs := ValidatePersistentVolume(scenario.volume)
60 if len(errs) == 0 && scenario.isExpectedFailure {
61 t.Errorf("Unexpected success for scenario: %s", name)
62 }
63 if len(errs) > 0 && !scenario.isExpectedFailure {
64 t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
65 }
66 }
67 }
68
69 func testVolumeWithMountOption(name string, namespace string, mountOptions string, spec api.PersistentVolumeSpec) *api.PersistentVolume {
70 annotations := map[string]string{
71 api.MountOptionAnnotation: mountOptions,
72 }
73 objMeta := metav1.ObjectMeta{
74 Name: name,
75 Annotations: annotations,
76 }
77
78 if namespace != "" {
79 objMeta.Namespace = namespace
80 }
81
82 return &api.PersistentVolume{
83 ObjectMeta: objMeta,
84 Spec: spec,
85 }
86 }
87
88 func TestValidatePathNoBacksteps(t *testing.T) {
89 testCases := map[string]struct {
90 path string
91 expectedErr bool
92 }{
93 "valid path": {
94 path: "/foo/bar",
95 },
96 "invalid path": {
97 path: "/foo/bar/..",
98 expectedErr: true,
99 },
100 }
101
102 for name, tc := range testCases {
103 err := ValidatePathNoBacksteps(tc.path)
104
105 if err == nil && tc.expectedErr {
106 t.Fatalf("expected test `%s` to return an error but it didn't", name)
107 }
108
109 if err != nil && !tc.expectedErr {
110 t.Fatalf("expected test `%s` to return no error but got `%v`", name, err)
111 }
112 }
113 }
114
View as plain text