下面列出了io.fabric8.kubernetes.api.model.EnvVarBuilder#io.fabric8.kubernetes.api.model.PodBuilder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
@DisplayName("Should create pods for with respect to a specified PodSet")
public void testReconcile() throws InterruptedException {
// Given
String testNamespace = "ns1";
PodSet testPodSet = getPodSet("example-podset", testNamespace, "0800cff3-9d80-11ea-8973-0e13a02d8ebd");
server.expect().post().withPath("/api/v1/namespaces/" + testNamespace + "/pods")
.andReturn(HttpURLConnection.HTTP_CREATED, new PodBuilder().withNewMetadata().withName("pod1-clone").endMetadata().build())
.times(testPodSet.getSpec().getReplicas());
KubernetesClient client = server.getClient();
SharedInformerFactory informerFactory = client.informers();
MixedOperation<PodSet, PodSetList, DoneablePodSet, Resource<PodSet, DoneablePodSet>> podSetClient = client.customResources(podSetCustomResourceDefinition, PodSet.class, PodSetList.class, DoneablePodSet.class);
SharedIndexInformer<Pod> podSharedIndexInformer = informerFactory.sharedIndexInformerFor(Pod.class, PodList.class, RESYNC_PERIOD_MILLIS);
SharedIndexInformer<PodSet> podSetSharedIndexInformer = informerFactory.sharedIndexInformerForCustomResource(podSetCustomResourceDefinitionContext, PodSet.class, PodSetList.class, RESYNC_PERIOD_MILLIS);
PodSetController podSetController = new PodSetController(client, podSetClient, podSharedIndexInformer, podSetSharedIndexInformer, testNamespace);
// When
podSetController.reconcile(testPodSet);
// Then
RecordedRequest recordedRequest = server.getLastRequest();
assertEquals("POST", recordedRequest.getMethod());
assertTrue(recordedRequest.getBody().readUtf8().contains(testPodSet.getMetadata().getName()));
}
public Pod newInstance(LanderConfiguration config, List<String> args) {
String truckParkName = podNameFactory.newName(config);
log.info("Creating pod named: {}", truckParkName);
Map<String, String> configMap = configMapSupplier.get().getData();
return new PodBuilder()
.withMetadata(new ObjectMetaBuilder()
.withName(truckParkName)
.withLabels(labels(config.getRoadName(), configMap))
.withAnnotations(annotations(configMap))
.build())
.withSpec(new PodSpecBuilder()
.withRestartPolicy(RESTART_POLICY_NEVER)
.withContainers(container(config.getRoadName(), args, configMap, truckParkName))
.build())
.build();
}
@Test
void testWaitOnConditionDeleted() throws InterruptedException {
Pod ready = new PodBuilder().withNewMetadata()
.withName("pod1")
.withResourceVersion("1")
.withNamespace("test").and().withNewStatus()
.addNewCondition()
.withType("Ready")
.withStatus("True")
.endCondition()
.endStatus()
.build();
server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, ready).once();
server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
.open()
.waitFor(1000).andEmit(new WatchEvent(ready, "DELETED"))
.done()
.once();
KubernetesClient client = server.getClient();
Pod p = client.pods().withName("pod1").waitUntilCondition(Objects::isNull,8, TimeUnit.SECONDS);
assertNull(p);
}
@Test
@DisplayName("Should delete a resource list with PropagationPolicy=Background")
void testDeleteResourceList() throws InterruptedException {
// Given
Pod testPod = new PodBuilder().withNewMetadata().withName("testpod").endMetadata().build();
server.expect().delete().withPath("/api/v1/namespaces/foo/pods/testpod")
.andReturn(HttpURLConnection.HTTP_OK, testPod)
.once();
KubernetesClient client = server.getClient();
// When
Boolean isDeleted = client.resourceList(new KubernetesListBuilder().withItems(testPod).build()).inNamespace("foo").delete();
// Then
assertTrue(isDeleted);
assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.BACKGROUND.toString(), server.getLastRequest());
}
@Test
public void testDelete() {
Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();
Pod pod2 = new PodBuilder().withNewMetadata().withName("pod2").withNamespace("ns1").and().build();
Pod pod3 = new PodBuilder().withNewMetadata().withName("pod3").withNamespace("any").and().build();
server.expect().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, pod1).once();
server.expect().withPath("/api/v1/namespaces/ns1/pods/pod2").andReturn(200, pod2).once();
KubernetesClient client = server.getClient();
Boolean deleted = client.resource(pod1).delete();
assertTrue(deleted);
deleted = client.resource(pod2).delete();
assertTrue(deleted);
deleted = client.resource(pod3).delete();
assertFalse(deleted);
}
@Test
public void shouldPollPodStatusAndEmitEvents() throws Exception {
// Change the pod status to terminated without notifying the runner through the pod watcher
final Pod terminatedPod = new PodBuilder(createdPod)
.withStatus(terminated("Succeeded", 20, null))
.build();
when(k8sClient.getPod(POD_NAME)).thenReturn(Optional.of(terminatedPod));
// Poll for execution status
var stateData = StateData.newBuilder().executionId(POD_NAME).build();
var runState = RunState.create(WORKFLOW_INSTANCE, State.SUBMITTED, stateData);
kdr.poll(runState);
// Verify that the runner found out that the pod is terminated and emits events
verify(stateManager, atLeastOnce()).receive(
Event.started(WORKFLOW_INSTANCE),
-1);
verify(stateManager, atLeastOnce()).receive(
Event.terminate(WORKFLOW_INSTANCE, Optional.of(20)),
0);
}
@Test
public void shouldTolerateCounterCapacityExceptionWhenEmittingEvents() throws Exception {
// Change the pod status to terminated without notifying the runner through the pod watcher
var terminatedPod = new PodBuilder(createdPod)
.withStatus(terminated("Succeeded", 20, null))
.build();
when(k8sClient.getPod(POD_NAME)).thenReturn(Optional.of(terminatedPod));
doThrow(new CounterCapacityException("foo!"))
.when(stateManager).receive(any(), anyLong());
verifyZeroInteractions(stateManager);
// Poll for execution status
var stateData = StateData.newBuilder().executionId(POD_NAME).build();
var runState = RunState.create(WORKFLOW_INSTANCE, State.SUBMITTED, stateData);
kdr.poll(runState);
verify(stateManager).receive(any(), anyLong());
}
@Test
public void testCreateFromLoad() throws Exception {
server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(404, new StatusBuilder().build()).always();
server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
.withNewMetadata().withResourceVersion("12345").and().build()).once();
KubernetesClient client = server.getClient();
Pod pod = client.pods().load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
assertNotNull(pod);
assertEquals("12345", pod.getMetadata().getResourceVersion());
RecordedRequest request = server.getLastRequest();
Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
assertEquals("nginx", requestPod.getMetadata().getName());
}
@Test
public void testResourceCreateFromLoad() throws Exception {
server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(404, new StatusBuilder().build()).always();
server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
.withNewMetadata().withResourceVersion("12345").and().build()).once();
KubernetesClient client = server.getClient();
List<HasMetadata> result = client.load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
assertNotNull(result);
assertEquals(1, result.size());
Pod pod = (Pod) result.get(0);
assertEquals("12345", pod.getMetadata().getResourceVersion());
RecordedRequest request = server.getMockServer().takeRequest();
assertEquals("/api/v1/namespaces/test/pods/nginx", request.getPath());
request = server.getMockServer().takeRequest();
Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
assertEquals("nginx", requestPod.getMetadata().getName());
}
@Test
public void addPodsWhenRecipeContainsThem() throws Exception {
// given
Pod pod =
new PodBuilder()
.withNewMetadata()
.withName("pod")
.endMetadata()
.withSpec(new PodSpec())
.build();
when(k8sRecipeParser.parse(any(InternalRecipe.class))).thenReturn(singletonList(pod));
// when
KubernetesEnvironment osEnv = osEnvFactory.doCreate(internalRecipe, emptyMap(), emptyList());
// then
assertEquals(osEnv.getPodsCopy().size(), 1);
assertEquals(osEnv.getPodsCopy().get("pod"), pod);
assertEquals(osEnv.getPodsData().size(), 1);
assertEquals(osEnv.getPodsData().get("pod").getMetadata(), pod.getMetadata());
assertEquals(osEnv.getPodsData().get("pod").getSpec(), pod.getSpec());
}
@Test
public void testReplaceFromLoad() throws Exception {
server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(200, new PodBuilder().build()).always();
server.expect().put().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(200, new PodBuilder()
.withNewMetadata().withResourceVersion("12345").and().build()).once();
KubernetesClient client = server.getClient();
Pod pod = client.pods().load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
assertNotNull(pod);
assertEquals("12345", pod.getMetadata().getResourceVersion());
RecordedRequest request = server.getLastRequest();
assertEquals("/api/v1/namespaces/test/pods/nginx", request.getPath());
Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
assertEquals("nginx", requestPod.getMetadata().getName());
}
/** Returns new instance of {@link Pod} with given name and command. */
private Pod newPod(String podName, String pvcName, String[] command) {
final Container container =
new ContainerBuilder()
.withName(podName)
.withImage(jobImage)
.withImagePullPolicy(imagePullPolicy)
.withCommand(command)
.withVolumeMounts(newVolumeMount(pvcName, JOB_MOUNT_PATH, null))
.withNewResources()
.endResources()
.build();
Containers.addRamLimit(container, jobMemoryLimit);
Containers.addRamRequest(container, jobMemoryLimit);
return new PodBuilder()
.withNewMetadata()
.withName(podName)
.endMetadata()
.withNewSpec()
.withContainers(container)
.withVolumes(newVolume(pvcName, pvcName))
.withRestartPolicy(POD_RESTART_POLICY)
.endSpec()
.build();
}
@Test
public void testGet() {
server.expect().withPath("/api/v1/nodes/node1").andReturn(200, new PodBuilder().build()).once();
server.expect().withPath("/api/v1/nodes/node2").andReturn(200, new PodBuilder().build()).once();
KubernetesClient client = server.getClient();
Node node = client.nodes().withName("node1").get();
assertNotNull(node);
node = client.nodes().withName("node2").get();
assertNotNull(node);
node = client.nodes().withName("node3").get();
assertNull(node);
}
@Test
public void testDeleteMulti() {
Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();
Pod pod2 = new PodBuilder().withNewMetadata().withName("pod2").withNamespace("ns1").and().build();
Pod pod3 = new PodBuilder().withNewMetadata().withName("pod3").withNamespace("any").and().build();
server.expect().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, pod1).once();
server.expect().withPath("/api/v1/namespaces/ns1/pods/pod2").andReturn(200, pod2).once();
KubernetesClient client = server.getClient();
Boolean deleted = client.pods().inAnyNamespace().delete(pod1, pod2);
assertTrue(deleted);
deleted = client.pods().inAnyNamespace().delete(pod3);
assertFalse(deleted);
}
@Test
public void list() {
Pod listPod1 = new PodBuilder()
.withNewMetadata().withName("pod3").endMetadata()
.withNewSpec()
.addNewContainer().withName("nginx").withImage("nginx").endContainer()
.endSpec()
.build();
client.resourceList(new PodListBuilder().withItems(listPod1).build())
.inNamespace(currentNamespace)
.apply();
assertTrue(client.pods().inNamespace(currentNamespace).withName("pod3") != null);
boolean bDeleted = client.resourceList(new PodListBuilder().withItems(listPod1).build())
.inNamespace(currentNamespace)
.delete();
assertTrue(bDeleted);
}
@BeforeMethod
public void setUp() throws Exception {
Container container = new ContainerBuilder().withName("main").build();
Pod pod =
new PodBuilder()
.withNewMetadata()
.withName("pod")
.endMetadata()
.withNewSpec()
.withContainers(container)
.endSpec()
.build();
kubernetesEnvironment =
KubernetesEnvironment.builder().setPods(ImmutableMap.of("pod", pod)).build();
externalServerExposer =
new ExternalServerExposer<>(
new DefaultHostExternalServiceExposureStrategy(), emptyMap(), "%s");
}
@BeforeMethod
public void setUp() throws Exception {
Container container = new ContainerBuilder().withName("main").build();
Pod pod =
new PodBuilder()
.withNewMetadata()
.withName("pod")
.endMetadata()
.withNewSpec()
.withContainers(container)
.endSpec()
.build();
kubernetesEnvironment =
KubernetesEnvironment.builder().setPods(ImmutableMap.of("pod", pod)).build();
externalServerExposer =
new ExternalServerExposer<>(
new MultiHostExternalServiceExposureStrategy(DOMAIN, MULTI_HOST_STRATEGY),
emptyMap(),
"%s");
}
@Test
public void testDelete() {
Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();
Pod pod2 = new PodBuilder().withNewMetadata().withName("pod2").withNamespace("ns1").and().build();
Pod pod3 = new PodBuilder().withNewMetadata().withName("pod3").withNamespace("any").and().build();
server.expect().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, pod1).times(2);
server.expect().withPath("/api/v1/namespaces/ns1/pods/pod2").andReturn(200, pod2).times(2);
server.expect().withPath("/api/v1/namespaces/any/pods/pod3").andReturn(200, pod3).times(1);
KubernetesClient client = server.getClient();
//First time all items should be deleted.
Boolean deleted = client.resourceList(new PodListBuilder().withItems(pod1, pod2, pod3).build()).delete();
assertTrue(deleted);
//Now we expect pod3 to fail.
deleted = client.resourceList(new PodListBuilder().withItems(pod1, pod2, pod3).build()).delete();
assertFalse(deleted);
}
@Test
public void testResourceReplaceFromLoad() throws Exception {
server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(200, new PodBuilder().withNewMetadata().withResourceVersion("12345").and().build()).always();
server.expect().put().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(200, new PodBuilder()
.withNewMetadata().withResourceVersion("12345").and().build()).once();
KubernetesClient client = server.getClient();
List<HasMetadata> result = client.load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
assertNotNull(result);
assertEquals(1, result.size());
Pod pod = (Pod) result.get(0);
assertEquals("12345", pod.getMetadata().getResourceVersion());
RecordedRequest request = server.getLastRequest();
assertEquals("/api/v1/namespaces/test/pods/nginx", request.getPath());
Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
assertEquals("nginx", requestPod.getMetadata().getName());
}
@Test
void testCacheIndex() {
Pod testPodObj = new PodBuilder().withNewMetadata().withName("test-pod").endMetadata().build();
cache.add(testPodObj);
cache.replace(Arrays.asList(testPodObj), "0");
String index = mockIndexFunction(testPodObj).get(0);
String key = mockKeyFunction(testPodObj);
List indexedObjectList = cache.byIndex("mock", index);
assertEquals(testPodObj, indexedObjectList.get(0));
indexedObjectList = cache.index("mock", testPodObj);
assertEquals(testPodObj, indexedObjectList.get(0));
List<String> allExistingKeys = cache.listKeys();
assertEquals(1, allExistingKeys.size());
assertEquals(key, allExistingKeys.get(0));
}
@Test
@DisplayName("Should delete a resource with specified PropagationPolicy")
void testDeleteResourceWithSpecifiedPropagationPolicy() throws InterruptedException {
// Given
Pod testPod = new PodBuilder().withNewMetadata().withName("testpod").endMetadata().build();
server.expect().delete().withPath("/api/v1/namespaces/foo/pods/testpod")
.andReturn(HttpURLConnection.HTTP_OK, testPod)
.once();
KubernetesClient client = server.getClient();
// When
Boolean isDeleted = client.resource(testPod).inNamespace("foo").withPropagationPolicy(DeletionPropagation.FOREGROUND).delete();
// Then
assertTrue(isDeleted);
assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.FOREGROUND.toString(), server.getLastRequest());
}
private Pod createNewPod(PodSet podSet) {
return new PodBuilder()
.withNewMetadata()
.withGenerateName(podSet.getMetadata().getName() + "-pod")
.withNamespace(podSet.getMetadata().getNamespace())
.withLabels(Collections.singletonMap(APP_LABEL, podSet.getMetadata().getName()))
.addNewOwnerReference().withController(true).withKind("PodSet").withApiVersion("demo.k8s.io/v1alpha1").withName(podSet.getMetadata().getName()).withNewUid(podSet.getMetadata().getUid()).endOwnerReference()
.endMetadata()
.withNewSpec()
.addNewContainer().withName("busybox").withImage("busybox").withCommand("sleep", "3600").endContainer()
.endSpec()
.build();
}
private List<Pod> generateDrainPods(
final Set<String> podNames,
final String clusterName,
final RabbitMQCustomResourceSpec rabbit,
final RabbitMQNetworkPartitionCustomResource networkPartition
) {
final Container container = rabbitMQContainers.buildContainer(
namespace,
clusterName,
rabbit.getRabbitMQImage(),
rabbit.getComputeResources(),
0);
return podNames.stream().map(podName ->
new PodBuilder()
.withNewMetadata()
.withName(podName)
.withNamespace(namespace)
.addToLabels(Labels.Kubernetes.INSTANCE, clusterName)
.addToLabels(Labels.Kubernetes.MANAGED_BY, Labels.Values.RABBITMQ_OPERATOR)
.addToLabels(Labels.Kubernetes.PART_OF, Labels.Values.RABBITMQ)
.addToLabels(Labels.Indeed.LOCKED_BY, "network-partition")
.addToLabels(Labels.Indeed.getIndeedLabels(networkPartition))
.addToOwnerReferences(new OwnerReference(networkPartition.getApiVersion(), false, true, networkPartition.getKind(), networkPartition.getName(), networkPartition.getMetadata().getUid()))
.endMetadata()
.withSpec(rabbitMQPods.buildPodSpec(clusterName, rabbit.getInitContainerImage(), container))
.editSpec()
.withHostname(podName)
.withSubdomain(RabbitMQServices.getDiscoveryServiceName(clusterName))
.addNewVolume().withName(RABBITMQ_STORAGE_NAME).withNewPersistentVolumeClaim().withClaimName(RABBITMQ_STORAGE_NAME + "-" + podName).endPersistentVolumeClaim().endVolume()
.endSpec()
.build()
).collect(Collectors.toList());
}
@Test
public void testProcessTemplatesLocallyNotNull() throws IOException {
//Given
Template template = new TemplateBuilder()
.withNewMetadata().withName("redis-template").endMetadata()
.withObjects(new PodBuilder()
.withNewMetadata().withName("redis-master").endMetadata()
.withNewSpec()
.addNewContainer()
.addNewEnv()
.withName("REDIS_PASSWORD")
.withValue("${REDIS_PASSWORD}")
.endEnv()
.withImage("dockerfile/redis")
.withName("master")
.addNewPort()
.withProtocol("TCP")
.withContainerPort(6379)
.endPort()
.endContainer()
.endSpec()
.build())
.addNewParameter()
.withDescription("Password used for Redis authentication")
.withFrom("[A-Z0-9]{8}")
.withGenerate("expression")
.withName("REDIS_PASSWORD")
.endParameter()
.build();
boolean failOnMissingParameterValue = false;
//When
KubernetesList result = OpenshiftHelper.processTemplatesLocally(template, failOnMissingParameterValue);
//Then
assertEquals(1, result.getItems().size());
assertTrue(result.getItems().get(0) instanceof Pod);
Pod item = (Pod) result.getItems().get(0);
assertEquals("REDIS_PASSWORD", item.getSpec().getContainers().get(0).getEnv().get(0).getName());
assertNotEquals("${REDIS_PASSWORD}", item.getSpec().getContainers().get(0).getEnv().get(0).getValue());
}
@Test
void testResync() {
Pod foo1 = new PodBuilder().withNewMetadata().withName("foo1").withNamespace("default").endMetadata().build();
Cache cache = new Cache();
DeltaFIFO<Pod> deltaFIFO = new DeltaFIFO<>(Cache::deletionHandlingMetaNamespaceKeyFunc, cache);
// sync after addition
cache.add(foo1);
deltaFIFO.resync();
Deque<AbstractMap.SimpleEntry<DeltaFIFO.DeltaType, Object>> deltas = deltaFIFO.getItems().get(Cache.deletionHandlingMetaNamespaceKeyFunc(foo1));
assertEquals(1, deltas.size());
assertEquals(foo1, deltas.peekLast().getValue());
assertEquals(DeltaFIFO.DeltaType.SYNCHRONIZATION, deltas.peekLast().getKey());
}
@Test
public void before() {
Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();
Pod pod2 = new PodBuilder().withNewMetadata().withName("pod2").withNamespace("test").and().build();
mockServer.expect().get().withPath("/api/v1/namespaces/test/pods")
.andReturn(200,
new PodListBuilder().withNewMetadata().withResourceVersion("1").endMetadata().withItems(pod1, pod2)
.build())
.always();
mockServer.expect().get().withPath("/api/v1/namespaces/test/pods/pod1")
.andReturn(200, pod1)
.always();
mockServer.expect().delete().withPath("/api/v1/namespaces/test/pods/pod1")
.andReturn(200, "{}")
.once();
// it doesn't really matter what we return here, we just need to return a Pod to make sure
// deserialization works
mockServer.expect().put().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, new PodBuilder()
.withNewMetadata().withName("pod1").addToLabels("key1", "value1").endMetadata().build()).once();
// same here, the content itself doesn't really matter
mockServer.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
.withNewMetadata().withResourceVersion("54321").and().build()).once();
}
@Test
public void shouldAddAnnotationToResources() {
Pod expectecd = new PodBuilder()
.withNewMetadata()
.withName("pod")
.endMetadata()
.withNewSpec()
.addNewVolume()
.withNewAwsElasticBlockStore()
.endAwsElasticBlockStore()
.endVolume()
.endSpec()
.build();
}
@Test
public void testReplace() throws Exception {
server.expect().get().withPath("/api/v1/namespaces/test/pods/pod123").andReturn(200, new PodBuilder().withNewMetadata().withResourceVersion("12345").and().build()).always();
server.expect().put().withPath("/api/v1/namespaces/test/pods/pod123").andReturn(200, new PodBuilder()
.withNewMetadata().withResourceVersion("12345").and().build()).once();
KubernetesClient client = server.getClient();
Pod pod = client.pods().createOrReplaceWithNew().withNewMetadata().withName("pod123").and().withNewSpec().and().done();
assertNotNull(pod);
assertEquals("12345", pod.getMetadata().getResourceVersion());
}
@Test
public void testList() throws InterruptedException {
server.expect().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, new PodBuilder()
.withNewMetadata()
.withName("testPod")
.endMetadata()
.build()).always();
server.expect().withPath("/api/v1/namespaces/test/pods/pod2").andReturn(200, new PodBuilder()
.withNewMetadata()
.withName("testPod")
.endMetadata()
.build()).always();
NamespacedKubernetesClient client = server.getClient();
Pod pod1 = client.withRequestConfig(new RequestConfigBuilder().withOauthToken("TOKEN").build()).call(c -> c.pods().inNamespace("test").withName("pod1").get());
//Let's check that request config actually works
RecordedRequest request1 = server.getMockServer().takeRequest();
String authHeader1 = request1.getHeader("Authorization");
assertEquals("Bearer TOKEN", authHeader1);
//Let's also check that we didn't pollute client config.
Pod pod2 = client.pods().inNamespace("test").withName("pod2").get();
RecordedRequest request2 = server.getMockServer().takeRequest();
String authHeader2 = request2.getHeader("Authorization");
assertNotEquals("Bearer TOKEN", authHeader2);
}
private List<Pod> stubForRunningPods(int numTasks) {
List<Pod> items = new ArrayList<>();
for (int i = 0; i < numTasks; i++) {
items.add(new PodBuilder().withNewMetadata()
.withName("task-" + i).endMetadata()
.withNewStatus()
.withPhase("Running")
.endStatus().build());
}
return items;
}