本文整理汇总了Golang中k8s/io/kubernetes/pkg/client/unversioned/testclient.NewSimpleFake函数的典型用法代码示例。如果您正苦于以下问题:Golang NewSimpleFake函数的具体用法?Golang NewSimpleFake怎么用?Golang NewSimpleFake使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewSimpleFake函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestRolling_deployInitial
func TestRolling_deployInitial(t *testing.T) {
initialStrategyInvoked := false
strategy := &RollingDeploymentStrategy{
decoder: kapi.Codecs.UniversalDecoder(),
rcClient: ktestclient.NewSimpleFake(),
eventClient: ktestclient.NewSimpleFake(),
initialStrategy: &testStrategy{
deployFn: func(from *kapi.ReplicationController, to *kapi.ReplicationController, desiredReplicas int, updateAcceptor strat.UpdateAcceptor) error {
initialStrategyInvoked = true
return nil
},
},
rollingUpdate: func(config *kubectl.RollingUpdaterConfig) error {
t.Fatalf("unexpected call to rollingUpdate")
return nil
},
getUpdateAcceptor: getUpdateAcceptor,
apiRetryPeriod: 1 * time.Millisecond,
apiRetryTimeout: 10 * time.Millisecond,
}
config := deploytest.OkDeploymentConfig(1)
config.Spec.Strategy = deploytest.OkRollingStrategy()
deployment, _ := deployutil.MakeDeployment(config, kapi.Codecs.LegacyCodec(registered.GroupOrDie(kapi.GroupName).GroupVersions[0]))
strategy.out, strategy.errOut = &bytes.Buffer{}, &bytes.Buffer{}
err := strategy.Deploy(nil, deployment, 2)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !initialStrategyInvoked {
t.Fatalf("expected initial strategy to be invoked")
}
}
示例2: TestGetServiceDetail
func TestGetServiceDetail(t *testing.T) {
cases := []struct {
service *api.Service
namespace, name string
expectedActions []string
expected *ServiceDetail
}{
{
service: &api.Service{},
namespace: "test-namespace-1", name: "test-name",
expectedActions: []string{"get", "list"},
expected: &ServiceDetail{
TypeMeta: common.TypeMeta{Kind: common.ResourceKindService},
PodList: pod.PodList{Pods: []pod.Pod{}},
},
}, {
service: &api.Service{ObjectMeta: api.ObjectMeta{
Name: "test-service", Namespace: "test-namespace",
}},
namespace: "test-namespace-2", name: "test-name",
expectedActions: []string{"get", "list"},
expected: &ServiceDetail{
ObjectMeta: common.ObjectMeta{
Name: "test-service",
Namespace: "test-namespace",
},
TypeMeta: common.TypeMeta{Kind: common.ResourceKindService},
InternalEndpoint: common.Endpoint{Host: "test-service.test-namespace"},
PodList: pod.PodList{Pods: []pod.Pod{}},
},
},
}
for _, c := range cases {
fakeClient := testclient.NewSimpleFake(c.service)
fakeHeapsterClient := FakeHeapsterClient{client: testclient.NewSimpleFake()}
actual, _ := GetServiceDetail(fakeClient, fakeHeapsterClient, c.namespace, c.name)
actions := fakeClient.Actions()
if len(actions) != len(c.expectedActions) {
t.Errorf("Unexpected actions: %v, expected %d actions got %d", actions,
len(c.expectedActions), len(actions))
continue
}
for i, verb := range c.expectedActions {
if actions[i].GetVerb() != verb {
t.Errorf("Unexpected action: %+v, expected %s",
actions[i], verb)
}
}
if !reflect.DeepEqual(actual, c.expected) {
t.Errorf("GetServiceDetail(client, %#v, %#v) == \ngot %#v, \nexpected %#v", c.namespace,
c.name, actual, c.expected)
}
}
}
示例3: TestGetReplicaSetDetail
func TestGetReplicaSetDetail(t *testing.T) {
eventList := &api.EventList{}
podList := &api.PodList{}
cases := []struct {
namespace, name string
expectedActions []string
replicaSet *extensions.ReplicaSet
expected *ReplicaSetDetail
}{
{
"test-namespace", "test-name",
[]string{"get", "list", "list", "get", "list", "list"},
&extensions.ReplicaSet{
ObjectMeta: api.ObjectMeta{Name: "test-replicaset"},
Spec: extensions.ReplicaSetSpec{
Selector: &unversioned.LabelSelector{
MatchLabels: map[string]string{},
}},
},
&ReplicaSetDetail{
ObjectMeta: common.ObjectMeta{Name: "test-replicaset"},
TypeMeta: common.TypeMeta{Kind: common.ResourceKindReplicaSet},
PodInfo: common.PodInfo{Warnings: []common.Event{}},
PodList: pod.PodList{Pods: []pod.Pod{}},
EventList: common.EventList{Events: []common.Event{}},
},
},
}
for _, c := range cases {
fakeClient := testclient.NewSimpleFake(c.replicaSet, podList, eventList, c.replicaSet,
podList, eventList)
fakeHeapsterClient := FakeHeapsterClient{client: testclient.NewSimpleFake()}
actual, _ := GetReplicaSetDetail(fakeClient, fakeHeapsterClient, c.namespace, c.name)
actions := fakeClient.Actions()
if len(actions) != len(c.expectedActions) {
t.Errorf("Unexpected actions: %v, expected %d actions got %d", actions,
len(c.expectedActions), len(actions))
continue
}
for i, verb := range c.expectedActions {
if actions[i].GetVerb() != verb {
t.Errorf("Unexpected action: %+v, expected %s",
actions[i], verb)
}
}
if !reflect.DeepEqual(actual, c.expected) {
t.Errorf("GetEvents(client,heapsterClient,%#v, %#v) == \ngot: %#v, \nexpected %#v",
c.namespace, c.name, actual, c.expected)
}
}
}
示例4: TestRolling_deployInitialHooks
// TestRolling_deployInitialHooks can go away once the rolling strategy
// supports initial deployments.
func TestRolling_deployInitialHooks(t *testing.T) {
var hookError error
strategy := &RollingDeploymentStrategy{
decoder: kapi.Codecs.UniversalDecoder(),
rcClient: ktestclient.NewSimpleFake(),
eventClient: ktestclient.NewSimpleFake(),
initialStrategy: &testStrategy{
deployFn: func(from *kapi.ReplicationController, to *kapi.ReplicationController, desiredReplicas int, updateAcceptor strat.UpdateAcceptor) error {
return nil
},
},
rollingUpdate: func(config *kubectl.RollingUpdaterConfig) error {
return nil
},
hookExecutor: &hookExecutorImpl{
executeFunc: func(hook *deployapi.LifecycleHook, deployment *kapi.ReplicationController, suffix, label string) error {
return hookError
},
},
getUpdateAcceptor: getUpdateAcceptor,
apiRetryPeriod: 1 * time.Millisecond,
apiRetryTimeout: 10 * time.Millisecond,
}
cases := []struct {
params *deployapi.RollingDeploymentStrategyParams
hookShouldFail bool
deploymentShouldFail bool
}{
{rollingParams(deployapi.LifecycleHookFailurePolicyAbort, ""), true, true},
{rollingParams(deployapi.LifecycleHookFailurePolicyAbort, ""), false, false},
{rollingParams("", deployapi.LifecycleHookFailurePolicyAbort), true, true},
{rollingParams("", deployapi.LifecycleHookFailurePolicyAbort), false, false},
}
for i, tc := range cases {
config := deploytest.OkDeploymentConfig(2)
config.Spec.Strategy.RollingParams = tc.params
deployment, _ := deployutil.MakeDeployment(config, kapi.Codecs.LegacyCodec(registered.GroupOrDie(kapi.GroupName).GroupVersions[0]))
hookError = nil
if tc.hookShouldFail {
hookError = fmt.Errorf("hook failure")
}
strategy.out, strategy.errOut = &bytes.Buffer{}, &bytes.Buffer{}
err := strategy.Deploy(nil, deployment, 2)
if err != nil && tc.deploymentShouldFail {
t.Logf("got expected error: %v", err)
}
if err == nil && tc.deploymentShouldFail {
t.Errorf("%d: expected an error for case: %v", i, tc)
}
if err != nil && !tc.deploymentShouldFail {
t.Errorf("%d: unexpected error for case: %v: %v", i, tc, err)
}
}
}
示例5: TestPlugin
func TestPlugin(t *testing.T) {
var (
testPodUID = types.UID("test_pod_uid")
testVolumeName = "test_volume_name"
testNamespace = "test_secret_namespace"
testName = "test_secret_name"
volumeSpec = volumeSpec(testVolumeName, testName)
secret = secret(testNamespace, testName)
client = testclient.NewSimpleFake(&secret)
pluginMgr = volume.VolumePluginMgr{}
rootDir, host = newTestHost(t, client)
)
pluginMgr.InitPlugins(ProbeVolumePlugins(), host)
plugin, err := pluginMgr.FindPluginByName(secretPluginName)
if err != nil {
t.Errorf("Can't find the plugin by name")
}
pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: testPodUID}}
builder, err := plugin.NewBuilder(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{})
if err != nil {
t.Errorf("Failed to make a new Builder: %v", err)
}
if builder == nil {
t.Errorf("Got a nil Builder")
}
volumePath := builder.GetPath()
if !strings.HasSuffix(volumePath, fmt.Sprintf("pods/test_pod_uid/volumes/kubernetes.io~secret/test_volume_name")) {
t.Errorf("Got unexpected path: %s", volumePath)
}
err = builder.SetUp()
if err != nil {
t.Errorf("Failed to setup volume: %v", err)
}
if _, err := os.Stat(volumePath); err != nil {
if os.IsNotExist(err) {
t.Errorf("SetUp() failed, volume path not created: %s", volumePath)
} else {
t.Errorf("SetUp() failed: %v", err)
}
}
// secret volume should create its own empty wrapper path
podWrapperMetadataDir := fmt.Sprintf("%v/pods/test_pod_uid/plugins/kubernetes.io~empty-dir/wrapped_test_volume_name", rootDir)
if _, err := os.Stat(podWrapperMetadataDir); err != nil {
if os.IsNotExist(err) {
t.Errorf("SetUp() failed, empty-dir wrapper path is not created: %s", podWrapperMetadataDir)
} else {
t.Errorf("SetUp() failed: %v", err)
}
}
doTestSecretDataInVolume(volumePath, secret, t)
doTestCleanAndTeardown(plugin, testPodUID, testVolumeName, volumePath, t)
}
示例6: TestPodWithUID
func TestPodWithUID(t *testing.T) {
client := testclient.NewSimpleFake()
enforcer := NewUidEnforcer(client)
testPod := validPod("test", 2)
userInfo := &user.DefaultInfo{
Name: "test",
UID: "50",
Groups: nil,
}
err := enforcer.Admit(admission.NewAttributesRecord(&testPod, "Pod", "test", "testPod", "pods", "", admission.Update, userInfo))
if err != nil {
t.Errorf("%+v", err)
}
for _, v := range testPod.Spec.Containers {
if v.SecurityContext != nil {
if *v.SecurityContext.RunAsUser != 50 {
t.Errorf("WTF!")
}
} else {
t.Errorf("Uh, no SecurityContext!")
}
}
}
示例7: TestDeploymentPruneNamespaced
func TestDeploymentPruneNamespaced(t *testing.T) {
kFake := ktestclient.NewSimpleFake()
osFake := testclient.NewSimpleFake()
opts := &PruneDeploymentsOptions{
Namespace: "foo",
OSClient: osFake,
KClient: kFake,
Out: ioutil.Discard,
}
if err := opts.Run(); err != nil {
t.Errorf("Unexpected error: %v", err)
}
if len(osFake.Actions()) == 0 || len(kFake.Actions()) == 0 {
t.Errorf("Missing get deployments actions")
}
for _, a := range osFake.Actions() {
if a.GetNamespace() != "foo" {
t.Errorf("Unexpected namespace while pruning %s: %s", a.GetResource(), a.GetNamespace())
}
}
for _, a := range kFake.Actions() {
if a.GetNamespace() != "foo" {
t.Errorf("Unexpected namespace while pruning %s: %s", a.GetResource(), a.GetNamespace())
}
}
}
示例8: TestIncrementUsagePods
func TestIncrementUsagePods(t *testing.T) {
namespace := "default"
client := testclient.NewSimpleFake(&api.PodList{
Items: []api.Pod{
{
ObjectMeta: api.ObjectMeta{Name: "123", Namespace: namespace},
Spec: api.PodSpec{
Volumes: []api.Volume{{Name: "vol"}},
Containers: []api.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements("100m", "1Gi")}},
},
},
},
})
status := &api.ResourceQuotaStatus{
Hard: api.ResourceList{},
Used: api.ResourceList{},
}
r := api.ResourcePods
status.Hard[r] = resource.MustParse("2")
status.Used[r] = resource.MustParse("1")
dirty, err := IncrementUsage(admission.NewAttributesRecord(&api.Pod{}, "Pod", namespace, "name", "pods", "", admission.Create, nil), status, client)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if !dirty {
t.Errorf("Expected the status to get incremented, therefore should have been dirty")
}
quantity := status.Used[r]
if quantity.Value() != int64(2) {
t.Errorf("Expected new item count to be 2, but was %s", quantity.String())
}
}
示例9: TestIncrementUsageReplicationControllers
func TestIncrementUsageReplicationControllers(t *testing.T) {
namespace := "default"
client := testclient.NewSimpleFake(&api.ReplicationControllerList{
Items: []api.ReplicationController{
{
ObjectMeta: api.ObjectMeta{Name: "123", Namespace: namespace},
},
},
})
status := &api.ResourceQuotaStatus{
Hard: api.ResourceList{},
Used: api.ResourceList{},
}
r := api.ResourceReplicationControllers
status.Hard[r] = resource.MustParse("2")
status.Used[r] = resource.MustParse("1")
dirty, err := IncrementUsage(admission.NewAttributesRecord(&api.ReplicationController{}, "ReplicationController", namespace, "name", "replicationcontrollers", "", admission.Create, nil), status, client)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if !dirty {
t.Errorf("Expected the status to get incremented, therefore should have been dirty")
}
quantity := status.Used[r]
if quantity.Value() != int64(2) {
t.Errorf("Expected new item count to be 2, but was %s", quantity.String())
}
}
示例10: TestExceedUsagePods
func TestExceedUsagePods(t *testing.T) {
namespace := "default"
client := testclient.NewSimpleFake(&api.PodList{
Items: []api.Pod{
{
ObjectMeta: api.ObjectMeta{Name: "123", Namespace: namespace},
Spec: api.PodSpec{
Volumes: []api.Volume{{Name: "vol"}},
Containers: []api.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements("100m", "1Gi")}},
},
},
},
})
status := &api.ResourceQuotaStatus{
Hard: api.ResourceList{},
Used: api.ResourceList{},
}
r := api.ResourcePods
status.Hard[r] = resource.MustParse("1")
status.Used[r] = resource.MustParse("1")
_, err := IncrementUsage(admission.NewAttributesRecord(&api.Pod{}, "Pod", namespace, "name", "pods", "", admission.Create, nil), status, client)
if err == nil {
t.Errorf("Expected error because this would exceed your quota")
}
}
示例11: TestUnboundedMemory
func TestUnboundedMemory(t *testing.T) {
namespace := "default"
client := testclient.NewSimpleFake(&api.PodList{
Items: []api.Pod{
{
ObjectMeta: api.ObjectMeta{Name: "123", Namespace: namespace},
Spec: api.PodSpec{
Volumes: []api.Volume{{Name: "vol"}},
Containers: []api.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements("100m", "1Gi")}},
},
},
},
})
status := &api.ResourceQuotaStatus{
Hard: api.ResourceList{},
Used: api.ResourceList{},
}
r := api.ResourceMemory
status.Hard[r] = resource.MustParse("10Gi")
status.Used[r] = resource.MustParse("1Gi")
newPod := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "123", Namespace: namespace},
Spec: api.PodSpec{
Volumes: []api.Volume{{Name: "vol"}},
Containers: []api.Container{{Name: "ctr", Image: "image", Resources: getResourceRequirements("250m", "0")}},
}}
_, err := IncrementUsage(admission.NewAttributesRecord(newPod, "Pod", namespace, "name", "pods", "", admission.Create, nil), status, client)
if err == nil {
t.Errorf("Expected memory unbounded usage error")
}
}
示例12: Repository
func (r *testRegistry) Repository(ctx context.Context, ref reference.Named) (distribution.Repository, error) {
repo, err := r.Namespace.Repository(ctx, ref)
if err != nil {
return nil, err
}
kFakeClient := ktestclient.NewSimpleFake()
parts := strings.SplitN(ref.Name(), "/", 3)
if len(parts) != 2 {
return nil, fmt.Errorf("failed to parse repository name %q", ref.Name())
}
return &repository{
Repository: repo,
ctx: ctx,
quotaClient: kFakeClient,
limitClient: kFakeClient,
registryOSClient: r.osClient,
registryAddr: "localhost:5000",
namespace: parts[0],
name: parts[1],
blobrepositorycachettl: r.blobrepositorycachettl,
cachedLayers: cachedLayers,
pullthrough: r.pullthrough,
}, nil
}
示例13: TestListProjects
func TestListProjects(t *testing.T) {
namespaceList := kapi.NamespaceList{
Items: []kapi.Namespace{
{
ObjectMeta: kapi.ObjectMeta{Name: "foo"},
},
},
}
mockClient := testclient.NewSimpleFake(&namespaceList)
storage := REST{
client: mockClient.Namespaces(),
lister: &mockLister{&namespaceList},
}
user := &user.DefaultInfo{
Name: "test-user",
UID: "test-uid",
Groups: []string{"test-groups"},
}
ctx := kapi.WithUser(kapi.NewContext(), user)
response, err := storage.List(ctx, labels.Everything(), fields.Everything())
if err != nil {
t.Errorf("%#v should be nil.", err)
}
projects := response.(*api.ProjectList)
if len(projects.Items) != 1 {
t.Errorf("%#v projects.Items should have len 1.", projects.Items)
}
responseProject := projects.Items[0]
if e, r := responseProject.Name, "foo"; e != r {
t.Errorf("%#v != %#v.", e, r)
}
}
示例14: TestDoNotDeleteMirrorPods
func TestDoNotDeleteMirrorPods(t *testing.T) {
staticPod := getTestPod()
staticPod.Annotations = map[string]string{kubetypes.ConfigSourceAnnotationKey: "file"}
mirrorPod := getTestPod()
mirrorPod.UID = "mirror-12345678"
mirrorPod.Annotations = map[string]string{
kubetypes.ConfigSourceAnnotationKey: "api",
kubetypes.ConfigMirrorAnnotationKey: "mirror",
}
// Set the deletion timestamp.
mirrorPod.DeletionTimestamp = new(unversioned.Time)
client := testclient.NewSimpleFake(mirrorPod)
m := newTestManager(client)
m.podManager.AddPod(staticPod)
m.podManager.AddPod(mirrorPod)
// Verify setup.
assert.True(t, kubepod.IsStaticPod(staticPod), "SetUp error: staticPod")
assert.True(t, kubepod.IsMirrorPod(mirrorPod), "SetUp error: mirrorPod")
assert.Equal(t, m.podManager.TranslatePodUID(mirrorPod.UID), staticPod.UID)
status := getRandomPodStatus()
now := unversioned.Now()
status.StartTime = &now
m.SetPodStatus(staticPod, status)
m.testSyncBatch()
// Expect not to see an delete action.
verifyActions(t, m.kubeClient, []testclient.Action{
testclient.GetActionImpl{ActionImpl: testclient.ActionImpl{Verb: "get", Resource: "pods"}},
testclient.UpdateActionImpl{ActionImpl: testclient.ActionImpl{Verb: "update", Resource: "pods", Subresource: "status"}},
})
}
示例15: mockREST
// mockREST mocks a DeploymentLog REST
func mockREST(version, desired int, endStatus api.DeploymentStatus) *REST {
// Fake deploymentConfig
config := deploytest.OkDeploymentConfig(version)
fakeDn := testclient.NewSimpleFake(config)
fakeDn.PrependReactor("get", "deploymentconfigs", func(action ktestclient.Action) (handled bool, ret runtime.Object, err error) {
return true, config, nil
})
// Fake deployments
fakeDeployments := makeDeploymentList(version)
fakeRn := ktestclient.NewSimpleFake(fakeDeployments)
fakeRn.PrependReactor("get", "replicationcontrollers", func(action ktestclient.Action) (handled bool, ret runtime.Object, err error) {
return true, &fakeDeployments.Items[desired-1], nil
})
// Fake watcher for deployments
fakeWatch := watch.NewFake()
fakeRn.PrependWatchReactor("replicationcontrollers", ktestclient.DefaultWatchReactor(fakeWatch, nil))
// Everything is fake
connectionInfo := &kclient.HTTPKubeletClient{Config: &kclient.KubeletConfig{EnableHttps: true, Port: 12345}, Client: &http.Client{}}
obj := &fakeDeployments.Items[desired-1]
obj.Annotations[api.DeploymentStatusAnnotation] = string(endStatus)
go fakeWatch.Add(obj)
return &REST{
ConfigGetter: fakeDn,
DeploymentGetter: fakeRn,
PodGetter: &deployerPodGetter{},
ConnectionInfo: connectionInfo,
Timeout: defaultTimeout,
}
}