Using assertions

Using assertions for unit tests:

1. cmd/kube-controller-manager/app/controller_manager_test.go
2. pkg/controller/bootstrap/jws_test.go
3. pkg/controller/cloud/node_controller_test.go
4. pkg/controller/controller_utils_test.go
pull/6/head
Chen Li 2017-09-20 00:24:07 -05:00
parent 1797255cd2
commit fb9b29dbb1
7 changed files with 166 additions and 221 deletions

View File

@ -151,5 +151,8 @@ go_test(
name = "go_default_test", name = "go_default_test",
srcs = ["controller_manager_test.go"], srcs = ["controller_manager_test.go"],
library = ":go_default_library", library = ":go_default_library",
deps = ["//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library"], deps = [
"//vendor/github.com/stretchr/testify/assert:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library",
],
) )

View File

@ -24,6 +24,8 @@ import (
"testing" "testing"
"k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/sets"
"github.com/stretchr/testify/assert"
) )
func TestIsControllerEnabled(t *testing.T) { func TestIsControllerEnabled(t *testing.T) {
@ -73,9 +75,7 @@ func TestIsControllerEnabled(t *testing.T) {
for _, tc := range tcs { for _, tc := range tcs {
actual := IsControllerEnabled(tc.controllerName, sets.NewString(tc.disabledByDefaultControllers...), tc.controllers...) actual := IsControllerEnabled(tc.controllerName, sets.NewString(tc.disabledByDefaultControllers...), tc.controllers...)
if actual != tc.expected { assert.Equal(t, tc.expected, actual, "%v: expected %v, got %v", tc.name, tc.expected, actual)
t.Errorf("%v: expected %v, got %v", tc.name, tc.expected, actual)
}
} }
} }

View File

@ -19,6 +19,7 @@ go_test(
"//pkg/api/testapi:go_default_library", "//pkg/api/testapi:go_default_library",
"//pkg/controller/testutil:go_default_library", "//pkg/controller/testutil:go_default_library",
"//pkg/securitycontext:go_default_library", "//pkg/securitycontext:go_default_library",
"//vendor/github.com/stretchr/testify/assert:go_default_library",
"//vendor/k8s.io/api/core/v1:go_default_library", "//vendor/k8s.io/api/core/v1:go_default_library",
"//vendor/k8s.io/api/extensions/v1beta1:go_default_library", "//vendor/k8s.io/api/extensions/v1beta1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/equality:go_default_library", "//vendor/k8s.io/apimachinery/pkg/api/equality:go_default_library",

View File

@ -16,7 +16,11 @@ limitations under the License.
package bootstrap package bootstrap
import "testing" import (
"testing"
"github.com/stretchr/testify/assert"
)
const ( const (
content = "Hello from the other side. I must have called a thousand times." content = "Hello from the other side. I must have called a thousand times."
@ -26,42 +30,40 @@ const (
func TestComputeDetachedSig(t *testing.T) { func TestComputeDetachedSig(t *testing.T) {
sig, err := computeDetachedSig(content, id, secret) sig, err := computeDetachedSig(content, id, secret)
if err != nil { assert.NoError(t, err, "Error when computing signature: %v", err)
t.Errorf("Error when computing signature: %v", err) assert.Equal(
} t,
if sig != "eyJhbGciOiJIUzI1NiIsImtpZCI6Impvc2h1YSJ9..VShe2taLd-YTrmWuRkcL_8QTNDHYxQIEBsAYYiIj1_8" { "eyJhbGciOiJIUzI1NiIsImtpZCI6Impvc2h1YSJ9..VShe2taLd-YTrmWuRkcL_8QTNDHYxQIEBsAYYiIj1_8",
t.Errorf("Wrong signature. Got: %v", sig) sig,
} "Wrong signature. Got: %v", sig)
// Try with null content // Try with null content
sig, err = computeDetachedSig("", id, secret) sig, err = computeDetachedSig("", id, secret)
if err != nil { assert.NoError(t, err, "Error when computing signature: %v", err)
t.Errorf("Error when computing signature: %v", err) assert.Equal(
} t,
if sig != "eyJhbGciOiJIUzI1NiIsImtpZCI6Impvc2h1YSJ9..7Ui1ALizW4jXphVUB7xUqC9vLYLL9RZeOFfVLoB7Tgk" { "eyJhbGciOiJIUzI1NiIsImtpZCI6Impvc2h1YSJ9..7Ui1ALizW4jXphVUB7xUqC9vLYLL9RZeOFfVLoB7Tgk",
t.Errorf("Wrong signature. Got: %v", sig) sig,
} "Wrong signature. Got: %v", sig)
// Try with no secret // Try with no secret
sig, err = computeDetachedSig(content, id, "") sig, err = computeDetachedSig(content, id, "")
if err != nil { assert.NoError(t, err, "Error when computing signature: %v", err)
t.Errorf("Error when computing signature: %v", err) assert.Equal(
} t,
if sig != "eyJhbGciOiJIUzI1NiIsImtpZCI6Impvc2h1YSJ9..UfkqvDGiIFxrMnFseDj9LYJOLNrvjW8aHhF71mvvAs8" { "eyJhbGciOiJIUzI1NiIsImtpZCI6Impvc2h1YSJ9..UfkqvDGiIFxrMnFseDj9LYJOLNrvjW8aHhF71mvvAs8",
t.Errorf("Wrong signature. Got: %v", sig) sig,
} "Wrong signature. Got: %v", sig)
} }
func TestDetachedTokenIsValid(t *testing.T) { func TestDetachedTokenIsValid(t *testing.T) {
// Valid detached JWS token and valid inputs should succeed // Valid detached JWS token and valid inputs should succeed
sig := "eyJhbGciOiJIUzI1NiIsImtpZCI6Impvc2h1YSJ9..VShe2taLd-YTrmWuRkcL_8QTNDHYxQIEBsAYYiIj1_8" sig := "eyJhbGciOiJIUzI1NiIsImtpZCI6Impvc2h1YSJ9..VShe2taLd-YTrmWuRkcL_8QTNDHYxQIEBsAYYiIj1_8"
if !DetachedTokenIsValid(sig, content, id, secret) { assert.True(t, DetachedTokenIsValid(sig, content, id, secret),
t.Errorf("Content %q and token \"%s:%s\" should equal signature: %q", content, id, secret, sig) "Content %q and token \"%s:%s\" should equal signature: %q", content, id, secret, sig)
}
// Invalid detached JWS token and valid inputs should fail // Invalid detached JWS token and valid inputs should fail
sig2 := sig + "foo" sig2 := sig + "foo"
if DetachedTokenIsValid(sig2, content, id, secret) { assert.False(t, DetachedTokenIsValid(sig2, content, id, secret),
t.Errorf("Content %q and token \"%s:%s\" should not equal signature: %q", content, id, secret, sig) "Content %q and token \"%s:%s\" should not equal signature: %q", content, id, secret, sig)
}
} }

View File

@ -56,6 +56,7 @@ go_test(
"//pkg/kubelet/apis:go_default_library", "//pkg/kubelet/apis:go_default_library",
"//plugin/pkg/scheduler/algorithm:go_default_library", "//plugin/pkg/scheduler/algorithm:go_default_library",
"//vendor/github.com/golang/glog:go_default_library", "//vendor/github.com/golang/glog:go_default_library",
"//vendor/github.com/stretchr/testify/assert:go_default_library",
"//vendor/k8s.io/api/core/v1:go_default_library", "//vendor/k8s.io/api/core/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",

View File

@ -18,12 +18,9 @@ package cloud
import ( import (
"errors" "errors"
"reflect"
"testing" "testing"
"time" "time"
"github.com/golang/glog"
"k8s.io/api/core/v1" "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes/fake" "k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/kubernetes/scheme"
@ -39,6 +36,9 @@ import (
"k8s.io/kubernetes/pkg/controller/testutil" "k8s.io/kubernetes/pkg/controller/testutil"
kubeletapis "k8s.io/kubernetes/pkg/kubelet/apis" kubeletapis "k8s.io/kubernetes/pkg/kubelet/apis"
"k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm"
"github.com/golang/glog"
"github.com/stretchr/testify/assert"
) )
func TestEnsureNodeExistsByProviderIDOrNodeName(t *testing.T) { func TestEnsureNodeExistsByProviderIDOrNodeName(t *testing.T) {
@ -129,26 +129,20 @@ func TestEnsureNodeExistsByProviderIDOrNodeName(t *testing.T) {
instances, _ := fc.Instances() instances, _ := fc.Instances()
exists, err := ensureNodeExistsByProviderIDOrExternalID(instances, tc.node) exists, err := ensureNodeExistsByProviderIDOrExternalID(instances, tc.node)
if err != nil { assert.NoError(t, err)
t.Error(err) assert.EqualValues(t, tc.expectedCalls, fc.Calls,
} "expected cloud provider methods `%v` to be called but `%v` was called ",
tc.expectedCalls, fc.Calls)
if !reflect.DeepEqual(fc.Calls, tc.expectedCalls) { assert.False(t, tc.existsByProviderID && tc.existsByProviderID != exists,
t.Errorf("expected cloud provider methods `%v` to be called but `%v` was called ", tc.expectedCalls, fc.Calls) "expected exist by provider id to be `%t` but got `%t`",
} tc.existsByProviderID, exists)
if tc.existsByProviderID && tc.existsByProviderID != exists { assert.False(t, tc.existsByNodeName && tc.existsByNodeName != exists,
t.Errorf("expected exist by provider id to be `%t` but got `%t`", tc.existsByProviderID, exists) "expected exist by node name to be `%t` but got `%t`", tc.existsByNodeName, exists)
}
if tc.existsByNodeName && tc.existsByNodeName != exists {
t.Errorf("expected exist by node name to be `%t` but got `%t`", tc.existsByNodeName, exists)
}
if !tc.existsByNodeName && !tc.existsByProviderID && exists {
t.Error("node is not supposed to exist")
}
assert.False(t, !tc.existsByNodeName && !tc.existsByProviderID && exists,
"node is not supposed to exist")
}) })
} }
@ -239,9 +233,9 @@ func TestNodeDeleted(t *testing.T) {
case <-time.After(wait.ForeverTestTimeout): case <-time.After(wait.ForeverTestTimeout):
t.Errorf("Timed out waiting %v for node to be deleted", wait.ForeverTestTimeout) t.Errorf("Timed out waiting %v for node to be deleted", wait.ForeverTestTimeout)
} }
if len(fnh.DeletedNodes) != 1 || fnh.DeletedNodes[0].Name != "node0" {
t.Errorf("Node was not deleted") assert.Equal(t, 1, len(fnh.DeletedNodes), "Node was not deleted")
} assert.Equal(t, "node0", fnh.DeletedNodes[0].Name, "Node was not deleted")
} }
// This test checks that a node with the external cloud provider taint is cloudprovider initialized // This test checks that a node with the external cloud provider taint is cloudprovider initialized
@ -314,14 +308,9 @@ func TestNodeInitialized(t *testing.T) {
cloudNodeController.AddCloudNode(fnh.Existing[0]) cloudNodeController.AddCloudNode(fnh.Existing[0])
if len(fnh.UpdatedNodes) != 1 || fnh.UpdatedNodes[0].Name != "node0" { assert.Equal(t, 1, len(fnh.UpdatedNodes), "Node was not updated")
t.Errorf("Node was not updated") assert.Equal(t, "node0", fnh.UpdatedNodes[0].Name, "Node was not updated")
} assert.Equal(t, 0, len(fnh.UpdatedNodes[0].Spec.Taints), "Node Taint was not removed after cloud init")
if len(fnh.UpdatedNodes[0].Spec.Taints) != 0 {
t.Errorf("Node Taint was not removed after cloud init")
}
} }
// This test checks that a node without the external cloud provider taint are NOT cloudprovider initialized // This test checks that a node without the external cloud provider taint are NOT cloudprovider initialized
@ -383,10 +372,7 @@ func TestNodeIgnored(t *testing.T) {
eventBroadcaster.StartLogging(glog.Infof) eventBroadcaster.StartLogging(glog.Infof)
cloudNodeController.AddCloudNode(fnh.Existing[0]) cloudNodeController.AddCloudNode(fnh.Existing[0])
assert.Equal(t, 0, len(fnh.UpdatedNodes), "Node was wrongly updated")
if len(fnh.UpdatedNodes) != 0 {
t.Errorf("Node was wrongly updated")
}
} }
@ -461,13 +447,9 @@ func TestGCECondition(t *testing.T) {
cloudNodeController.AddCloudNode(fnh.Existing[0]) cloudNodeController.AddCloudNode(fnh.Existing[0])
if len(fnh.UpdatedNodes) != 1 && fnh.UpdatedNodes[0].Name != "node0" { assert.Equal(t, 1, len(fnh.UpdatedNodes), "Node was not updated")
t.Errorf("Node was not updated") assert.Equal(t, "node0", fnh.UpdatedNodes[0].Name, "Node was not updated")
} assert.Equal(t, 2, len(fnh.UpdatedNodes[0].Status.Conditions), "No new conditions were added for GCE")
if len(fnh.UpdatedNodes[0].Status.Conditions) != 2 {
t.Errorf("No new conditions were added for GCE")
}
conditionAdded := false conditionAdded := false
for _, cond := range fnh.UpdatedNodes[0].Status.Conditions { for _, cond := range fnh.UpdatedNodes[0].Status.Conditions {
@ -476,9 +458,7 @@ func TestGCECondition(t *testing.T) {
} }
} }
if !conditionAdded { assert.True(t, conditionAdded, "Network Route Condition for GCE not added by external cloud intializer")
t.Errorf("Network Route Condition for GCE not added by external cloud intializer")
}
} }
// This test checks that a node with the external cloud provider taint is cloudprovider initialized and // This test checks that a node with the external cloud provider taint is cloudprovider initialized and
@ -557,21 +537,14 @@ func TestZoneInitialized(t *testing.T) {
cloudNodeController.AddCloudNode(fnh.Existing[0]) cloudNodeController.AddCloudNode(fnh.Existing[0])
if len(fnh.UpdatedNodes) != 1 && fnh.UpdatedNodes[0].Name != "node0" { assert.Equal(t, 1, len(fnh.UpdatedNodes), "Node was not updated")
t.Errorf("Node was not updated") assert.Equal(t, "node0", fnh.UpdatedNodes[0].Name, "Node was not updated")
} assert.Equal(t, 2, len(fnh.UpdatedNodes[0].ObjectMeta.Labels),
"Node label for Region and Zone were not set")
if len(fnh.UpdatedNodes[0].ObjectMeta.Labels) != 2 { assert.Equal(t, "us-west", fnh.UpdatedNodes[0].ObjectMeta.Labels[kubeletapis.LabelZoneRegion],
t.Errorf("Node label for Region and Zone were not set") "Node Region not correctly updated")
} assert.Equal(t, "us-west-1a", fnh.UpdatedNodes[0].ObjectMeta.Labels[kubeletapis.LabelZoneFailureDomain],
"Node FailureDomain not correctly updated")
if fnh.UpdatedNodes[0].ObjectMeta.Labels[kubeletapis.LabelZoneRegion] != "us-west" {
t.Errorf("Node Region not correctly updated")
}
if fnh.UpdatedNodes[0].ObjectMeta.Labels[kubeletapis.LabelZoneFailureDomain] != "us-west-1a" {
t.Errorf("Node FailureDomain not correctly updated")
}
} }
// This test checks that a node with the external cloud provider taint is cloudprovider initialized and // This test checks that a node with the external cloud provider taint is cloudprovider initialized and
@ -655,13 +628,9 @@ func TestNodeAddresses(t *testing.T) {
cloudNodeController.AddCloudNode(fnh.Existing[0]) cloudNodeController.AddCloudNode(fnh.Existing[0])
if len(fnh.UpdatedNodes) != 1 && fnh.UpdatedNodes[0].Name != "node0" { assert.Equal(t, 1, len(fnh.UpdatedNodes), "Node was not updated")
t.Errorf("Node was not updated") assert.Equal(t, "node0", fnh.UpdatedNodes[0].Name, "Node was not updated")
} assert.Equal(t, 3, len(fnh.UpdatedNodes[0].Status.Addresses), "Node status not updated")
if len(fnh.UpdatedNodes[0].Status.Addresses) != 3 {
t.Errorf("Node status not updated")
}
fakeCloud.Addresses = []v1.NodeAddress{ fakeCloud.Addresses = []v1.NodeAddress{
{ {
@ -680,9 +649,8 @@ func TestNodeAddresses(t *testing.T) {
updatedNodes := fnh.GetUpdatedNodesCopy() updatedNodes := fnh.GetUpdatedNodesCopy()
if len(updatedNodes[0].Status.Addresses) != 2 { assert.Equal(t, 2, len(updatedNodes[0].Status.Addresses), "Node Addresses not correctly updated")
t.Errorf("Node Addresses not correctly updated")
}
} }
// This test checks that a node with the external cloud provider taint is cloudprovider initialized and // This test checks that a node with the external cloud provider taint is cloudprovider initialized and
@ -775,13 +743,9 @@ func TestNodeProvidedIPAddresses(t *testing.T) {
cloudNodeController.AddCloudNode(fnh.Existing[0]) cloudNodeController.AddCloudNode(fnh.Existing[0])
if len(fnh.UpdatedNodes) != 1 && fnh.UpdatedNodes[0].Name != "node0" { assert.Equal(t, 1, len(fnh.UpdatedNodes), "Node was not updated")
t.Errorf("Node was not updated") assert.Equal(t, "node0", fnh.UpdatedNodes[0].Name, "Node was not updated")
} assert.Equal(t, 1, len(fnh.UpdatedNodes[0].Status.Addresses), "Node status unexpectedly updated")
if len(fnh.UpdatedNodes[0].Status.Addresses) != 1 {
t.Errorf("Node status unexpectedly updated")
}
cloudNodeController.Run() cloudNodeController.Run()
@ -789,9 +753,8 @@ func TestNodeProvidedIPAddresses(t *testing.T) {
updatedNodes := fnh.GetUpdatedNodesCopy() updatedNodes := fnh.GetUpdatedNodesCopy()
if len(updatedNodes[0].Status.Addresses) != 1 || updatedNodes[0].Status.Addresses[0].Address != "10.0.0.1" { assert.Equal(t, 1, len(updatedNodes[0].Status.Addresses), 1, "Node Addresses not correctly updated")
t.Errorf("Node Addresses not correctly updated") assert.Equal(t, "10.0.0.1", updatedNodes[0].Status.Addresses[0].Address, "Node Addresses not correctly updated")
}
} }
// Tests that node address changes are detected correctly // Tests that node address changes are detected correctly
@ -816,9 +779,9 @@ func TestNodeAddressesChangeDetected(t *testing.T) {
Address: "132.143.154.163", Address: "132.143.154.163",
}, },
} }
if nodeAddressesChangeDetected(addressSet1, addressSet2) {
t.Errorf("Node address changes are not detected correctly") assert.False(t, nodeAddressesChangeDetected(addressSet1, addressSet2),
} "Node address changes are not detected correctly")
addressSet1 = []v1.NodeAddress{ addressSet1 = []v1.NodeAddress{
{ {
@ -840,9 +803,9 @@ func TestNodeAddressesChangeDetected(t *testing.T) {
Address: "132.143.154.163", Address: "132.143.154.163",
}, },
} }
if !nodeAddressesChangeDetected(addressSet1, addressSet2) {
t.Errorf("Node address changes are not detected correctly") assert.True(t, nodeAddressesChangeDetected(addressSet1, addressSet2),
} "Node address changes are not detected correctly")
addressSet1 = []v1.NodeAddress{ addressSet1 = []v1.NodeAddress{
{ {
@ -868,9 +831,9 @@ func TestNodeAddressesChangeDetected(t *testing.T) {
Address: "132.143.154.164", Address: "132.143.154.164",
}, },
} }
if !nodeAddressesChangeDetected(addressSet1, addressSet2) {
t.Errorf("Node address changes are not detected correctly") assert.True(t, nodeAddressesChangeDetected(addressSet1, addressSet2),
} "Node address changes are not detected correctly")
addressSet1 = []v1.NodeAddress{ addressSet1 = []v1.NodeAddress{
{ {
@ -896,9 +859,9 @@ func TestNodeAddressesChangeDetected(t *testing.T) {
Address: "hostname.zone.region.aws.test", Address: "hostname.zone.region.aws.test",
}, },
} }
if !nodeAddressesChangeDetected(addressSet1, addressSet2) {
t.Errorf("Node address changes are not detected correctly") assert.True(t, nodeAddressesChangeDetected(addressSet1, addressSet2),
} "Node address changes are not detected correctly")
addressSet1 = []v1.NodeAddress{ addressSet1 = []v1.NodeAddress{
{ {
@ -920,9 +883,9 @@ func TestNodeAddressesChangeDetected(t *testing.T) {
Address: "132.143.154.163", Address: "132.143.154.163",
}, },
} }
if !nodeAddressesChangeDetected(addressSet1, addressSet2) {
t.Errorf("Node address changes are not detected correctly") assert.True(t, nodeAddressesChangeDetected(addressSet1, addressSet2),
} "Node address changes are not detected correctly")
} }
// This test checks that a node is set with the correct providerID // This test checks that a node is set with the correct providerID
@ -1003,13 +966,9 @@ func TestNodeProviderID(t *testing.T) {
cloudNodeController.AddCloudNode(fnh.Existing[0]) cloudNodeController.AddCloudNode(fnh.Existing[0])
if len(fnh.UpdatedNodes) != 1 || fnh.UpdatedNodes[0].Name != "node0" { assert.Equal(t, 1, len(fnh.UpdatedNodes), "Node was not updated")
t.Errorf("Node was not updated") assert.Equal(t, "node0", fnh.UpdatedNodes[0].Name, "Node was not updated")
} assert.Equal(t, "test://12345", fnh.UpdatedNodes[0].Spec.ProviderID, "Node ProviderID not set correctly")
if fnh.UpdatedNodes[0].Spec.ProviderID != "test://12345" {
t.Errorf("Node ProviderID not set correctly")
}
} }
// This test checks that a node's provider ID will not be overwritten // This test checks that a node's provider ID will not be overwritten
@ -1091,12 +1050,8 @@ func TestNodeProviderIDAlreadySet(t *testing.T) {
cloudNodeController.AddCloudNode(fnh.Existing[0]) cloudNodeController.AddCloudNode(fnh.Existing[0])
if len(fnh.UpdatedNodes) != 1 || fnh.UpdatedNodes[0].Name != "node0" { assert.Equal(t, 1, len(fnh.UpdatedNodes), "Node was not updated")
t.Errorf("Node was not updated") assert.Equal(t, "node0", fnh.UpdatedNodes[0].Name, "Node was not updated")
}
// CCM node controller should not overwrite provider if it's already set // CCM node controller should not overwrite provider if it's already set
if fnh.UpdatedNodes[0].Spec.ProviderID != "test-provider-id" { assert.Equal(t, "test-provider-id", fnh.UpdatedNodes[0].Spec.ProviderID, "Node ProviderID not set correctly")
t.Errorf("Node ProviderID not set correctly")
}
} }

View File

@ -22,7 +22,6 @@ import (
"math" "math"
"math/rand" "math/rand"
"net/http/httptest" "net/http/httptest"
"reflect"
"sort" "sort"
"sync" "sync"
"testing" "testing"
@ -47,6 +46,8 @@ import (
"k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/api/testapi"
"k8s.io/kubernetes/pkg/controller/testutil" "k8s.io/kubernetes/pkg/controller/testutil"
"k8s.io/kubernetes/pkg/securitycontext" "k8s.io/kubernetes/pkg/securitycontext"
"github.com/stretchr/testify/assert"
) )
// NewFakeControllerExpectationsLookup creates a fake store for PodExpectations. // NewFakeControllerExpectationsLookup creates a fake store for PodExpectations.
@ -171,9 +172,8 @@ func TestControllerExpectations(t *testing.T) {
// RC fires off adds and deletes at apiserver, then sets expectations // RC fires off adds and deletes at apiserver, then sets expectations
rcKey, err := KeyFunc(rc) rcKey, err := KeyFunc(rc)
if err != nil { assert.NoError(t, err, "Couldn't get key for object %#v: %v", rc, err)
t.Errorf("Couldn't get key for object %#v: %v", rc, err)
}
e.SetExpectations(rcKey, adds, dels) e.SetExpectations(rcKey, adds, dels)
var wg sync.WaitGroup var wg sync.WaitGroup
for i := 0; i < adds+1; i++ { for i := 0; i < adds+1; i++ {
@ -188,9 +188,8 @@ func TestControllerExpectations(t *testing.T) {
wg.Wait() wg.Wait()
// There are still delete expectations // There are still delete expectations
if e.SatisfiedExpectations(rcKey) { assert.False(t, e.SatisfiedExpectations(rcKey), "Rc will sync before expectations are met")
t.Errorf("Rc will sync before expectations are met")
}
for i := 0; i < dels+1; i++ { for i := 0; i < dels+1; i++ {
wg.Add(1) wg.Add(1)
go func() { go func() {
@ -201,34 +200,29 @@ func TestControllerExpectations(t *testing.T) {
wg.Wait() wg.Wait()
// Expectations have been surpassed // Expectations have been surpassed
if podExp, exists, err := e.GetExpectations(rcKey); err == nil && exists { podExp, exists, err := e.GetExpectations(rcKey)
assert.NoError(t, err, "Could not get expectations for rc, exists %v and err %v", exists, err)
assert.True(t, exists, "Could not get expectations for rc, exists %v and err %v", exists, err)
add, del := podExp.GetExpectations() add, del := podExp.GetExpectations()
if add != -1 || del != -1 { assert.Equal(t, int64(-1), add, "Unexpected pod expectations %#v", podExp)
t.Errorf("Unexpected pod expectations %#v", podExp) assert.Equal(t, int64(-1), del, "Unexpected pod expectations %#v", podExp)
} assert.True(t, e.SatisfiedExpectations(rcKey), "Expectations are met but the rc will not sync")
} else {
t.Errorf("Could not get expectations for rc, exists %v and err %v", exists, err)
}
if !e.SatisfiedExpectations(rcKey) {
t.Errorf("Expectations are met but the rc will not sync")
}
// Next round of rc sync, old expectations are cleared // Next round of rc sync, old expectations are cleared
e.SetExpectations(rcKey, 1, 2) e.SetExpectations(rcKey, 1, 2)
if podExp, exists, err := e.GetExpectations(rcKey); err == nil && exists { podExp, exists, err = e.GetExpectations(rcKey)
add, del := podExp.GetExpectations() assert.NoError(t, err, "Could not get expectations for rc, exists %v and err %v", exists, err)
if add != 1 || del != 2 { assert.True(t, exists, "Could not get expectations for rc, exists %v and err %v", exists, err)
t.Errorf("Unexpected pod expectations %#v", podExp) add, del = podExp.GetExpectations()
}
} else { assert.Equal(t, int64(1), add, "Unexpected pod expectations %#v", podExp)
t.Errorf("Could not get expectations for rc, exists %v and err %v", exists, err) assert.Equal(t, int64(2), del, "Unexpected pod expectations %#v", podExp)
}
// Expectations have expired because of ttl // Expectations have expired because of ttl
fakeClock.Step(ttl + 1) fakeClock.Step(ttl + 1)
if !e.SatisfiedExpectations(rcKey) { assert.True(t, e.SatisfiedExpectations(rcKey),
t.Errorf("Expectations should have expired but didn't") "Expectations should have expired but didn't")
}
} }
func TestUIDExpectations(t *testing.T) { func TestUIDExpectations(t *testing.T) {
@ -266,19 +260,20 @@ func TestUIDExpectations(t *testing.T) {
rcKeys[i], rcKeys[j] = rcKeys[j], rcKeys[i] rcKeys[i], rcKeys[j] = rcKeys[j], rcKeys[i]
} }
for _, rcKey := range rcKeys { for _, rcKey := range rcKeys {
if uidExp.SatisfiedExpectations(rcKey) { assert.False(t, uidExp.SatisfiedExpectations(rcKey),
t.Errorf("Controller %v satisfied expectations before deletion", rcKey) "Controller %v satisfied expectations before deletion", rcKey)
}
for _, p := range rcToPods[rcKey] { for _, p := range rcToPods[rcKey] {
uidExp.DeletionObserved(rcKey, p) uidExp.DeletionObserved(rcKey, p)
} }
if !uidExp.SatisfiedExpectations(rcKey) {
t.Errorf("Controller %v didn't satisfy expectations after deletion", rcKey) assert.True(t, uidExp.SatisfiedExpectations(rcKey),
} "Controller %v didn't satisfy expectations after deletion", rcKey)
uidExp.DeleteExpectations(rcKey) uidExp.DeleteExpectations(rcKey)
if uidExp.GetUIDs(rcKey) != nil {
t.Errorf("Failed to delete uid expectations for %v", rcKey) assert.Nil(t, uidExp.GetUIDs(rcKey),
} "Failed to delete uid expectations for %v", rcKey)
} }
} }
@ -301,9 +296,8 @@ func TestCreatePods(t *testing.T) {
controllerSpec := newReplicationController(1) controllerSpec := newReplicationController(1)
// Make sure createReplica sends a POST to the apiserver with a pod from the controllers pod template // Make sure createReplica sends a POST to the apiserver with a pod from the controllers pod template
if err := podControl.CreatePods(ns, controllerSpec.Spec.Template, controllerSpec); err != nil { err := podControl.CreatePods(ns, controllerSpec.Spec.Template, controllerSpec)
t.Fatalf("unexpected error: %v", err) assert.NoError(t, err, "unexpected error: %v", err)
}
expectedPod := v1.Pod{ expectedPod := v1.Pod{
ObjectMeta: metav1.ObjectMeta{ ObjectMeta: metav1.ObjectMeta{
@ -314,14 +308,10 @@ func TestCreatePods(t *testing.T) {
} }
fakeHandler.ValidateRequest(t, testapi.Default.ResourcePath("pods", metav1.NamespaceDefault, ""), "POST", nil) fakeHandler.ValidateRequest(t, testapi.Default.ResourcePath("pods", metav1.NamespaceDefault, ""), "POST", nil)
var actualPod = &v1.Pod{} var actualPod = &v1.Pod{}
err := json.Unmarshal([]byte(fakeHandler.RequestBody), actualPod) err = json.Unmarshal([]byte(fakeHandler.RequestBody), actualPod)
if err != nil { assert.NoError(t, err, "unexpected error: %v", err)
t.Fatalf("Unexpected error: %v", err) assert.True(t, apiequality.Semantic.DeepDerivative(&expectedPod, actualPod),
} "Body: %s", fakeHandler.RequestBody)
if !apiequality.Semantic.DeepDerivative(&expectedPod, actualPod) {
t.Logf("Body: %s", fakeHandler.RequestBody)
t.Errorf("Unexpected mismatch. Expected\n %#v,\n Got:\n %#v", &expectedPod, actualPod)
}
} }
func TestActivePodFiltering(t *testing.T) { func TestActivePodFiltering(t *testing.T) {
@ -344,9 +334,11 @@ func TestActivePodFiltering(t *testing.T) {
for _, pod := range got { for _, pod := range got {
gotNames.Insert(pod.Name) gotNames.Insert(pod.Name)
} }
if expectedNames.Difference(gotNames).Len() != 0 || gotNames.Difference(expectedNames).Len() != 0 {
t.Errorf("expected %v, got %v", expectedNames.List(), gotNames.List()) assert.Equal(t, 0, expectedNames.Difference(gotNames).Len(),
} "expected %v, got %v", expectedNames.List(), gotNames.List())
assert.Equal(t, 0, gotNames.Difference(expectedNames).Len(),
"expected %v, got %v", expectedNames.List(), gotNames.List())
} }
func TestSortingActivePods(t *testing.T) { func TestSortingActivePods(t *testing.T) {
@ -420,9 +412,7 @@ func TestSortingActivePods(t *testing.T) {
sort.Sort(ActivePods(randomizedPods)) sort.Sort(ActivePods(randomizedPods))
actual := getOrder(randomizedPods) actual := getOrder(randomizedPods)
if !reflect.DeepEqual(actual, expected) { assert.EqualValues(t, expected, actual, "expected %v, got %v", expected, actual)
t.Errorf("expected %v, got %v", expected, actual)
}
} }
} }
@ -443,9 +433,10 @@ func TestActiveReplicaSetsFiltering(t *testing.T) {
gotNames.Insert(rs.Name) gotNames.Insert(rs.Name)
} }
if expectedNames.Difference(gotNames).Len() != 0 || gotNames.Difference(expectedNames).Len() != 0 { assert.Equal(t, 0, expectedNames.Difference(gotNames).Len(),
t.Errorf("expected %v, got %v", expectedNames.List(), gotNames.List()) "expected %v, got %v", expectedNames.List(), gotNames.List())
} assert.Equal(t, 0, gotNames.Difference(expectedNames).Len(),
"expected %v, got %v", expectedNames.List(), gotNames.List())
} }
func int64P(num int64) *int64 { func int64P(num int64) *int64 {
@ -480,9 +471,7 @@ func TestComputeHash(t *testing.T) {
hash := ComputeHash(test.template, test.collisionCount) hash := ComputeHash(test.template, test.collisionCount)
otherHash := ComputeHash(test.template, test.otherCollisionCount) otherHash := ComputeHash(test.template, test.otherCollisionCount)
if hash == otherHash { assert.NotEqual(t, hash, otherHash, "expected different hashes but got the same: %d", hash)
t.Errorf("expected different hashes but got the same: %d", hash)
}
} }
} }
@ -646,22 +635,19 @@ func TestRemoveTaintOffNode(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
node, _ := test.nodeHandler.Get(test.nodeName, metav1.GetOptions{}) node, _ := test.nodeHandler.Get(test.nodeName, metav1.GetOptions{})
if err := RemoveTaintOffNode(test.nodeHandler, test.nodeName, node, test.taintsToRemove...); err != nil { err := RemoveTaintOffNode(test.nodeHandler, test.nodeName, node, test.taintsToRemove...)
t.Errorf("%s: RemoveTaintOffNode() error = %v", test.name, err) assert.NoError(t, err, "%s: RemoveTaintOffNode() error = %v", test.name, err)
}
node, _ = test.nodeHandler.Get(test.nodeName, metav1.GetOptions{}) node, _ = test.nodeHandler.Get(test.nodeName, metav1.GetOptions{})
if !reflect.DeepEqual(node.Spec.Taints, test.expectedTaints) { assert.EqualValues(t, test.expectedTaints, node.Spec.Taints,
t.Errorf("%s: failed to remove taint off node: expected %+v, got %+v", "%s: failed to remove taint off node: expected %+v, got %+v",
test.name, test.expectedTaints, node.Spec.Taints) test.name, test.expectedTaints, node.Spec.Taints)
}
if test.nodeHandler.RequestCount != test.requestCount { assert.Equal(t, test.requestCount, test.nodeHandler.RequestCount,
t.Errorf("%s: unexpected request count: expected %+v, got %+v", "%s: unexpected request count: expected %+v, got %+v",
test.name, test.requestCount, test.nodeHandler.RequestCount) test.name, test.requestCount, test.nodeHandler.RequestCount)
} }
} }
}
func TestAddOrUpdateTaintOnNode(t *testing.T) { func TestAddOrUpdateTaintOnNode(t *testing.T) {
tests := []struct { tests := []struct {
@ -824,19 +810,16 @@ func TestAddOrUpdateTaintOnNode(t *testing.T) {
}, },
} }
for _, test := range tests { for _, test := range tests {
if err := AddOrUpdateTaintOnNode(test.nodeHandler, test.nodeName, test.taintsToAdd...); err != nil { err := AddOrUpdateTaintOnNode(test.nodeHandler, test.nodeName, test.taintsToAdd...)
t.Errorf("%s: AddOrUpdateTaintOnNode() error = %v", test.name, err) assert.NoError(t, err, "%s: AddOrUpdateTaintOnNode() error = %v", test.name, err)
}
node, _ := test.nodeHandler.Get(test.nodeName, metav1.GetOptions{}) node, _ := test.nodeHandler.Get(test.nodeName, metav1.GetOptions{})
if !reflect.DeepEqual(node.Spec.Taints, test.expectedTaints) { assert.EqualValues(t, test.expectedTaints, node.Spec.Taints,
t.Errorf("%s: failed to add taint to node: expected %+v, got %+v", "%s: failed to add taint to node: expected %+v, got %+v",
test.name, test.expectedTaints, node.Spec.Taints) test.name, test.expectedTaints, node.Spec.Taints)
}
if test.nodeHandler.RequestCount != test.requestCount { assert.Equal(t, test.requestCount, test.nodeHandler.RequestCount,
t.Errorf("%s: unexpected request count: expected %+v, got %+v", "%s: unexpected request count: expected %+v, got %+v",
test.name, test.requestCount, test.nodeHandler.RequestCount) test.name, test.requestCount, test.nodeHandler.RequestCount)
} }
} }
}