本文整理汇总了Golang中k8s/io/kubernetes/pkg/client/clientset_generated/internalclientset/fake.NewSimpleClientset函数的典型用法代码示例。如果您正苦于以下问题:Golang NewSimpleClientset函数的具体用法?Golang NewSimpleClientset怎么用?Golang NewSimpleClientset使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewSimpleClientset函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestRolling_deployInitial
func TestRolling_deployInitial(t *testing.T) {
initialStrategyInvoked := false
strategy := &RollingDeploymentStrategy{
decoder: kapi.Codecs.UniversalDecoder(),
rcClient: fake.NewSimpleClientset().Core(),
eventClient: fake.NewSimpleClientset().Core(),
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: TestIsValidSecret
func TestIsValidSecret(t *testing.T) {
fk := testclient.NewSimpleClientset(&api.Secret{
ObjectMeta: api.ObjectMeta{
Namespace: api.NamespaceDefault,
Name: "demo",
},
})
_, err := IsValidSecret(fk, "")
if err == nil {
t.Errorf("expected error but retuned nil")
}
s, err := IsValidSecret(fk, "default/demo")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if s == nil {
t.Errorf("expected a Secret but retuned nil")
}
fk = testclient.NewSimpleClientset()
s, err = IsValidSecret(fk, "default/demo")
if err == nil {
t.Errorf("expected an error but retuned nil")
}
if s != nil {
t.Errorf("unexpected Secret returned: %v", s)
}
}
示例3: TestAdmitImageStreamMapping
func TestAdmitImageStreamMapping(t *testing.T) {
tests := map[string]struct {
imageStreamMapping *imageapi.ImageStreamMapping
limitRange *kapi.LimitRange
shouldAdmit bool
operation kadmission.Operation
}{
"new ism, no limit range": {
imageStreamMapping: getImageStreamMapping(),
operation: kadmission.Create,
shouldAdmit: true,
},
"new ism, under limit range": {
imageStreamMapping: getImageStreamMapping(),
limitRange: getLimitRange("1Ki"),
operation: kadmission.Create,
shouldAdmit: true,
},
"new ism, over limit range": {
imageStreamMapping: getImageStreamMapping(),
limitRange: getLimitRange("0Ki"),
operation: kadmission.Create,
shouldAdmit: false,
},
}
for k, v := range tests {
var fakeKubeClient clientset.Interface
if v.limitRange != nil {
fakeKubeClient = clientsetfake.NewSimpleClientset(v.limitRange)
} else {
fakeKubeClient = clientsetfake.NewSimpleClientset()
}
plugin, err := NewImageLimitRangerPlugin(fakeKubeClient, nil)
if err != nil {
t.Errorf("%s failed creating plugin %v", k, err)
continue
}
attrs := kadmission.NewAttributesRecord(v.imageStreamMapping,
imageapi.Kind("ImageStreamMapping").WithVersion("version"),
v.imageStreamMapping.Namespace,
v.imageStreamMapping.Name,
imageapi.Resource("imagestreammappings").WithVersion("version"),
"",
v.operation,
nil)
err = plugin.Admit(attrs)
if v.shouldAdmit && err != nil {
t.Errorf("%s expected to be admitted but received error %v", k, err)
}
if !v.shouldAdmit && err == nil {
t.Errorf("%s expected to be rejected but received no error", k)
}
}
}
示例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: fake.NewSimpleClientset().Core(),
eventClient: fake.NewSimpleClientset().Core(),
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: fakeMasterConfig
// fakeMasterConfig creates a new fake master config with an empty kubelet config and dummy storage.
func fakeMasterConfig() *MasterConfig {
kubeInformerFactory := informers.NewSharedInformerFactory(fake.NewSimpleClientset(), 1*time.Second)
informerFactory := shared.NewInformerFactory(kubeInformerFactory, fake.NewSimpleClientset(), testclient.NewSimpleFake(), shared.DefaultListerWatcherOverrides{}, 1*time.Second)
return &MasterConfig{
KubeletClientConfig: &kubeletclient.KubeletClientConfig{},
RESTOptionsGetter: restoptions.NewSimpleGetter(&storagebackend.Config{ServerList: []string{"localhost"}}),
Informers: informerFactory,
ClusterQuotaMappingController: clusterquotamapping.NewClusterQuotaMappingController(kubeInformerFactory.Namespaces(), informerFactory.ClusterResourceQuotas()),
PrivilegedLoopbackKubernetesClientset: &kclientset.Clientset{},
}
}
示例6: TestPersistentClaimReadOnlyFlag
func TestPersistentClaimReadOnlyFlag(t *testing.T) {
tmpDir, err := utiltesting.MkTmpdir("glusterfs_test")
if err != nil {
t.Fatalf("error creating temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
pv := &api.PersistentVolume{
ObjectMeta: api.ObjectMeta{
Name: "pvA",
},
Spec: api.PersistentVolumeSpec{
PersistentVolumeSource: api.PersistentVolumeSource{
Glusterfs: &api.GlusterfsVolumeSource{EndpointsName: "ep", Path: "vol", ReadOnly: false},
},
ClaimRef: &api.ObjectReference{
Name: "claimA",
},
},
}
claim := &api.PersistentVolumeClaim{
ObjectMeta: api.ObjectMeta{
Name: "claimA",
Namespace: "nsA",
},
Spec: api.PersistentVolumeClaimSpec{
VolumeName: "pvA",
},
Status: api.PersistentVolumeClaimStatus{
Phase: api.ClaimBound,
},
}
ep := &api.Endpoints{
ObjectMeta: api.ObjectMeta{
Namespace: "nsA",
Name: "ep",
},
Subsets: []api.EndpointSubset{{
Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}},
Ports: []api.EndpointPort{{Name: "foo", Port: 80, Protocol: api.ProtocolTCP}},
}},
}
client := fake.NewSimpleClientset(pv, claim, ep)
plugMgr := volume.VolumePluginMgr{}
plugMgr.InitPlugins(ProbeVolumePlugins(), volumetest.NewFakeVolumeHost(tmpDir, client, nil))
plug, _ := plugMgr.FindPluginByName(glusterfsPluginName)
// readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes
spec := volume.NewSpecFromPersistentVolume(pv, true)
pod := &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: "nsA", UID: types.UID("poduid")}}
mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{})
if !mounter.GetAttributes().ReadOnly {
t.Errorf("Expected true for mounter.IsReadOnly")
}
}
示例7: 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 := fake.NewSimpleClientset(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, []core.Action{
core.GetActionImpl{ActionImpl: core.ActionImpl{Verb: "get", Resource: "pods"}},
core.UpdateActionImpl{ActionImpl: core.ActionImpl{Verb: "update", Resource: "pods", Subresource: "status"}},
})
}
示例8: TestRecreate_initialDeployment
func TestRecreate_initialDeployment(t *testing.T) {
var deployment *kapi.ReplicationController
scaler := &cmdtest.FakeScaler{}
strategy := &RecreateDeploymentStrategy{
out: &bytes.Buffer{},
errOut: &bytes.Buffer{},
decoder: kapi.Codecs.UniversalDecoder(),
retryTimeout: 1 * time.Second,
retryPeriod: 1 * time.Millisecond,
getUpdateAcceptor: getUpdateAcceptor,
scaler: scaler,
eventClient: fake.NewSimpleClientset().Core(),
}
config := deploytest.OkDeploymentConfig(1)
config.Spec.Strategy = recreateParams(30, "", "", "")
deployment, _ = deployutil.MakeDeployment(config, kapi.Codecs.LegacyCodec(registered.GroupOrDie(kapi.GroupName).GroupVersions[0]))
strategy.rcClient = &fakeControllerClient{deployment: deployment}
err := strategy.Deploy(nil, deployment, 3)
if err != nil {
t.Fatalf("unexpected deploy error: %#v", err)
}
if e, a := 1, len(scaler.Events); e != a {
t.Fatalf("expected %d scale calls, got %d", e, a)
}
if e, a := uint(3), scaler.Events[0].Size; e != a {
t.Errorf("expected scale up to %d, got %d", e, a)
}
}
示例9: TestLimitRangerCacheAndLRUExpiredMisses
func TestLimitRangerCacheAndLRUExpiredMisses(t *testing.T) {
liveLookupCache, err := lru.New(10000)
if err != nil {
t.Fatal(err)
}
limitRange := validLimitRangeNoDefaults()
client := fake.NewSimpleClientset(&limitRange)
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc})
handler := &limitRanger{
Handler: admission.NewHandler(admission.Create, admission.Update),
client: client,
actions: &DefaultLimitRangerActions{},
indexer: indexer,
liveLookupCache: liveLookupCache,
}
testPod := validPod("testPod", 1, api.ResourceRequirements{})
// add to the lru cache
liveLookupCache.Add(limitRange.Namespace, liveLookupEntry{expiry: time.Now().Add(time.Duration(-30 * time.Second)), items: []*api.LimitRange{}})
err = handler.Admit(admission.NewAttributesRecord(&testPod, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Update, nil))
if err == nil {
t.Errorf("Expected an error since the pod did not specify resource limits in its update call")
}
err = handler.Admit(admission.NewAttributesRecord(&testPod, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "status", admission.Update, nil))
if err != nil {
t.Errorf("Should have ignored calls to any subresource of pod %v", err)
}
}
示例10: TestCasting
func TestCasting(t *testing.T) {
clientset := fake.NewSimpleClientset()
binder := NewPersistentVolumeClaimBinder(clientset, 1*time.Second)
pv := &api.PersistentVolume{}
unk := cache.DeletedFinalStateUnknown{}
pvc := &api.PersistentVolumeClaim{
ObjectMeta: api.ObjectMeta{Name: "foo"},
Status: api.PersistentVolumeClaimStatus{Phase: api.ClaimBound},
}
// Inject mockClient into the binder. This prevents weird errors on stderr
// as the binder wants to load PV/PVC from API server.
mockClient := &mockBinderClient{
volume: pv,
claim: pvc,
}
binder.client = mockClient
// none of these should fail casting.
// the real test is not failing when passed DeletedFinalStateUnknown in the deleteHandler
binder.addVolume(pv)
binder.updateVolume(pv, pv)
binder.deleteVolume(pv)
binder.deleteVolume(unk)
binder.addClaim(pvc)
binder.updateClaim(pvc, pvc)
}
示例11: TestRepairEmpty
func TestRepairEmpty(t *testing.T) {
_, cidr, _ := net.ParseCIDR("192.168.1.0/24")
previous := ipallocator.NewCIDRRange(cidr)
previous.Allocate(net.ParseIP("192.168.1.10"))
var dst api.RangeAllocation
err := previous.Snapshot(&dst)
if err != nil {
t.Fatal(err)
}
fakeClient := fake.NewSimpleClientset()
ipregistry := &mockRangeRegistry{
item: &api.RangeAllocation{
ObjectMeta: api.ObjectMeta{
ResourceVersion: "1",
},
Range: dst.Range,
Data: dst.Data,
},
}
r := NewRepair(0, fakeClient.Core(), cidr, ipregistry)
if err := r.RunOnce(); err != nil {
t.Fatal(err)
}
after := ipallocator.NewCIDRRange(cidr)
if err := after.Restore(cidr, ipregistry.updated.Data); err != nil {
t.Fatal(err)
}
if after.Has(net.ParseIP("192.168.1.10")) {
t.Errorf("unexpected ipallocator state: %#v", after)
}
}
示例12: TestAdmitExceedQuotaLimit
// TestAdmitExceedQuotaLimit verifies that if a pod exceeded allowed usage that its rejected during admission.
func TestAdmitExceedQuotaLimit(t *testing.T) {
resourceQuota := &api.ResourceQuota{
ObjectMeta: api.ObjectMeta{Name: "quota", Namespace: "test", ResourceVersion: "124"},
Status: api.ResourceQuotaStatus{
Hard: api.ResourceList{
api.ResourceCPU: resource.MustParse("3"),
api.ResourceMemory: resource.MustParse("100Gi"),
api.ResourcePods: resource.MustParse("5"),
},
Used: api.ResourceList{
api.ResourceCPU: resource.MustParse("1"),
api.ResourceMemory: resource.MustParse("50Gi"),
api.ResourcePods: resource.MustParse("3"),
},
},
}
kubeClient := fake.NewSimpleClientset(resourceQuota)
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc})
evaluator, _ := newQuotaEvaluator(kubeClient, install.NewRegistry(kubeClient))
evaluator.indexer = indexer
evaluator.Run(5)
handler := "aAdmission{
Handler: admission.NewHandler(admission.Create, admission.Update),
evaluator: evaluator,
}
indexer.Add(resourceQuota)
newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", "")))
err := handler.Admit(admission.NewAttributesRecord(newPod, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, nil))
if err == nil {
t.Errorf("Expected an error exceeding quota")
}
}
示例13: TestDeployAppContainerCommands
func TestDeployAppContainerCommands(t *testing.T) {
command := "foo-command"
commandArgs := "foo-command-args"
spec := &AppDeploymentSpec{
Namespace: "foo-namespace",
Name: "foo-name",
ContainerCommand: &command,
ContainerCommandArgs: &commandArgs,
}
testClient := fake.NewSimpleClientset()
DeployApp(spec, testClient)
createAction := testClient.Actions()[0].(core.CreateActionImpl)
rc := createAction.GetObject().(*extensions.Deployment)
container := rc.Spec.Template.Spec.Containers[0]
if container.Command[0] != command {
t.Errorf("Expected command to be %#v but got %#v",
command, container.Command)
}
if container.Args[0] != commandArgs {
t.Errorf("Expected command args to be %#v but got %#v",
commandArgs, container.Args)
}
}
示例14: TestDeployWithResourceRequirements
func TestDeployWithResourceRequirements(t *testing.T) {
cpuRequirement := resource.Quantity{}
memoryRequirement := resource.Quantity{}
spec := &AppDeploymentSpec{
Namespace: "foo-namespace",
Name: "foo-name",
CpuRequirement: &cpuRequirement,
MemoryRequirement: &memoryRequirement,
}
expectedResources := api.ResourceRequirements{
Requests: map[api.ResourceName]resource.Quantity{
api.ResourceMemory: memoryRequirement,
api.ResourceCPU: cpuRequirement,
},
}
testClient := fake.NewSimpleClientset()
DeployApp(spec, testClient)
createAction := testClient.Actions()[0].(core.CreateActionImpl)
rc := createAction.GetObject().(*extensions.Deployment)
container := rc.Spec.Template.Spec.Containers[0]
if !reflect.DeepEqual(container.Resources, expectedResources) {
t.Errorf("Expected resource requirements to be %#v but got %#v",
expectedResources, container.Resources)
}
}
示例15: testPSPAdmit
func testPSPAdmit(testCaseName string, psps []*extensions.PodSecurityPolicy, pod *kapi.Pod, shouldPass bool, expectedPSP string, t *testing.T) {
namespace := createNamespaceForTest()
serviceAccount := createSAForTest()
tc := clientsetfake.NewSimpleClientset(namespace, serviceAccount)
store := cache.NewStore(cache.MetaNamespaceKeyFunc)
for _, psp := range psps {
store.Add(psp)
}
plugin := NewTestAdmission(store, tc)
attrs := kadmission.NewAttributesRecord(pod, nil, kapi.Kind("Pod").WithVersion("version"), "namespace", "", kapi.Resource("pods").WithVersion("version"), "", kadmission.Create, &user.DefaultInfo{})
err := plugin.Admit(attrs)
if shouldPass && err != nil {
t.Errorf("%s expected no errors but received %v", testCaseName, err)
}
if shouldPass && err == nil {
if pod.Annotations[psputil.ValidatedPSPAnnotation] != expectedPSP {
t.Errorf("%s expected to validate under %s but found %s", testCaseName, expectedPSP, pod.Annotations[psputil.ValidatedPSPAnnotation])
}
}
if !shouldPass && err == nil {
t.Errorf("%s expected errors but received none", testCaseName)
}
}