Skip to content

Commit

Permalink
Test controller to the point of committing changes
Browse files Browse the repository at this point in the history
This adds a test for the controller, checking that it will commit and
push a change, with the given commit message. I think checking it made
the right change will need a bit of rejigging tests elsewhere, so I
can compare directory contents (as with pkg/update tests).
  • Loading branch information
squaremo committed Jul 23, 2020
1 parent d3a8b90 commit 7bdbe7e
Show file tree
Hide file tree
Showing 6 changed files with 213 additions and 31 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
notes

# This is downloaded in the Makefile
controllers/testdata/crds/*

# Binaries for programs and plugins
*.exe
*.exe~
Expand Down
21 changes: 20 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,36 @@ IMG ?= squaremo/image-automation-controller
# Produce CRDs that work back to Kubernetes 1.11 (no version conversion)
CRD_OPTIONS ?= "crd:trivialVersions=true"

# Version of the Toolkit from which to get CRDs. Change this if you
# bump the go module version.
TOOLKIT_VERSION:=v0.0.6

# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)
ifeq (,$(shell go env GOBIN))
GOBIN=$(shell go env GOPATH)/bin
else
GOBIN=$(shell go env GOBIN)
endif

TEST_CRDS:=controllers/testdata/crds

all: manager

# Running the tests requires the source.fluxcd.io CRDs
test_deps: ${TEST_CRDS}/imagepolicies.yaml ${TEST_CRDS}/gitrepositories.yaml

${TEST_CRDS}/gitrepositories.yaml:
mkdir -p ${TEST_CRDS}
curl -s https://raw.githubusercontent.com/fluxcd/source-controller/${TOOLKIT_VERSION}/config/crd/bases/source.fluxcd.io_gitrepositories.yaml \
-o ${TEST_CRDS}/gitrepositories.yaml

${TEST_CRDS}/imagepolicies.yaml:
mkdir -p ${TEST_CRDS}
curl -s https://raw.githubusercontent.com/squaremo/image-reflector-controller/master/config/crd/bases/image.fluxcd.io_imagepolicies.yaml \
-o ${TEST_CRDS}/imagepolicies.yaml

# Run tests
test: generate fmt vet manifests
test: test_deps generate fmt vet manifests
go test ./... -coverprofile cover.out

# Build manager binary
Expand Down
25 changes: 15 additions & 10 deletions controllers/imageupdateautomation_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"time"

gogit "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-logr/logr"
Expand Down Expand Up @@ -137,12 +138,15 @@ func (r *ImageUpdateAutomationReconciler) Reconcile(req ctrl.Request) (ctrl.Resu

log.V(debug).Info("made updates to working dir", "working", tmp)

if err = commitAllAndPush(ctx, repo, access, &auto.Spec.Commit); err != nil {
var rev string
if rev, err = commitAllAndPush(ctx, repo, access, &auto.Spec.Commit); err != nil {
if err == errNoChanges {
log.Info("no changes made in working directory; no commit")
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
log.V(debug).Info("pushed commit to origin", "revision", rev)

return ctrl.Result{}, nil
}
Expand Down Expand Up @@ -203,17 +207,17 @@ func cloneInto(ctx context.Context, access repoAccess, path string) (*gogit.Repo

var errNoChanges = errors.New("no changes in working directory")

func commitAllAndPush(ctx context.Context, repo *gogit.Repository, access repoAccess, commit *imagev1alpha1.CommitSpec) error {
func commitAllAndPush(ctx context.Context, repo *gogit.Repository, access repoAccess, commit *imagev1alpha1.CommitSpec) (string, error) {
working, err := repo.Worktree()
if err != nil {
return err
return "", err
}

status, err := working.Status()
if err != nil {
return err
return "", err
} else if status.IsClean() {
return errNoChanges
return "", errNoChanges
}

msgTmpl := commit.MessageTemplate
Expand All @@ -222,25 +226,26 @@ func commitAllAndPush(ctx context.Context, repo *gogit.Repository, access repoAc
}
tmpl, err := template.New("commit message").Parse(msgTmpl)
if err != nil {
return err
return "", err
}
buf := &strings.Builder{}
if err := tmpl.Execute(buf, "no data! yet"); err != nil {
return err
return "", err
}

if _, err = working.Commit(buf.String(), &gogit.CommitOptions{
var rev plumbing.Hash
if rev, err = working.Commit(buf.String(), &gogit.CommitOptions{
All: true,
Author: &object.Signature{
Name: commit.AuthorName,
Email: commit.AuthorEmail,
When: time.Now(),
},
}); err != nil {
return err
return "", err
}

return repo.PushContext(ctx, &gogit.PushOptions{
return rev.String(), repo.PushContext(ctx, &gogit.PushOptions{
Auth: access.auth,
})
}
Expand Down
32 changes: 28 additions & 4 deletions controllers/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,16 @@ import (
. "github.com/onsi/gomega"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
"sigs.k8s.io/controller-runtime/pkg/envtest/printer"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"

sourcev1alpha1 "github.com/fluxcd/source-controller/api/v1alpha1"
imagev1alpha1 "github.com/squaremo/image-automation-controller/api/v1alpha1"
imagev1alpha1_reflect "github.com/squaremo/image-reflector-controller/api/v1alpha1"
// +kubebuilder:scaffold:imports
)

Expand All @@ -39,6 +42,7 @@ import (

var cfg *rest.Config
var k8sClient client.Client
var k8sManager ctrl.Manager
var testEnv *envtest.Environment

func TestAPIs(t *testing.T) {
Expand All @@ -54,21 +58,41 @@ var _ = BeforeSuite(func(done Done) {

By("bootstrapping test environment")
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
CRDDirectoryPaths: []string{
filepath.Join("..", "config", "crd", "bases"),
filepath.Join("testdata", "crds"),
},
}

var err error
cfg, err = testEnv.Start()
Expect(err).ToNot(HaveOccurred())
Expect(cfg).ToNot(BeNil())

err = imagev1alpha1.AddToScheme(scheme.Scheme)
Expect(err).NotTo(HaveOccurred())
Expect(imagev1alpha1.AddToScheme(scheme.Scheme)).To(Succeed())
Expect(sourcev1alpha1.AddToScheme(scheme.Scheme)).To(Succeed())
Expect(imagev1alpha1_reflect.AddToScheme(scheme.Scheme)).To(Succeed())

// +kubebuilder:scaffold:scheme

k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
k8sManager, err = ctrl.NewManager(cfg, ctrl.Options{
Scheme: scheme.Scheme,
})
Expect(err).ToNot(HaveOccurred())

err = (&ImageUpdateAutomationReconciler{
Client: k8sManager.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("ImageUpdateAutomation"),
Scheme: scheme.Scheme,
}).SetupWithManager(k8sManager)
Expect(err).ToNot(HaveOccurred())

go func() {
err = k8sManager.Start(ctrl.SetupSignalHandler())
Expect(err).ToNot(HaveOccurred())
}()

k8sClient = k8sManager.GetClient()
Expect(k8sClient).ToNot(BeNil())

close(done)
Expand Down
Loading

0 comments on commit 7bdbe7e

Please sign in to comment.