Add linting config and fix issues. (#1001)

This commit is contained in:
Markus Thömmes 2020-09-11 14:41:00 +02:00 committed by GitHub
parent a1b4f39814
commit 8f7088f0c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
62 changed files with 154 additions and 213 deletions

12
.golangci.yaml Normal file
View File

@ -0,0 +1,12 @@
run:
timeout: 5m
build-tags:
- e2e
linters:
enable:
- unconvert
- prealloc
disable:
- errcheck

View File

@ -121,7 +121,7 @@ func stripFlags(rootCmd *cobra.Command, args []string) ([]string, error) {
// Strip all plugin commands before calling out to the plugin
func argsWithoutCommands(cmdArgs []string, pluginCommandsParts []string) []string {
var ret []string
ret := make([]string, 0, len(cmdArgs))
for _, arg := range cmdArgs {
if len(pluginCommandsParts) > 0 && pluginCommandsParts[0] == arg {
pluginCommandsParts = pluginCommandsParts[1:]
@ -197,6 +197,6 @@ func extractCommandPathFromErrorMessage(errorMsg string, arg0 string) string {
// cleanupErrorMessage remove any redundance content of an error message
func cleanupErrorMessage(msg string) string {
regexp := regexp.MustCompile("(?i)^error:\\s*")
regexp := regexp.MustCompile(`(?i)^error:\s*`)
return string(regexp.ReplaceAll([]byte(msg), []byte("")))
}

View File

@ -118,7 +118,7 @@ func (c *KnRunResultCollector) errorDetails() string {
dumpInfos = append(dumpInfos, c.extraDumps...)
for _, d := range dumpInfos {
fmt.Fprintln(&out, "--------------------------[[DUMP]]-------------------------------")
fmt.Fprintf(&out, d)
fmt.Fprint(&out, d)
}
fmt.Fprintln(&out, "=================================================================")

View File

@ -26,9 +26,8 @@ import (
// MockKnDynamicClient is a combine of test object and recorder
type MockKnDynamicClient struct {
t *testing.T
recorder *ClientRecorder
namespace string
t *testing.T
recorder *ClientRecorder
}
// NewMockKnDyanmicClient returns a new mock instance which you need to record for

View File

@ -122,7 +122,7 @@ func TestListSources(t *testing.T) {
sources, err := client.ListSources(WithTypeFilter("pingsource"), WithTypeFilter("ApiServerSource"))
assert.NilError(t, err)
assert.Equal(t, len(sources.Items), 2)
assert.DeepEqual(t, sources.GroupVersionKind(), schema.GroupVersionKind{sourceListGroup, sourceListVersion, sourceListKind})
assert.DeepEqual(t, sources.GroupVersionKind(), schema.GroupVersionKind{Group: sourceListGroup, Version: sourceListVersion, Kind: sourceListKind})
})
}
@ -143,21 +143,25 @@ func TestListSourcesUsingGVKs(t *testing.T) {
newSourceUnstructuredObj("a1", "sources.knative.dev/v1alpha1", "ApiServerSource"),
)
assert.Check(t, client.RawClient() != nil)
gv := schema.GroupVersion{"sources.knative.dev", "v1alpha1"}
gv := schema.GroupVersion{Group: "sources.knative.dev", Version: "v1alpha1"}
gvks := []schema.GroupVersionKind{gv.WithKind("ApiServerSource"), gv.WithKind("PingSource")}
s, err := client.ListSourcesUsingGVKs(&gvks)
assert.NilError(t, err)
assert.Check(t, s != nil)
if s == nil {
t.Fatal("s = nil, want not nil")
}
assert.Equal(t, len(s.Items), 2)
assert.DeepEqual(t, s.GroupVersionKind(), schema.GroupVersionKind{sourceListGroup, sourceListVersion, sourceListKind})
assert.DeepEqual(t, s.GroupVersionKind(), schema.GroupVersionKind{Group: sourceListGroup, Version: sourceListVersion, Kind: sourceListKind})
// withType
s, err = client.ListSourcesUsingGVKs(&gvks, WithTypeFilter("PingSource"))
assert.NilError(t, err)
assert.Check(t, s != nil)
if s == nil {
t.Fatal("s = nil, want not nil")
}
assert.Equal(t, len(s.Items), 1)
assert.DeepEqual(t, s.GroupVersionKind(), schema.GroupVersionKind{sourceListGroup, sourceListVersion, sourceListKind})
assert.DeepEqual(t, s.GroupVersionKind(), schema.GroupVersionKind{Group: sourceListGroup, Version: sourceListVersion, Kind: sourceListKind})
})
}

View File

@ -80,7 +80,7 @@ func TestGVRFromUnstructured(t *testing.T) {
}
func TestUnstructuredCRDFromGVK(t *testing.T) {
u := UnstructuredCRDFromGVK(schema.GroupVersionKind{"sources.knative.dev", "v1alpha2", "ApiServerSource"})
u := UnstructuredCRDFromGVK(schema.GroupVersionKind{Group: "sources.knative.dev", Version: "v1alpha2", Kind: "ApiServerSource"})
g, err := groupFromUnstructured(u)
assert.NilError(t, err)
assert.Equal(t, g, "sources.knative.dev")

View File

@ -25,9 +25,8 @@ import (
// MockKnEventingClient is a combine of test object and recorder
type MockKnEventingClient struct {
t *testing.T
recorder *EventingRecorder
namespace string
t *testing.T
recorder *EventingRecorder
}
// NewMockKnEventingClient returns a new mock instance which you need to record for

View File

@ -329,9 +329,9 @@ func newBroker(name string) *v1beta1.Broker {
func getBrokerDeleteEvents(name string) []watch.Event {
return []watch.Event{
{watch.Added, createBrokerWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{watch.Modified, createBrokerWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{watch.Deleted, createBrokerWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
{Type: watch.Added, Object: createBrokerWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{Type: watch.Modified, Object: createBrokerWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{Type: watch.Deleted, Object: createBrokerWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
}
}

View File

@ -53,7 +53,7 @@ func TestCreateChannelDefaultChannel(t *testing.T) {
func TestCreateChannelWithTypeFlagInMemoryChannel(t *testing.T) {
cClient := v1beta1.NewMockKnChannelsClient(t)
cRecorder := cClient.Recorder()
cRecorder.CreateChannel(createChannel("pipe", &schema.GroupVersionKind{"messaging.knative.dev", "v1beta1", "InMemoryChannel"}), nil)
cRecorder.CreateChannel(createChannel("pipe", &schema.GroupVersionKind{Group: "messaging.knative.dev", Version: "v1beta1", Kind: "InMemoryChannel"}), nil)
out, err := executeChannelCommand(cClient, "create", "pipe", "--type", "imcv1beta1")
assert.NilError(t, err, "channel should be created")
assert.Assert(t, util.ContainsAll(out, "created", "pipe", "default"))

View File

@ -45,7 +45,7 @@ func TestDescribeChannelErrorCaseNotFound(t *testing.T) {
func TestDescribeChannel(t *testing.T) {
cClient := v1beta1.NewMockKnChannelsClient(t)
cRecorder := cClient.Recorder()
cRecorder.GetChannel("pipe", createChannel("pipe", &schema.GroupVersionKind{"messaging.knative.dev", "v1beta1", "InMemoryChannel"}), nil)
cRecorder.GetChannel("pipe", createChannel("pipe", &schema.GroupVersionKind{Group: "messaging.knative.dev", Version: "v1beta1", Kind: "InMemoryChannel"}), nil)
out, err := executeChannelCommand(cClient, "describe", "pipe")
assert.NilError(t, err, "channel should be described")
assert.Assert(t, util.ContainsAll(out, "messaging.knative.dev", "v1beta1", "InMemoryChannel", "pipe"))

View File

@ -93,7 +93,7 @@ func printChannelListWithNamespace(channelList *messagingv1beta1.ChannelList, op
rows := make([]metav1beta1.TableRow, 0, len(channelList.Items))
// temporary slice for sorting services in non-default namespace
var others []metav1beta1.TableRow
others := make([]metav1beta1.TableRow, 0, len(rows))
for _, channel := range channelList.Items {
// Fill in with services in `default` namespace at first

View File

@ -41,8 +41,8 @@ func TestChannelList(t *testing.T) {
cRecorder := cClient.Recorder()
clist := &messagingv1beta1.ChannelList{}
clist.Items = []messagingv1beta1.Channel{
*createChannel("c0", &schema.GroupVersionKind{"messaging.knative.dev", "v1beta1", "InMemoryChannel"}),
*createChannel("c1", &schema.GroupVersionKind{"messaging.knative.dev", "v1beta1", "InMemoryChannel"}),
*createChannel("c0", &schema.GroupVersionKind{Group: "messaging.knative.dev", Version: "v1beta1", Kind: "InMemoryChannel"}),
*createChannel("c1", &schema.GroupVersionKind{Group: "messaging.knative.dev", Version: "v1beta1", Kind: "InMemoryChannel"}),
}
cRecorder.ListChannel(clist, nil)
out, err := executeChannelCommand(cClient, "list")

View File

@ -86,7 +86,7 @@ func Age(t time.Time) string {
if t.IsZero() {
return ""
}
return duration.ShortHumanDuration(time.Now().Sub(t))
return duration.ShortHumanDuration(time.Since(t))
}
func formatConditionType(condition apis.Condition) string {
@ -130,9 +130,7 @@ func getMaxTypeLen(conditions []apis.Condition) int {
func sortConditions(conditions []apis.Condition) []apis.Condition {
// Don't change the orig slice
ret := make([]apis.Condition, len(conditions))
for i, c := range conditions {
ret[i] = c
}
copy(ret, conditions)
sort.SliceStable(ret, func(i, j int) bool {
ic := &ret[i]
jc := &ret[j]
@ -220,5 +218,5 @@ func joinAndTruncate(sortedKeys []string, m map[string]string, width int) string
if len(ret) <= width {
return ret
}
return string(ret[:width-4]) + " ..."
return ret[:width-4] + " ..."
}

View File

@ -84,7 +84,7 @@ func TestSortConditions(t *testing.T) {
}
}
var spaces = regexp.MustCompile("\\s*")
var spaces = regexp.MustCompile(`\s*`)
func normalizeSpace(s string) string {
return spaces.ReplaceAllLiteralString(s, " ")

View File

@ -99,7 +99,7 @@ func NonReadyConditionReason(conditions duckv1.Conditions) string {
if condition.Message != "" {
return fmt.Sprintf("%s : %s", condition.Reason, condition.Message)
}
return string(condition.Reason)
return condition.Reason
}
}
return "<unknown>"

View File

@ -34,9 +34,10 @@ import (
func TestPluginListBasic(t *testing.T) {
pluginListCmd := NewPluginListCommand(&commands.KnParams{})
assert.Assert(t, pluginListCmd != nil)
if pluginListCmd == nil {
t.Fatal("pluginListCmd = nil, want not nil")
}
assert.Assert(t, pluginListCmd != nil)
assert.Assert(t, pluginListCmd.Use == "list")
assert.Assert(t, pluginListCmd.Short == "List plugins")
assert.Assert(t, strings.Contains(pluginListCmd.Long, "List all installed plugins"))

View File

@ -25,9 +25,10 @@ import (
func TestNewPluginCommand(t *testing.T) {
pluginCmd := NewPluginCommand(&commands.KnParams{})
assert.Assert(t, pluginCmd != nil)
if pluginCmd == nil {
t.Fatal("pluginCmd = nil, want not nil")
}
assert.Assert(t, pluginCmd != nil)
assert.Equal(t, pluginCmd.Use, "plugin")
assert.Assert(t, util.ContainsAllIgnoreCase(pluginCmd.Short, "plugin"))
assert.Assert(t, util.ContainsAllIgnoreCase(pluginCmd.Long, "plugins"))

View File

@ -100,8 +100,8 @@ func TestMultipleRevisionDelete(t *testing.T) {
func getRevisionDeleteEvents(name string) []watch.Event {
return []watch.Event{
{watch.Added, &servingv1.Revision{ObjectMeta: metav1.ObjectMeta{Name: name}}},
{watch.Deleted, &servingv1.Revision{ObjectMeta: metav1.ObjectMeta{Name: name}}},
{Type: watch.Added, Object: &servingv1.Revision{ObjectMeta: metav1.ObjectMeta{Name: name}}},
{Type: watch.Deleted, Object: &servingv1.Revision{ObjectMeta: metav1.ObjectMeta{Name: name}}},
}
}

View File

@ -111,7 +111,7 @@ func describe(w io.Writer, revision *servingv1.Revision, service *servingv1.Serv
serviceSection.WriteAttribute("Latest Ready", strconv.FormatBool(revision.Name == service.Status.LatestReadyRevisionName))
percent, tags := trafficAndTagsForRevision(revision.Name, service)
if percent != 0 {
serviceSection.WriteAttribute("Traffic", strconv.FormatInt(int64(percent), 10)+"%")
serviceSection.WriteAttribute("Traffic", strconv.FormatInt(percent, 10)+"%")
}
if len(tags) > 0 {
commands.WriteSliceDesc(serviceSection, tags, "Tags", printDetails)
@ -135,7 +135,7 @@ func WriteConcurrencyOptions(dw printers.PrefixWriter, revision *servingv1.Revis
if target != nil || limit != nil && *limit != 0 || autoscaleWindow != "" || concurrencyUtilization != nil {
section := dw.WriteAttribute("Concurrency", "")
if limit != nil && *limit != 0 {
section.WriteAttribute("Limit", strconv.FormatInt(int64(*limit), 10))
section.WriteAttribute("Limit", strconv.FormatInt(*limit, 10))
}
if target != nil {
section.WriteAttribute("Target", strconv.Itoa(*target))
@ -248,7 +248,7 @@ func writeResourcesHelper(dw printers.PrefixWriter, label string, request *resou
func shortenDigest(digest string) string {
match := imageDigestRegexp.FindStringSubmatch(digest)
if len(match) > 1 {
return string(match[1][:6])
return match[1][:6]
}
return digest
}

View File

@ -103,5 +103,5 @@ func trunc(txt string) string {
if len(txt) <= ListColumnMaxLength {
return txt
}
return string(txt[:ListColumnMaxLength-4]) + " ..."
return txt[:ListColumnMaxLength-4] + " ..."
}

View File

@ -224,17 +224,6 @@ func waitForServiceToGetReady(client clientservingv1.KnServingClient, name strin
return showUrl(client, name, "", verbDone, out)
}
// Duck type for writers having a flush
type flusher interface {
Flush() error
}
func flush(out io.Writer) {
if flusher, ok := out.(flusher); ok {
flusher.Flush()
}
}
func serviceExists(client clientservingv1.KnServingClient, name string) (bool, error) {
_, err := client.GetService(name)
if apierrors.IsNotFound(err) {

View File

@ -114,9 +114,9 @@ func fakeServiceCreate(args []string, withExistingService bool) (
func getServiceEvents(name string) []watch.Event {
return []watch.Event{
{watch.Added, wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{watch.Modified, wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{watch.Modified, wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
{Type: watch.Added, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{Type: watch.Modified, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{Type: watch.Modified, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
}
}

View File

@ -98,8 +98,8 @@ func TestMultipleServiceDelete(t *testing.T) {
func getServiceDeleteEvents(name string) []watch.Event {
return []watch.Event{
{watch.Added, wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{watch.Modified, wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{watch.Deleted, wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
{Type: watch.Added, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{Type: watch.Modified, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{Type: watch.Deleted, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
}
}

View File

@ -228,11 +228,6 @@ func writeRevisions(dw printers.PrefixWriter, revisions []*revisionDesc, printDe
// ======================================================================================
// Helper functions
// Format label (extracted so that color could be added more easily to all labels)
func l(label string) string {
return label + ":"
}
// Format the revision name along with its generation. Use colors if enabled.
func revisionHeader(desc *revisionDesc) string {
header := desc.revision.Name

View File

@ -301,7 +301,7 @@ func TestServiceUpdateEnvFromRemovalWithConfigMap(t *testing.T) {
assert.Assert(t, util.ContainsAll(output, "updated", svcName, "default"))
// empty string
output, err = executeServiceCommand(client,
_, err = executeServiceCommand(client,
"update", svcName,
"--env-from", "config-map:-",
"--no-wait", "--revision-name=",
@ -647,7 +647,7 @@ func TestServiceUpdateEnvFromRemovalWithSecret(t *testing.T) {
assert.Assert(t, util.ContainsAll(output, "updated", svcName, "default"))
// empty string
output, err = executeServiceCommand(client,
_, err = executeServiceCommand(client,
"update", svcName,
"--env-from", "secret:-",
"--no-wait", "--revision-name=",

View File

@ -215,6 +215,7 @@ func TestServiceUpdateCommand(t *testing.T) {
origTemplate := &orig.Spec.Template
err := servinglib.UpdateContainerCommand(origTemplate, "./start")
assert.NilError(t, err)
action, updated, _, err := fakeServiceUpdate(orig, []string{
"service", "update", "foo", "--cmd", "/app/start", "--no-wait"})
@ -527,6 +528,7 @@ func TestServiceUpdateDoesntPinToDigestWhenUnAsked(t *testing.T) {
template := orig.Spec.Template
err := servinglib.UpdateImage(&template, "gcr.io/foo/bar:baz")
assert.NilError(t, err)
action, updated, _, err := fakeServiceUpdate(orig, []string{
"service", "update", "foo", "-e", "TARGET=Awesome", "--no-lock-to-digest", "--no-wait"})

View File

@ -27,8 +27,6 @@ import (
"knative.dev/client/pkg/kn/commands"
)
const testNamespace = "default"
var blankConfig clientcmd.ClientConfig
// TODO: Remove that blankConfig hack for tests in favor of overwriting GetConfig()

View File

@ -129,7 +129,7 @@ func writeAPIServerSource(dw printers.PrefixWriter, source *v1alpha2.ApiServerSo
func writeCeOverrides(dw printers.PrefixWriter, ceOverrides map[string]string) {
subDw := dw.WriteAttribute("CloudEvent Overrides", "")
var keys []string
keys := make([]string, 0, len(ceOverrides))
for k := range ceOverrides {
keys = append(keys, k)
}

View File

@ -50,7 +50,7 @@ type APIServerSourceUpdateFlags struct {
// getAPIServerVersionKindSelector is to construct an array of resources.
func (f *APIServerSourceUpdateFlags) getAPIServerVersionKindSelector() ([]v1alpha2.APIVersionKindSelector, error) {
var resourceList []v1alpha2.APIVersionKindSelector
resourceList := make([]v1alpha2.APIVersionKindSelector, 0, len(f.Resources))
for _, r := range f.Resources {
resourceSpec, err := getValidAPIVersionKindSelector(r)
if err != nil {
@ -198,7 +198,7 @@ func printSource(source *v1alpha2.ApiServerSource, options hprinters.PrintOption
conditions := commands.ConditionsValue(source.Status.Conditions)
ready := commands.ReadyCondition(source.Status.Conditions)
reason := strings.TrimSpace(commands.NonReadyConditionReason(source.Status.Conditions))
var resources []string
resources := make([]string, 0, len(source.Spec.Resources))
for _, resource := range source.Spec.Resources {
resources = append(resources, apiVersionKindSelectorToString(resource))
}

View File

@ -31,7 +31,7 @@ import (
var blankConfig clientcmd.ClientConfig
// Gvk used in tests
var deploymentGvk = schema.GroupVersionKind{"apps", "v1", "deployment"}
var deploymentGvk = schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "deployment"}
// TODO: Remove that blankConfig hack for tests in favor of overwriting GetConfig()
// Remove also in service_test.go

View File

@ -109,7 +109,7 @@ func writeSink(dw printers.PrefixWriter, namespace string, sink *duckv1.Destinat
func writeCeOverrides(dw printers.PrefixWriter, ceOverrides map[string]string) {
subDw := dw.WriteAttribute("CloudEvent Overrides", "")
var keys []string
keys := make([]string, 0, len(ceOverrides))
for k := range ceOverrides {
keys = append(keys, k)
}

View File

@ -33,7 +33,6 @@ const (
crdGroup = "apiextensions.k8s.io"
crdVersion = "v1beta1"
crdKind = "CustomResourceDefinition"
crdKinds = "customresourcedefinitions"
sourcesLabelKey = "duck.knative.dev/source"
sourcesLabelValue = "true"
testNamespace = "current"
@ -83,7 +82,9 @@ func TestListBuiltInSourceTypes(t *testing.T) {
fakeDynamic := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme())
sources, err := listBuiltInSourceTypes(clientdynamic.NewKnDynamicClient(fakeDynamic, "current"))
assert.NilError(t, err)
assert.Check(t, sources != nil)
if sources == nil {
t.Fatal("sources = nil, want not nil")
}
assert.Equal(t, len(sources.Items), 4)
}

View File

@ -119,7 +119,7 @@ func writePingSource(dw printers.PrefixWriter, source *v1alpha2.PingSource, prin
func writeCeOverrides(dw printers.PrefixWriter, ceOverrides map[string]string) {
subDw := dw.WriteAttribute("CloudEvent Overrides", "")
var keys []string
keys := make([]string, 0, len(ceOverrides))
for k := range ceOverrides {
keys = append(keys, k)
}

View File

@ -128,7 +128,7 @@ func printSourceListWithNamespace(sourceList *v1alpha2.PingSourceList, options h
rows := make([]metav1beta1.TableRow, 0, len(sourceList.Items))
// temporary slice for sorting services in non-default namespace
var others []metav1beta1.TableRow
others := make([]metav1beta1.TableRow, 0, len(rows))
for _, source := range sourceList.Items {
// Fill in with services in `default` namespace at first

View File

@ -16,7 +16,6 @@ package commands
import (
"bytes"
"os"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
@ -35,18 +34,10 @@ import (
const FakeNamespace = "current"
var (
oldStdout *os.File
stdout *os.File
output string
readFile, writeFile *os.File
)
// CreateTestKnCommand helper for creating test commands
func CreateTestKnCommand(cmd *cobra.Command, knParams *KnParams) (*cobra.Command, *servingv1fake.FakeServingV1, *bytes.Buffer) {
buf := new(bytes.Buffer)
fakeServing := &servingv1fake.FakeServingV1{&clienttesting.Fake{}}
fakeServing := &servingv1fake.FakeServingV1{Fake: &clienttesting.Fake{}}
knParams.Output = buf
knParams.NewServingClient = func(namespace string) (clientservingv1.KnServingClient, error) {
return clientservingv1.NewKnServingClient(fakeServing, FakeNamespace), nil

View File

@ -45,7 +45,7 @@ func TestGetFilters(t *testing.T) {
createFlag = TriggerUpdateFlags{
Filters: []string{"type="},
}
filters, err := createFlag.GetFilters()
filters, _ := createFlag.GetFilters()
wanted := map[string]string{"type": ""}
assert.DeepEqual(t, wanted, filters)

View File

@ -25,8 +25,7 @@ import (
)
var (
negPrefix = "no-"
deprecatedPrefix = "DEPRECATED:"
negPrefix = "no-"
)
// AddBothBoolFlagsUnhidden is just like AddBothBoolFlags but shows both flags.

View File

@ -70,15 +70,17 @@ func TestChannelTypesFlags(t *testing.T) {
}
for _, c := range cases {
f := &ChannelTypeFlags{}
flagset := &pflag.FlagSet{}
f.Add(flagset)
flagset.Set("type", c.arg)
gvk, err := f.Parse()
if c.expectedErrText != "" {
assert.Equal(t, err.Error(), c.expectedErrText)
} else {
assert.Equal(t, *gvk, *c.expectedGVK)
}
t.Run(c.name, func(t *testing.T) {
f := &ChannelTypeFlags{}
flagset := &pflag.FlagSet{}
f.Add(flagset)
flagset.Set("type", c.arg)
gvk, err := f.Parse()
if c.expectedErrText != "" {
assert.Equal(t, err.Error(), c.expectedErrText)
} else {
assert.Equal(t, *gvk, *c.expectedGVK)
}
})
}
}

View File

@ -327,7 +327,7 @@ func extractCommandGroup(cmd *cobra.Command, parts []string) []string {
// sorting or otherwise altering its order in any way.
func uniquePathsList(paths []string) []string {
seen := map[string]bool{}
var newPaths []string
newPaths := make([]string, 0, len(paths))
for _, p := range paths {
if seen[p] {
continue
@ -347,7 +347,7 @@ func extractPluginCommandFromFileName(name string) []string {
if len(parts) < 1 {
return []string{}
}
var ret []string
ret := make([]string, 0, len(parts)-1)
for _, p := range parts[1:] {
ret = append(ret, convertUnderscoreToDash(p))
}

View File

@ -251,12 +251,12 @@ func TestPluginHelpMessage(t *testing.T) {
root.AddCommand(serviceCmd)
helpRoot := listPluginsFunc(root)
re := regexp.MustCompile("^\\s*admin\\s.*admin")
re := regexp.MustCompile(`^\s*admin\s.*admin`)
assert.Assert(t, re.MatchString(helpRoot))
helpService := listPluginsFunc(serviceCmd)
println(helpService)
re = regexp.MustCompile("^\\s*log-2\\s.*kn-service-log_2")
re = regexp.MustCompile(`^\s*log-2\s.*kn-service-log_2`)
assert.Assert(t, re.MatchString(helpService))
helpServiceCreate := listPluginsFunc(serviceCreateCmd)

View File

@ -169,10 +169,7 @@ func checkIfUserInGroup(gid uint32) (bool, error) {
}
func checkIfUserIsFileOwner(uid uint32) bool {
if int(uid) == os.Getuid() {
return true
}
return false
return int(uid) == os.Getuid()
}
// Check if all can execute, and the user is not file owner and not in the file's perm group

View File

@ -161,7 +161,7 @@ func validateCommandStructure(cmd *cobra.Command) error {
// ExtractSubCommandNames extracts the names of all sub commands of a given command
func ExtractSubCommandNames(cmds []*cobra.Command) []string {
var ret []string
ret := make([]string, 0, len(cmds))
for _, subCmd := range cmds {
ret = append(ret, subCmd.Name())
}

View File

@ -28,7 +28,9 @@ import (
func TestNewRootCommand(t *testing.T) {
rootCmd, err := NewRootCommand(nil)
assert.NilError(t, err)
assert.Assert(t, rootCmd != nil)
if rootCmd == nil {
t.Fatal("rootCmd = nil, want not nil")
}
assert.Equal(t, rootCmd.Name(), "kn")
assert.Assert(t, util.ContainsAll(rootCmd.Short, "Knative", "Serving", "Eventing"))
@ -114,14 +116,18 @@ func TestCommandGroupWithRunMethod(t *testing.T) {
func checkLeafCommand(t *testing.T, name string, rootCmd *cobra.Command) {
cmd, _, err := rootCmd.Find([]string{name})
assert.Assert(t, err == nil)
assert.Assert(t, cmd != nil)
if cmd == nil {
t.Fatal("cmd = nil, want not nil")
}
assert.Assert(t, !cmd.HasSubCommands())
}
func checkCommandGroup(t *testing.T, commands []string, rootCmd *cobra.Command) {
cmd, _, err := rootCmd.Find(commands)
assert.Assert(t, err == nil)
assert.Assert(t, cmd != nil)
if cmd == nil {
t.Fatal("cmd = nil, want not nil")
}
assert.Assert(t, cmd.RunE != nil)
assert.Assert(t, cmd.HasSubCommands())

View File

@ -105,7 +105,7 @@ func (e ServiceTraffic) isRevisionPresent(revision string) bool {
func (e ServiceTraffic) isLatestRevisionTrue() bool {
for _, target := range e {
if *target.LatestRevision == true {
if *target.LatestRevision {
return true
}
}

View File

@ -23,9 +23,8 @@ import (
)
type MockKnChannelsClient struct {
t *testing.T
recorder *ChannelsRecorder
namespace string
t *testing.T
recorder *ChannelsRecorder
}
// NewMockKnChannelsClient returns a new mock instance which you need to record for

View File

@ -73,9 +73,7 @@ func (h *HumanReadablePrinter) GenerateTable(obj runtime.Object, options PrintOp
return nil, results[1].Interface().(error)
}
var columns []metav1beta1.TableColumnDefinition
columns = make([]metav1beta1.TableColumnDefinition, 0, len(handler.columnDefinitions))
columns := make([]metav1beta1.TableColumnDefinition, 0, len(handler.columnDefinitions))
for i := range handler.columnDefinitions {
columns = append(columns, handler.columnDefinitions[i])
}

View File

@ -45,9 +45,8 @@ func (h *HumanReadablePrinter) PrintObj(obj runtime.Object, output io.Writer) er
return nil
}
w, found := output.(*tabwriter.Writer)
if !found {
w = NewTabWriter(output)
if _, found := output.(*tabwriter.Writer); !found {
w := NewTabWriter(output)
output = w
defer w.Flush()
}

View File

@ -132,25 +132,6 @@ func TestFreezeImageToDigest(t *testing.T) {
assert.Equal(t, container.Image, "gcr.io/foo/bar@sha256:deadbeef")
}
func testUpdateEnvVarsAppendOld(t *testing.T, template *servingv1.RevisionTemplateSpec, container *corev1.Container) {
container.Env = []corev1.EnvVar{
{Name: "a", Value: "foo"},
}
env := map[string]string{
"b": "bar",
}
err := UpdateEnvVars(template, env, []string{})
assert.NilError(t, err)
expected := []corev1.EnvVar{
{Name: "a", Value: "foo"},
{Name: "b", Value: "bar"},
}
assert.DeepEqual(t, expected, container.Env)
}
func TestUpdateEnvVarsModify(t *testing.T) {
revision, container := getRevisionTemplate()
container.Env = []corev1.EnvVar{
@ -181,7 +162,7 @@ func TestUpdateEnvVarsRemove(t *testing.T) {
assert.NilError(t, err)
expected := []corev1.EnvVar{
{"a", "foo", nil},
{Name: "a", Value: "foo"},
}
assert.DeepEqual(t, expected, container.Env)

View File

@ -28,9 +28,8 @@ import (
)
type MockKnServingClient struct {
t *testing.T
recorder *ServingRecorder
namespace string
t *testing.T
recorder *ServingRecorder
}
// NewMockKnServiceClient returns a new mock instance which you need to record for

View File

@ -205,9 +205,9 @@ func TestDeleteService(t *testing.T) {
func getServiceDeleteEvents(name string) []watch.Event {
return []watch.Event{
{watch.Added, wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{watch.Modified, wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{watch.Deleted, wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
{Type: watch.Added, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{Type: watch.Modified, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{Type: watch.Deleted, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
}
}
@ -529,8 +529,8 @@ func newRoute(name string) *servingv1.Route {
func getServiceEvents(name string) []watch.Event {
return []watch.Event{
{watch.Added, wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{watch.Modified, wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{watch.Modified, wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
{Type: watch.Added, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{Type: watch.Modified, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", "msg2")},
{Type: watch.Modified, Object: wait.CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
}
}

View File

@ -24,9 +24,8 @@ import (
// MockKnAPIServerSourceClient for mocking the client
type MockKnAPIServerSourceClient struct {
t *testing.T
recorder *APIServerSourcesRecorder
namespace string
t *testing.T
recorder *APIServerSourcesRecorder
}
// NewMockKnAPIServerSourceClient returns a new mock instance which you need to record for

View File

@ -24,9 +24,8 @@ import (
// MockKnSinkBindingClient is a combine of test object and recorder
type MockKnSinkBindingClient struct {
t *testing.T
recorder *EventingRecorder
namespace string
t *testing.T
recorder *EventingRecorder
}
// NewMockKnSinkBindingClient returns a new mock instance which you need to record for

View File

@ -195,7 +195,7 @@ func TestSinkBindingBuilderForSubjectError(t *testing.T) {
assert.ErrorContains(t, err, "kind")
b, err = NewSinkBindingBuilder("test").
SubjectGVK(&schema.GroupVersionKind{"apps", "v1", "Deployment"}).
SubjectGVK(&schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}).
SubjectName("foo").
AddSubjectMatchLabel("bla", "blub").
Build()
@ -207,7 +207,7 @@ func TestSinkBindingBuilderForSubjectError(t *testing.T) {
}
func TestSinkBindingBuilderForSubject(t *testing.T) {
gvk := schema.GroupVersionKind{"apps", "v1", "Deployment"}
gvk := schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}
b, err := NewSinkBindingBuilder("test").
SubjectGVK(&gvk).
@ -220,7 +220,7 @@ func TestSinkBindingBuilderForSubject(t *testing.T) {
assert.DeepEqual(t, subject.GroupVersionKind(), gvk)
b, err = NewSinkBindingBuilder("test").
SubjectGVK(&schema.GroupVersionKind{"apps", "v1", "Deployment"}).
SubjectGVK(&schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}).
AddSubjectMatchLabel("bla", "blub").
AddSubjectMatchLabel("foo", "bar").
Build()
@ -259,7 +259,7 @@ func newSinkBinding(name, sinkService, pingName string) *v1alpha2.SinkBinding {
b, _ := NewSinkBindingBuilder(name).
Namespace(testNamespace).
Sink(sink).
SubjectGVK(&schema.GroupVersionKind{"batch", "v1beta1", "CronJob"}).
SubjectGVK(&schema.GroupVersionKind{Group: "batch", Version: "v1beta1", Kind: "CronJob"}).
SubjectName(pingName).
CloudEventOverrides(map[string]string{"type": "foo"}, []string{}).
Build()

View File

@ -23,9 +23,8 @@ import (
)
type MockKnPingSourceClient struct {
t *testing.T
recorder *PingSourcesRecorder
namespace string
t *testing.T
recorder *PingSourcesRecorder
}
// NewMockKnPingSourceClient returns a new mock instance which you need to record for

View File

@ -106,7 +106,7 @@ func (e templateEngine) templateFunctions() template.FuncMap {
}
func (e templateEngine) cmdGroupsString() string {
var groups []string
groups := make([]string, 0, len(e.CommandGroups))
for _, cmdGroup := range e.CommandGroups {
groups = append(groups, formatCommandGroup(cmdGroup))
}

View File

@ -24,12 +24,6 @@ import (
// and adapted to the specific needs of `kn`
const (
// sectionAliases is the help template section that displays command aliases.
sectionAliases = `{{if gt .Aliases 0}}Aliases:
{{.NameAndAliases}}
{{end}}`
// sectionExamples is the help template section that displays command examples.
sectionExamples = `{{if .HasExample}}Examples:
{{trimRight .Example}}

View File

@ -129,7 +129,7 @@ func (it *orderedMapIterator) Next() (string, interface{}, bool) {
}
key := it.orderedMap.Keys[it.nextIndex]
ve, _ := it.orderedMap.ValueMap[key]
ve := it.orderedMap.ValueMap[key]
it.nextIndex++

View File

@ -53,10 +53,10 @@ func newFakePollInterval(n int) PollInterval {
func newWatcherForTest(pollResults []runtime.Object) watch.Interface {
i := 0
poll := func() (runtime.Object, error) {
defer func() { i += 1 }()
defer func() { i++ }()
if pollResults[i] == nil {
// 404
return nil, api_errors.NewNotFound(schema.GroupResource{"thing", "stuff"}, "eggs")
return nil, api_errors.NewNotFound(schema.GroupResource{Group: "thing", Resource: "stuff"}, "eggs")
}
return pollResults[i], nil
}
@ -87,14 +87,14 @@ type testCase struct {
func TestPollWatcher(t *testing.T) {
cases := []testCase{
// Doesn't exist for a while, then does for a while.
{[]runtime.Object{nil, nil, a, aa, nil}, []watch.Event{{watch.Added, a}, {watch.Deleted, a}}},
{[]runtime.Object{nil, nil, a, aa, nil}, []watch.Event{{Type: watch.Added, Object: a}, {Type: watch.Deleted, Object: a}}},
// Changes.
{[]runtime.Object{a, b}, []watch.Event{{watch.Added, a}, {watch.Modified, b}}},
{[]runtime.Object{a, b}, []watch.Event{{Type: watch.Added, Object: a}, {Type: watch.Modified, Object: b}}},
// Changes but stays the same a couple times too.
{[]runtime.Object{a, aa, b, bb, c, cc, nil},
[]watch.Event{{watch.Added, a}, {watch.Modified, b}, {watch.Modified, c}, {watch.Deleted, c}}},
[]watch.Event{{Type: watch.Added, Object: a}, {Type: watch.Modified, Object: b}, {Type: watch.Modified, Object: c}, {Type: watch.Deleted, Object: c}}},
// Deleted and recreated between polls.
{[]runtime.Object{a, z}, []watch.Event{{watch.Added, a}, {watch.Deleted, a}, {watch.Added, z}}},
{[]runtime.Object{a, z}, []watch.Event{{Type: watch.Added, Object: a}, {Type: watch.Deleted, Object: a}, {Type: watch.Added, Object: z}}},
}
for _, c := range cases {
w := newWatcherForTest(c.pollResults)

View File

@ -129,8 +129,8 @@ func prepareDeleteTestCases(name string) []waitForReadyTestCase {
func errorTest(name string) waitForReadyTestCase {
events := []watch.Event{
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionFalse, corev1.ConditionTrue, "FakeError", "Test Error")},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", "msg1")},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionFalse, corev1.ConditionTrue, "FakeError", "Test Error")},
}
return waitForReadyTestCase{
@ -162,41 +162,41 @@ func pMessages(max int) []string {
func peNormal(name string) ([]watch.Event, int) {
messages := pMessages(2)
return []watch.Event{
{watch.Added, CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", messages[1])},
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
{Type: watch.Added, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", messages[1])},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
}, len(messages)
}
func peTimeout(name string) ([]watch.Event, int) {
messages := pMessages(1)
return []watch.Event{
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
}, len(messages)
}
func peWrongGeneration(name string) ([]watch.Event, int) {
messages := pMessages(1)
return []watch.Event{
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "", 1, 2)},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "", 1, 2)},
}, len(messages)
}
func peReadyFalseWithinErrorWindow(name string) ([]watch.Event, int) {
messages := pMessages(1)
return []watch.Event{
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionFalse, corev1.ConditionFalse, "Route not ready", messages[0])},
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "Route ready", "")},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionFalse, corev1.ConditionFalse, "Route not ready", messages[0])},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "Route ready", "")},
}, len(messages)
}
func deNormal(name string) ([]watch.Event, int) {
messages := pMessages(2)
return []watch.Event{
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
{watch.Modified, CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", messages[1])},
{watch.Deleted, CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionUnknown, "", messages[0])},
{Type: watch.Modified, Object: CreateTestServiceWithConditions(name, corev1.ConditionUnknown, corev1.ConditionTrue, "", messages[1])},
{Type: watch.Deleted, Object: CreateTestServiceWithConditions(name, corev1.ConditionTrue, corev1.ConditionTrue, "", "")},
}, len(messages)
}

View File

@ -98,21 +98,6 @@ func pingSourceUpdateSink(r *test.KnRunResultCollector, sourceName string, sink
r.AssertNoError(out)
}
func pingSourceCreateWithResources(r *test.KnRunResultCollector, sourceName string, schedule string, data string, sink string, sa string, requestcpu string, requestmm string, limitcpu string, limitmm string) {
out := r.KnTest().Kn().Run("source", "ping", "create", sourceName,
"--schedule", schedule, "--data", data, "--sink", sink, "--service-account", sa,
"--requests-cpu", requestcpu, "--requests-memory", requestmm, "--limits-cpu", limitcpu, "--limits-memory", limitmm)
assert.Check(r.T(), util.ContainsAllIgnoreCase(out.Stdout, "ping", "source", sourceName, "created", "namespace", r.KnTest().Kn().Namespace()))
r.AssertNoError(out)
}
func pingSourceUpdateResources(r *test.KnRunResultCollector, sourceName string, requestcpu string, requestmm string, limitcpu string, limitmm string) {
out := r.KnTest().Kn().Run("source", "ping", "update", sourceName,
"--requests-cpu", requestcpu, "--requests-memory", requestmm, "--limits-cpu", limitcpu, "--limits-memory", limitmm)
assert.Check(r.T(), util.ContainsAllIgnoreCase(out.Stdout, sourceName, "updated", "namespace", r.KnTest().Kn().Namespace()))
r.AssertNoError(out)
}
func verifyPingSourceDescribe(r *test.KnRunResultCollector, sourceName string, schedule string, data string, sink string) {
out := r.KnTest().Kn().Run("source", "ping", "describe", sourceName)
assert.Check(r.T(), util.ContainsAllIgnoreCase(out.Stdout, sourceName, schedule, data, sink))

View File

@ -43,8 +43,8 @@ exit 1`
)
type pluginTestConfig struct {
knConfigDir, knPluginsDir, knPluginsDir2, knPluginsDir3 string
knConfigPath, knPluginPath, knPluginPath2, knPluginsPath3 string
knConfigDir, knPluginsDir, knPluginsDir2 string
knConfigPath, knPluginPath, knPluginPath2 string
}
func (pc *pluginTestConfig) setup() error {

View File

@ -425,11 +425,6 @@ func withServiceName(name string) expectedServiceOption {
svc.ObjectMeta.Name = name
}
}
func withConfigurationLabels(labels map[string]string) expectedServiceOption {
return func(svc *servingv1.Service) {
svc.Spec.Template.ObjectMeta.Labels = labels
}
}
func withConfigurationAnnotations(annotations map[string]string) expectedServiceOption {
return func(svc *servingv1.Service) {
svc.Spec.Template.ObjectMeta.Annotations = annotations