|
| 1 | +/* |
| 2 | +Copyright 2020 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package behaviors |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "io/ioutil" |
| 22 | + utilerrors "k8s.io/apimachinery/pkg/util/errors" |
| 23 | + "os" |
| 24 | + "path/filepath" |
| 25 | + "regexp" |
| 26 | + "strings" |
| 27 | + |
| 28 | + "gopkg.in/yaml.v2" |
| 29 | +) |
| 30 | + |
| 31 | +// BehaviorFileList returns a list of eligible behavior files in or under dir |
| 32 | +func BehaviorFileList(dir string) ([]string, error) { |
| 33 | + var behaviorFiles []string |
| 34 | + |
| 35 | + r, _ := regexp.Compile(".+.yaml$") |
| 36 | + err := filepath.Walk(dir, |
| 37 | + func(path string, info os.FileInfo, err error) error { |
| 38 | + if err != nil { |
| 39 | + return err |
| 40 | + } |
| 41 | + if r.MatchString(path) { |
| 42 | + behaviorFiles = append(behaviorFiles, path) |
| 43 | + } |
| 44 | + return nil |
| 45 | + }, |
| 46 | + ) |
| 47 | + return behaviorFiles, err |
| 48 | +} |
| 49 | + |
| 50 | +// LoadSuite loads a Behavior Suite from .yaml file at path |
| 51 | +func LoadSuite(path string) (*Suite, error) { |
| 52 | + var suite Suite |
| 53 | + bytes, err := ioutil.ReadFile(path) |
| 54 | + if err != nil { |
| 55 | + return nil, fmt.Errorf("error loading suite %s: %v", path, err) |
| 56 | + } |
| 57 | + err = yaml.UnmarshalStrict(bytes, &suite) |
| 58 | + if err != nil { |
| 59 | + return nil, fmt.Errorf("error loading suite %s: %v", path, err) |
| 60 | + } |
| 61 | + return &suite, nil |
| 62 | +} |
| 63 | + |
| 64 | +// ValidateSuite validates that the given suite has no duplicate behavior IDs |
| 65 | +func ValidateSuite(suite *Suite) error { |
| 66 | + var errs []error |
| 67 | + behaviorsByID := make(map[string]bool) |
| 68 | + for _, b := range suite.Behaviors { |
| 69 | + if _, ok := behaviorsByID[b.ID]; ok { |
| 70 | + errs = append(errs, fmt.Errorf("Duplicate behavior ID: %s", b.ID)) |
| 71 | + } |
| 72 | + if !strings.HasPrefix(b.ID, suite.Suite) { |
| 73 | + errs = append(errs, fmt.Errorf("Invalid behavior ID: %s, must have suite name as prefix: %s", b.ID, suite.Suite)) |
| 74 | + } |
| 75 | + behaviorsByID[b.ID] = true |
| 76 | + } |
| 77 | + return utilerrors.NewAggregate(errs) |
| 78 | +} |
0 commit comments