github.com/dmvolod/operator-sdk@v0.8.2/doc/user/unit-testing.md (about)

     1  # Unit testing
     2  
     3  Testing your operator should involve both unit and [end-to-end][doc_e2e_test] tests. Unit tests assess the expected outcomes of individual operator components without requiring coordination between components. Operator unit tests should test multiple scenarios likely to be encountered by your custom operator logic at runtime. Much of your custom logic will involve API server calls via a [client][doc_client]; `Reconcile()` in particular will be making API calls on each reconciliation loop. These API calls can be mocked by using `controller-runtime`'s [fake client][doc_cr_fake_client], perfect for unit testing. This document steps through writing a unit test for the [memcached-operator][repo_memcached_reconcile]'s `Reconcile()` method using a fake client.
     4  
     5  ## Fake client
     6  
     7  `controller-runtime`'s fake client exposes the same set of operations as a typical client, but simply tracks objects rather than sending requests over a network. You can create a new fake client that tracks an initial set of objects with the following code:
     8  
     9  ```Go
    10  import (
    11    "testing"
    12  
    13    cachev1alpha1 "github.com/example-inc/memcached-operator/pkg/apis/cache/v1alpha1"
    14  
    15    "k8s.io/apimachinery/pkg/runtime"
    16    "sigs.k8s.io/controller-runtime/pkg/client/fake"
    17  )
    18  
    19  func TestMemcachedController(t *testing.T) {
    20  
    21    // A Memcached object with metadata and spec.
    22    memcached := &cachev1alpha1.Memcached{
    23      ObjectMeta: metav1.ObjectMeta{
    24        Name:      "memcached",
    25        Namespace: "memcached-operator",
    26      },
    27    }
    28    objs := []runtime.Object{memcached}
    29    cl := fake.NewFakeClient(objs...)
    30  
    31    ...
    32  }
    33  
    34  ```
    35  
    36  `cl` will cache `memcached` in an internal object tracker so that CRUD operations via `cl` can be performed on it.
    37  
    38  ## Testing Reconcile
    39  
    40  [`Reconcile()`][doc_reconcile] performs most API server calls a particular operator controller will make. `ReconcileMemcached.Reconcile()` will ensure the `Memcached` resource exists as well as reconcile the state of owned Deployments and Pods. We can test runtime reconciliation scenarios using the above client. The following is an example that tests if `Reconcile()` creates a deployment if one is not found, and whether the created deployment is correct:
    41  
    42  ```Go
    43  import (
    44    "context"
    45    "testing"
    46  
    47    cachev1alpha1 "github.com/example-inc/memcached-operator/pkg/apis/cache/v1alpha1"
    48  
    49    appsv1 "k8s.io/api/apps/v1"
    50    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    51    "k8s.io/apimachinery/pkg/runtime"
    52    "k8s.io/apimachinery/pkg/types"
    53    "k8s.io/client-go/kubernetes/scheme"
    54    "sigs.k8s.io/controller-runtime/pkg/client/fake"
    55    "sigs.k8s.io/controller-runtime/pkg/reconcile"
    56    logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
    57  )
    58  
    59  func TestMemcachedControllerDeploymentCreate(t *testing.T) {
    60    var (
    61      name            = "memcached-operator"
    62      namespace       = "memcached"
    63      replicas  int32 = 3
    64    )
    65  
    66    // A Memcached object with metadata and spec.
    67    memcached := &cachev1alpha1.Memcached{
    68      ObjectMeta: metav1.ObjectMeta{
    69        Name:      name,
    70        Namespace: namespace,
    71      },
    72      Spec: cachev1alpha1.MemcachedSpec{
    73        Size: replicas, // Set desired number of Memcached replicas.
    74      },
    75    }
    76    // Objects to track in the fake client.
    77    objs := []runtime.Object{
    78      memcached,
    79    }
    80  
    81    // Register operator types with the runtime scheme.
    82    s := scheme.Scheme
    83    s.AddKnownTypes(cachev1alpha1.SchemeGroupVersion, memcached)
    84    // Create a fake client to mock API calls.
    85    cl := fake.NewFakeClient(objs...)
    86    // Create a ReconcileMemcached object with the scheme and fake client.
    87    r := &ReconcileMemcached{client: cl, scheme: s}
    88  
    89    // Mock request to simulate Reconcile() being called on an event for a
    90    // watched resource .
    91    req := reconcile.Request{
    92      NamespacedName: types.NamespacedName{
    93        Name:      name,
    94        Namespace: namespace,
    95      },
    96    }
    97    res, err := r.Reconcile(req)
    98    if err != nil {
    99      t.Fatalf("reconcile: (%v)", err)
   100    }
   101    // Check the result of reconciliation to make sure it has the desired state.
   102    if !res.Requeue {
   103      t.Error("reconcile did not requeue request as expected")
   104    }
   105  
   106    // Check if deployment has been created and has the correct size.
   107    dep := &appsv1.Deployment{}
   108    err = cl.Get(context.TODO(), req.NamespacedName, dep)
   109    if err != nil {
   110      t.Fatalf("get deployment: (%v)", err)
   111    }
   112    dsize := *dep.Spec.Replicas
   113    if dsize != replicas {
   114      t.Errorf("dep size (%d) is not the expected size (%d)", dsize, replicas)
   115    }
   116  }
   117  ```
   118  
   119  The above tests if:
   120  - `Reconcile()` fails to find a Deployment object.
   121  - A Deployment is created.
   122  - The request is requeued in the expected manner.
   123  - The number of replicas in the created Deployment's spec is as expected.
   124  
   125  A unit test checking more cases can be found in our [`samples repo`][code_test_example].
   126  
   127  [doc_e2e_test]:https://github.com/operator-framework/operator-sdk/blob/2f772d1dc2340dd19bdc3ec8c2dc9f0f77cc8297/doc/test-framework/writing-e2e-tests.md
   128  [doc_client]:https://github.com/operator-framework/operator-sdk/blob/5c50126e7a112d67826894997eca143e12dc165f/doc/user/client.md
   129  [doc_cr_fake_client]:https://godoc.org/github.com/kubernetes-sigs/controller-runtime/pkg/client/fake
   130  [repo_memcached_reconcile]:https://github.com/operator-framework/operator-sdk-samples/blob/4c6934448684a6953ece4d3d9f3f77494b1c125e/memcached-operator/pkg/controller/memcached/memcached_controller.go#L82
   131  [doc_reconcile]:https://godoc.org/sigs.k8s.io/controller-runtime/pkg/reconcile#Reconciler
   132  [code_test_example]: https://github.com/operator-framework/operator-sdk-samples/blob/master/memcached-operator/pkg/controller/memcached/memcached_controller_test.go#L25