Skip to content

Commit

Permalink
Merge pull request nephio-project#84 from Nordix/rpkg-unit-test
Browse files Browse the repository at this point in the history
Add unit tests for rpkg commands
  • Loading branch information
nephio-prow[bot] authored Jul 22, 2024
2 parents 170d423 + 4e27641 commit 05ae047
Show file tree
Hide file tree
Showing 12 changed files with 788 additions and 58 deletions.
34 changes: 4 additions & 30 deletions internal/kpt/util/porch/approval.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,27 @@
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package porch

import (
"context"
"fmt"

"github.com/nephio-project/porch/api/porch/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
)

func UpdatePackageRevisionApproval(ctx context.Context, client rest.Interface, key client.ObjectKey, new v1alpha1.PackageRevisionLifecycle) error {
scheme := runtime.NewScheme()
if err := v1alpha1.SchemeBuilder.AddToScheme(scheme); err != nil {
return err
}
func UpdatePackageRevisionApproval(ctx context.Context, client client.Client, key client.ObjectKey, new v1alpha1.PackageRevisionLifecycle) error {

codec := runtime.NewParameterCodec(scheme)
var pr v1alpha1.PackageRevision
if err := client.Get().
Namespace(key.Namespace).
Resource("packagerevisions").
Name(key.Name).
VersionedParams(&metav1.GetOptions{}, codec).
Do(ctx).
Into(&pr); err != nil {
if err := client.Get(ctx, key, &pr); err != nil {
return err
}

Expand All @@ -52,19 +37,8 @@ func UpdatePackageRevisionApproval(ctx context.Context, client rest.Interface, k
default:
return fmt.Errorf("cannot change approval from %s to %s", lifecycle, new)
}

// Approve - change the package revision kind to "final".
pr.Spec.Lifecycle = new
return client.SubResource("approval").Update(ctx, &pr)

opts := metav1.UpdateOptions{}
result := &v1alpha1.PackageRevision{}
return client.Put().
Namespace(pr.Namespace).
Resource("packagerevisions").
Name(pr.Name).
SubResource("approval").
VersionedParams(&opts, codec).
Body(&pr).
Do(ctx).
Into(result)
}
10 changes: 4 additions & 6 deletions pkg/cli/commands/rpkg/approve/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
"github.com/nephio-project/porch/pkg/cli/commands/rpkg/docs"
"github.com/spf13/cobra"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
)

Expand All @@ -39,9 +38,8 @@ func NewCommand(ctx context.Context, rcg *genericclioptions.ConfigFlags) *cobra.

func newRunner(ctx context.Context, rcg *genericclioptions.ConfigFlags) *runner {
r := &runner{
ctx: ctx,
cfg: rcg,
client: nil,
ctx: ctx,
cfg: rcg,
}

c := &cobra.Command{
Expand All @@ -61,7 +59,7 @@ func newRunner(ctx context.Context, rcg *genericclioptions.ConfigFlags) *runner
type runner struct {
ctx context.Context
cfg *genericclioptions.ConfigFlags
client rest.Interface
client client.Client
Command *cobra.Command

// Flags
Expand All @@ -70,7 +68,7 @@ type runner struct {
func (r *runner) preRunE(_ *cobra.Command, _ []string) error {
const op errors.Op = command + ".preRunE"

client, err := porch.CreateRESTClient(r.cfg)
client, err := porch.CreateClientWithFlags(r.cfg)
if err != nil {
return errors.E(op, err)
}
Expand Down
190 changes: 190 additions & 0 deletions pkg/cli/commands/rpkg/approve/command_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
// Copyright 2024 The kpt and Nephio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package approve

import (
"context"
"io"
"os"
"testing"

"github.com/google/go-cmp/cmp"
porchapi "github.com/nephio-project/porch/api/porch/v1alpha1"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/genericclioptions"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
)

func createScheme() (*runtime.Scheme, error) {
scheme := runtime.NewScheme()
for _, api := range (runtime.SchemeBuilder{
porchapi.AddToScheme,
}) {
if err := api(scheme); err != nil {
return nil, err
}
}
scheme.AddKnownTypes(porchapi.SchemeGroupVersion, &porchapi.PackageRevision{})
return scheme, nil
}

func TestCmd(t *testing.T) {
pkgRevName := "test-pr"
repoName := "test-repo"
ns := "ns"
var scheme, err = createScheme()
if err != nil {
t.Fatalf("error creating scheme: %v", err)
}
testCases := map[string]struct {
output string
wantErr bool
fakeclient client.WithWatch
}{
"Package not found in ns": {
wantErr: true,
output: pkgRevName + " failed (packagerevisions.porch.kpt.dev \"" + pkgRevName + "\" not found)\n",
fakeclient: fake.NewClientBuilder().WithScheme(scheme).
WithObjects(&porchapi.PackageRevision{
TypeMeta: metav1.TypeMeta{
Kind: "PackageRevision",
APIVersion: porchapi.SchemeGroupVersion.Identifier(),
},
ObjectMeta: metav1.ObjectMeta{
Namespace: "dummy",
Name: pkgRevName,
}}).Build(),
},
"Approve draft package": {
wantErr: true,
output: pkgRevName + " failed (cannot change approval from Draft to Published)\n",
fakeclient: fake.NewClientBuilder().WithScheme(scheme).
WithObjects(&porchapi.PackageRevision{
TypeMeta: metav1.TypeMeta{
Kind: "PackageRevision",
APIVersion: porchapi.SchemeGroupVersion.Identifier(),
},
Spec: porchapi.PackageRevisionSpec{
Lifecycle: porchapi.PackageRevisionLifecycleDraft,
RepositoryName: repoName,
},
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: pkgRevName,
}}).Build(),
},
"Approve published package": {
output: pkgRevName + " approved\n",
fakeclient: fake.NewClientBuilder().WithScheme(scheme).
WithObjects(&porchapi.PackageRevision{
TypeMeta: metav1.TypeMeta{
Kind: "PackageRevision",
APIVersion: porchapi.SchemeGroupVersion.Identifier(),
},
Spec: porchapi.PackageRevisionSpec{
Lifecycle: porchapi.PackageRevisionLifecyclePublished,
RepositoryName: repoName,
},
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: pkgRevName,
}}).Build(),
},
"Approve deletion-proposed package": {
output: pkgRevName + " approved\n",
fakeclient: fake.NewClientBuilder().WithInterceptorFuncs(interceptor.Funcs{
//fake subresourceupdate
SubResourceUpdate: func(ctx context.Context, client client.Client, subResourceName string, obj client.Object, opts ...client.SubResourceUpdateOption) error {
return nil
},
}).WithScheme(scheme).
WithObjects(&porchapi.PackageRevision{
TypeMeta: metav1.TypeMeta{
Kind: "PackageRevision",
APIVersion: porchapi.SchemeGroupVersion.Identifier(),
},
Spec: porchapi.PackageRevisionSpec{
Lifecycle: porchapi.PackageRevisionLifecycleDeletionProposed,
RepositoryName: repoName,
},
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: pkgRevName,
}}).Build(),
},
"Approve proposed package": {
output: pkgRevName + " approved\n",
fakeclient: fake.NewClientBuilder().WithInterceptorFuncs(interceptor.Funcs{
//fake subresourceupdate
SubResourceUpdate: func(ctx context.Context, client client.Client, subResourceName string, obj client.Object, opts ...client.SubResourceUpdateOption) error {
return nil
},
}).WithScheme(scheme).
WithObjects(&porchapi.PackageRevision{
TypeMeta: metav1.TypeMeta{
Kind: "PackageRevision",
APIVersion: porchapi.SchemeGroupVersion.Identifier(),
},
Spec: porchapi.PackageRevisionSpec{
Lifecycle: porchapi.PackageRevisionLifecycleProposed,
RepositoryName: repoName,
},
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: pkgRevName,
}}).Build(),
},
}

for tn := range testCases {
tc := testCases[tn]
t.Run(tn, func(t *testing.T) {

cmd := &cobra.Command{}
o := os.Stdout
e := os.Stderr
read, write, _ := os.Pipe()
os.Stdout = write
os.Stderr = write

r := &runner{
ctx: context.Background(),
cfg: &genericclioptions.ConfigFlags{
Namespace: &ns,
},
client: tc.fakeclient,
Command: cmd,
}
go func() {
defer write.Close()
err := r.runE(cmd, []string{pkgRevName})
if err != nil && !tc.wantErr {
t.Errorf("unexpected error: %v", err)
}
}()
out, _ := io.ReadAll(read)
os.Stdout = o
os.Stderr = e

if diff := cmp.Diff(string(tc.output), string(out)); diff != "" {
t.Errorf("Unexpected result (-want, +got): %s", diff)
}
})
}
}
Loading

0 comments on commit 05ae047

Please sign in to comment.