From 811b880f0ffd6dfa55ba348e88b9d2b963ec92a3 Mon Sep 17 00:00:00 2001 From: Peter Kurfer Date: Thu, 14 Apr 2022 18:20:52 +0200 Subject: [PATCH] Add tests for types --- reaper/types.go | 5 +++ reaper/types_test.go | 103 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 reaper/types_test.go diff --git a/reaper/types.go b/reaper/types.go index 86d0ea0..a770cf6 100644 --- a/reaper/types.go +++ b/reaper/types.go @@ -48,6 +48,11 @@ func (t Target) String() string { } func (t *Target) Set(s string) error { + tmp := Target(s) + if _, err := tmp.Selector(); err != nil { + return err + } + val := (*string)(t) *val = s return nil diff --git a/reaper/types_test.go b/reaper/types_test.go new file mode 100644 index 0000000..319a053 --- /dev/null +++ b/reaper/types_test.go @@ -0,0 +1,103 @@ +package reaper_test + +import ( + "flag" + "testing" + + "github.com/maxatome/go-testdeep/td" + + "github.com/baez90/kreaper/reaper" +) + +func TestParseTarget(t *testing.T) { + t.Parallel() + tests := []struct { + name string + in string + wantErr bool + }{ + { + name: "Empty target", + in: "", + wantErr: true, + }, + { + name: "Missing value", + in: "app", + wantErr: true, + }, + { + name: "Invalid separator", + in: "app: prometheus", + wantErr: true, + }, + { + name: "Simple target", + in: "app=prometheus", + }, + { + name: "full qualified target", + in: "app.kubernetes.io/name=prometheus", + }, + { + name: "Invalid domain - too many path segments", + in: "app.kubernetes.io/name/detailed=prometheus", + wantErr: true, + }, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + _, err := reaper.ParseTarget(tt.in) + if (err != nil) != tt.wantErr { + t.Errorf("ParseTarget() error = %v, wantErr %v", err, tt.wantErr) + return + } + }) + } +} + +func TestTargetFlag(t *testing.T) { + t.Parallel() + tests := []struct { + name string + args []string + want reaper.Target + wantErr bool + }{ + { + name: "Empty args", + }, + { + name: "Valid target", + args: []string{"-target", "app.kubernetes.io/name=prometheus"}, + want: "app.kubernetes.io/name=prometheus", + wantErr: false, + }, + { + name: "Invalid target", + args: []string{"-target", "app.kubernetes.io/name/detailed=prometheus"}, + want: "", + wantErr: true, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var target reaper.Target + flagSet := flag.NewFlagSet(t.Name(), flag.ContinueOnError) + flagSet.Var(&target, "target", "") + if err := flagSet.Parse(tt.args); err != nil { + if !tt.wantErr { + t.Errorf("Failed to parse arguments: %v", err) + } + return + } + + td.Cmp(t, target, tt.want) + }) + } +}