EnvTest Setup

Overview

This document describes how to configure the environment for the controller tests which uses envtest and is supported by the SDK.

Installing prerequisites

Envtest requires that kubectl, api-server and etcd be present locally. You can use this script to download these binaries into the testbin/ directory. It may be convenient to add this script your Makefile as follows:

  1. # Setup binaries required to run the tests
  2. # See that it expects the Kubernetes and ETCD version
  3. K8S_VERSION = v1.18.2
  4. ETCD_VERSION = v3.4.3
  5. testbin:
  6. curl -sSLo setup_envtest.sh https://raw.githubusercontent.com/kubernetes-sigs/kubebuilder/master/scripts/setup_envtest_bins.sh
  7. chmod +x setup_envtest.sh
  8. ./setup_envtest.sh $(K8S_VERSION) $(ETCD_VERSION)

The above script sets these environment variables to specify where test binaries can be found. In case you would like to not use the script then, is possible to do the same configuration to inform the path of your binaries:

  1. $ export TEST_ASSET_KUBECTL=<kubectl-bin-path>
  2. $ export TEST_ASSET_KUBE_APISERVER=<api-server-bin-path>
  3. $ export TEST_ASSET_ETCD=<etcd-bin-path>

See that the environment variables also can be specified via your controllers/suite_test.go such as the following example.

  1. var _ = BeforeSuite(func(done Done) {
  2. Expect(os.Setenv("TEST_ASSET_KUBE_APISERVER", "../../testbin/kube-apiserver")).To(Succeed())
  3. Expect(os.Setenv("TEST_ASSET_ETCD", "../../testbin/etcd")).To(Succeed())
  4. Expect(os.Setenv("TEST_ASSET_KUBECTL", "../../testbin/kubectl")).To(Succeed())
  5. logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
  6. testenv = &envtest.Environment{}
  7. var err error
  8. cfg, err = testenv.Start()
  9. Expect(err).NotTo(HaveOccurred())
  10. close(done)
  11. }, 60)
  12. var _ = AfterSuite(func() {
  13. Expect(testenv.Stop()).To(Succeed())
  14. Expect(os.Unsetenv("TEST_ASSET_KUBE_APISERVER")).To(Succeed())
  15. Expect(os.Unsetenv("TEST_ASSET_ETCD")).To(Succeed())
  16. Expect(os.Unsetenv("TEST_ASSET_KUBECTL")).To(Succeed())
  17. })

Last modified July 27, 2020: doc: add envtest setup info (#3517) (ef73f4ee)