下面列出了org.junit.rules.TestName#io.fabric8.kubernetes.client.KubernetesClient 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testUpdateStatusThrowsWhenHttp422ResponseWithOtherField(VertxTestContext context) throws IOException {
KubernetesClient mockClient = mock(KubernetesClient.class);
OkHttpClient mockOkHttp = mock(OkHttpClient.class);
when(mockClient.adapt(eq(OkHttpClient.class))).thenReturn(mockOkHttp);
URL fakeUrl = new URL("http", "my-host", 9443, "/");
when(mockClient.getMasterUrl()).thenReturn(fakeUrl);
Call mockCall = mock(Call.class);
when(mockOkHttp.newCall(any(Request.class))).thenReturn(mockCall);
ResponseBody body = ResponseBody.create(OperationSupport.JSON, "{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{},\"status\":\"Failure\",\"message\":\"Kafka." + Constants.RESOURCE_GROUP_NAME + " \\\"my-cluster\\\" is invalid: apiVersion: Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"reason\":\"Invalid\",\"details\":{\"name\":\"my-cluster\",\"group\":\"" + Constants.RESOURCE_GROUP_NAME + "\",\"kind\":\"Kafka\",\"causes\":[{\"reason\":\"FieldValueInvalid\",\"message\":\"Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"field\":\"someOtherField\"}]},\"code\":422}");
Response response = new Response.Builder().code(422).request(new Request.Builder().url(fakeUrl).build()).body(body).message("Unprocessable Entity").protocol(Protocol.HTTP_1_1).build();
when(mockCall.execute()).thenReturn(response);
Checkpoint async = context.checkpoint();
createResourceOperations(vertx, mockClient)
.updateStatusAsync(resource())
.onComplete(context.failing(e -> context.verify(() -> {
assertThat(e, instanceOf(KubernetesClientException.class));
async.flag();
})));
}
@Test
@DisplayName("Should delete a resource with PropagationPolicy=Background")
void testDeleteResource() 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").delete();
// Then
assertTrue(isDeleted);
assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.BACKGROUND.toString(), server.getLastRequest());
}
@Test
public void testDelete() {
server.expect().withPath("/apis/policy/v1beta1/namespaces/test/poddisruptionbudgets/poddisruptionbudget1").andReturn(200, new PodDisruptionBudgetBuilder()
.withNewMetadata().withName("poddisruptionbudget1").withNamespace("test").endMetadata()
.withNewSpec()
.withMaxUnavailable(new IntOrString("1%"))
.withNewSelector()
.withMatchLabels(Collections.singletonMap("app", "zookeeper"))
.endSelector()
.endSpec()
.build()).once();
KubernetesClient client = server.getClient();
Boolean deleted = client.policy().podDisruptionBudget().withName("poddisruptionbudget1").delete();
assertNotNull(deleted);
assertTrue(deleted);
}
protected AbstractWatcher(boolean isCrd, String namespace, String entityName, KubernetesClient client,
CustomResourceDefinition crd, Map<String, String> selector, BiConsumer<T, String> onAdd,
BiConsumer<T, String> onDelete, BiConsumer<T, String> onModify, Predicate<ConfigMap> isSupported,
Function<ConfigMap, T> convert, Function<InfoClass, T> convertCr) {
this.isCrd = isCrd;
this.namespace = namespace;
this.entityName = entityName;
this.client = client;
this.crd = crd;
this.selector = selector;
this.onAdd = onAdd;
this.onDelete = onDelete;
this.onModify = onModify;
this.isSupported = isSupported;
this.convert = convert;
this.convertCr = convertCr;
}
/**
* {@inheritDoc}
*/
@Override
public <C extends Namespaceable<C> & KubernetesClient> void create(
C client, LeaderElectionRecord leaderElectionRecord) throws LockException {
try {
client.inNamespace(leaseNamespace).leases().withName(leaseName).createNew()
.withNewMetadata().withNamespace(leaseNamespace).withName(leaseName).endMetadata()
.withNewSpec()
.withHolderIdentity(leaderElectionRecord.getHolderIdentity())
.withLeaseDurationSeconds((int)leaderElectionRecord.getLeaseDuration().get(ChronoUnit.SECONDS))
.withAcquireTime(leaderElectionRecord.getAcquireTime())
.withRenewTime(leaderElectionRecord.getRenewTime())
.withLeaseTransitions(leaderElectionRecord.getLeaderTransitions())
.endSpec()
.done();
} catch (Exception e) {
throw new LockException("Unable to create LeaseLock", e);
}
}
@Test
public void deserializationTest() {
Map<String, KubernetesDeployerProperties> k8sAccounts = this.kubernetesPlatformProperties.getAccounts();
KubernetesClient devK8sClient = KubernetesClientFactory.getKubernetesClient(k8sAccounts.get("dev"));
KubernetesClient qaK8sClient = KubernetesClientFactory.getKubernetesClient(k8sAccounts.get("qa"));
assertThat(k8sAccounts).hasSize(2);
assertThat(k8sAccounts).containsKeys("dev", "qa");
assertThat(devK8sClient.getNamespace()).isEqualTo("dev1");
assertThat(devK8sClient.getMasterUrl().toString()).isEqualTo("https://192.168.0.1:8443");
assertThat(qaK8sClient.getMasterUrl().toString()).isEqualTo("https://192.168.0.2:8443");
assertThat(k8sAccounts.get("dev").getImagePullPolicy()).isEqualTo(ImagePullPolicy.Always);
assertThat(k8sAccounts.get("dev").getEntryPointStyle()).isEqualTo(EntryPointStyle.exec);
assertThat(k8sAccounts.get("dev").getLimits().getCpu()).isEqualTo("4");
assertThat(k8sAccounts.get("qa").getImagePullPolicy()).isEqualTo(ImagePullPolicy.IfNotPresent);
assertThat(k8sAccounts.get("qa").getEntryPointStyle()).isEqualTo(EntryPointStyle.boot);
assertThat(k8sAccounts.get("qa").getLimits().getMemory()).isEqualTo("1024m");
}
@Test
@DisplayName("Should list all PodTemplate resources in some namespace")
public void testList() {
// Given
server.expect().get().withPath("/api/v1/namespaces/test/podtemplates")
.andReturn(200, new PodTemplateListBuilder().withItems(getPodTemplate()).build())
.once();
KubernetesClient client = server.getClient();
// When
PodTemplateList podTemplateList = client.v1().podTemplates().inNamespace("test").list();
// Then
assertNotNull(podTemplateList);
assertEquals(1, podTemplateList.getItems().size());
assertEquals("pt1", podTemplateList.getItems().get(0).getMetadata().getName());
assertEquals(1, podTemplateList.getItems().get(0).getTemplate().getSpec().getContainers().size());
}
private void delete(String namespaceName, KubernetesClient client)
throws InfrastructureException {
try {
client.namespaces().withName(namespaceName).withPropagationPolicy("Background").delete();
} catch (KubernetesClientException e) {
if (e.getCode() == 404) {
LOG.warn(
format(
"Tried to delete namespace '%s' but it doesn't exist in the cluster.",
namespaceName),
e);
} else if (e.getCode() == 409) {
LOG.info(format("The namespace '%s' is currently being deleted.", namespaceName), e);
} else {
throw new KubernetesInfrastructureException(e);
}
}
}
@Test
public void testApiDetectionOpenshift(VertxTestContext context) throws InterruptedException {
List<String> apis = new ArrayList<>();
apis.add("/apis/route.openshift.io/v1");
apis.add("/apis/build.openshift.io/v1");
apis.add("/apis/apps.openshift.io/v1");
apis.add("/apis/image.openshift.io/v1");
HttpServer mockHttp = startMockApi(context, apis);
KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());
Checkpoint async = context.checkpoint();
PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
assertThat(pfa.hasRoutes(), is(true));
assertThat(pfa.hasBuilds(), is(true));
assertThat(pfa.hasImages(), is(true));
assertThat(pfa.hasApps(), is(true));
stopMockApi(context, mockHttp);
async.flag();
})));
}
@Test
@DisplayName("Should delete a ConfigMap with specified PropagationPolicy")
void testDeleteConfigMapWithExplicitPropagationPolicy() throws InterruptedException {
// Given
server.expect().delete().withPath("/api/v1/namespaces/ns1/configmaps/myconfigMap")
.andReturn(HttpURLConnection.HTTP_OK, new ConfigMapBuilder().build())
.once();
KubernetesClient client = server.getClient();
// When
Boolean isDeleted = client.configMaps().inNamespace("ns1").withName("myconfigMap").withPropagationPolicy(DeletionPropagation.FOREGROUND).delete();
// Then
assertTrue(isDeleted);
assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.FOREGROUND.toString(), server.getLastRequest());
}
@Override
public void watch(List<ImageConfiguration> configs, Set<HasMetadata> resources, PlatformMode mode) throws Exception {
KubernetesClient kubernetes = getContext().getJKubeServiceHub().getClient();
PodLogService.PodLogServiceContext logContext = PodLogService.PodLogServiceContext.builder()
.log(log)
.newPodLog(getContext().getNewPodLogger())
.oldPodLog(getContext().getOldPodLogger())
.build();
new PodLogService(logContext).tailAppPodsLogs(
kubernetes,
getContext().getJKubeServiceHub().getClusterAccess().getNamespace(),
resources, false, null, true, null, false);
String url = getServiceExposeUrl(kubernetes, resources);
if (url == null) {
url = getPortForwardUrl(resources);
}
if (url != null) {
runRemoteSpringApplication(url);
} else {
throw new IllegalStateException("Unable to open a channel to the remote pod.");
}
}
@Test
public void testDeleteMulti() {
Ingress ingress1 = new IngressBuilder().withNewMetadata().withName("ingress1").withNamespace("test").and().build();
Ingress ingress2 = new IngressBuilder().withNewMetadata().withName("ingress2").withNamespace("ns1").and().build();
Ingress ingress3 = new IngressBuilder().withNewMetadata().withName("ingress3").withNamespace("any").and().build();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/ingresses/ingress1").andReturn(200, ingress1).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/ingresses/ingress2").andReturn(200, ingress2).once();
KubernetesClient client = server.getClient();
Boolean deleted = client.extensions().ingress().inAnyNamespace().delete(ingress1, ingress2);
assertTrue(deleted);
deleted = client.extensions().ingress().inAnyNamespace().delete(ingress3);
assertFalse(deleted);
}
private void testEnvironmentVariables(KubernetesSchedulerProperties kubernetesSchedulerProperties,
Map<String, String> schedulerProperties, EnvVar[] expectedVars) {
if (kubernetesSchedulerProperties.getNamespace() == null) {
kubernetesSchedulerProperties.setNamespace("default");
}
KubernetesClient kubernetesClient = new DefaultKubernetesClient()
.inNamespace(kubernetesSchedulerProperties.getNamespace());
KubernetesScheduler kubernetesScheduler = new KubernetesScheduler(kubernetesClient,
kubernetesSchedulerProperties);
AppDefinition appDefinition = new AppDefinition(randomName(), getAppProperties());
ScheduleRequest scheduleRequest = new ScheduleRequest(appDefinition, schedulerProperties,
null, getCommandLineArgs(), randomName(), testApplication());
CronJob cronJob = kubernetesScheduler.createCronJob(scheduleRequest);
CronJobSpec cronJobSpec = cronJob.getSpec();
Container container = cronJobSpec.getJobTemplate().getSpec().getTemplate().getSpec().getContainers().get(0);
assertTrue("Environment variables should not be empty", !container.getEnv().isEmpty());
assertThat(container.getEnv()).contains(expectedVars);
kubernetesScheduler.unschedule(cronJob.getMetadata().getName());
}
@Test
public void shouldCreateKubernetesClusterObject() throws Exception {
final KubernetesClient kubernetesClient = mock(KubernetesClient.class);
NodeOperationsImpl nodes = mock(NodeOperationsImpl.class);
PodOperationsImpl pods = mock(PodOperationsImpl.class);
when(nodes.list()).thenReturn(new NodeList());
when(kubernetesClient.nodes()).thenReturn(nodes);
when(pods.withLabel(Constants.CREATED_BY_LABEL_KEY, Constants.PLUGIN_ID)).thenReturn(pods);
when(pods.list()).thenReturn(new PodList());
when(kubernetesClient.pods()).thenReturn(pods);
final KubernetesCluster cluster = new KubernetesCluster(kubernetesClient);
verify(kubernetesClient, times(1)).nodes();
verify(kubernetesClient, times(1)).pods();
}
private static EntityPatcher<PersistentVolumeClaim> pvcPatcher() {
return (KubernetesClient client, String namespace, PersistentVolumeClaim newObj, PersistentVolumeClaim oldObj) -> {
if (UserConfigurationCompare.configEqual(newObj, oldObj)) {
return oldObj;
}
DoneablePersistentVolumeClaim entity =
client.persistentVolumeClaims()
.inNamespace(namespace)
.withName(oldObj.getMetadata().getName())
.edit();
if (!UserConfigurationCompare.configEqual(newObj.getMetadata(), oldObj.getMetadata())) {
entity.withMetadata(newObj.getMetadata());
}
if(!UserConfigurationCompare.configEqual(newObj.getSpec(), oldObj.getSpec())) {
entity.withSpec(newObj.getSpec());
}
return entity.done();
};
}
@Test
@DisplayName("Should delete a StatefulSet with PropagationPolicy=Background")
void testDeleteStatefulSet() throws InterruptedException {
// Given
server.expect().delete().withPath("/apis/apps/v1/namespaces/ns1/statefulsets/mystatefulset")
.andReturn(HttpURLConnection.HTTP_OK, new StatefulSetBuilder().build())
.once();
KubernetesClient client = server.getClient();
// When
Boolean isDeleted = client.apps().statefulSets().inNamespace("ns1").withName("mystatefulset").delete();
// Then
assertTrue(isDeleted);
assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.BACKGROUND.toString(), server.getLastRequest());
}
public static void deleteOpenShiftEntities(KubernetesClient kubernetes, String namespace, Set<HasMetadata> entities, String s2iBuildNameSuffix, KitLogger log) {
// For OpenShift cluster, also delete s2i buildconfig
OpenShiftClient openshiftClient = OpenshiftHelper.asOpenShiftClient(kubernetes);
if (openshiftClient == null) {
return;
}
for (HasMetadata entity : entities) {
if ("ImageStream".equals(KubernetesHelper.getKind(entity))) {
ImageName imageName = new ImageName(entity.getMetadata().getName());
String buildName = getS2IBuildName(imageName, s2iBuildNameSuffix);
log.info("Deleting resource BuildConfig %s/%s and Builds", namespace, buildName);
openshiftClient.builds().inNamespace(namespace).withLabel("buildconfig", buildName).delete();
openshiftClient.buildConfigs().inNamespace(namespace).withName(buildName).delete();
}
}
}
/**
* Log the last lines of containers logs
*/
private void logLastLines(@CheckForNull List<ContainerStatus> containers, String podId, String namespace, KubernetesSlave slave,
Map<String, Integer> errors, KubernetesClient client) {
if (containers != null) {
for (ContainerStatus containerStatus : containers) {
String containerName = containerStatus.getName();
PrettyLoggable<String, LogWatch> tailingLines = client.pods().inNamespace(namespace).withName(podId)
.inContainer(containerStatus.getName()).tailingLines(30);
String log = tailingLines.getLog();
if (!StringUtils.isBlank(log)) {
String msg = errors != null ? String.format(" exited with error %s", errors.get(containerName)) : "";
LOGGER.log(Level.SEVERE, "Error in provisioning; agent={0}, template={1}. Container {2}{3}. Logs: {4}",
new Object[]{slave, slave.getTemplate(), containerName, msg, tailingLines.getLog()});
}
}
}
}
@Test
public void testResourceGetFromLoadWhenMultipleDocumentsWithDelimiter() throws Exception {
// given
KubernetesClient client = server.getClient();
// when
List<HasMetadata> result = client.load(getClass().getResourceAsStream("/multiple-document-template.yml")).get();
// then
assertNotNull(result);
assertEquals(6, result.size());
HasMetadata deploymentResource = result.get(1);
assertEquals("apps/v1", deploymentResource.getApiVersion());
assertEquals("Deployment", deploymentResource.getKind());
assertEquals("redis-master", deploymentResource.getMetadata().getName());
}
@Test
public void testFabric8Namespacing() {
KubernetesDeployerProperties kubernetesDeployerProperties = new KubernetesDeployerProperties();
kubernetesDeployerProperties.getFabric8().setTrustCerts(true);
kubernetesDeployerProperties.getFabric8().setMasterUrl("http://localhost:8090");
// this can be set programatically in properties as well as an environment variable
// (ie: CI, cmd line, etc) so ensure we have a clean slate here
kubernetesDeployerProperties.setNamespace(null);
kubernetesDeployerProperties.getFabric8().setNamespace("testing");
KubernetesClient kubernetesClient = KubernetesClientFactory
.getKubernetesClient(kubernetesDeployerProperties);
assertEquals("http://localhost:8090", kubernetesClient.getMasterUrl().toString());
assertEquals("testing", kubernetesClient.getNamespace());
assertEquals("http://localhost:8090", kubernetesClient.getConfiguration().getMasterUrl());
assertEquals(Boolean.TRUE, kubernetesClient.getConfiguration().isTrustCerts());
}
@Test
public void testUpdateStatusWorksAfterUpgradeWithHttp422ResponseAboutApiVersionField(VertxTestContext context) throws IOException {
KubernetesClient mockClient = mock(KubernetesClient.class);
OkHttpClient mockOkHttp = mock(OkHttpClient.class);
when(mockClient.adapt(eq(OkHttpClient.class))).thenReturn(mockOkHttp);
URL fakeUrl = new URL("http", "my-host", 9443, "/");
when(mockClient.getMasterUrl()).thenReturn(fakeUrl);
Call mockCall = mock(Call.class);
when(mockOkHttp.newCall(any(Request.class))).thenReturn(mockCall);
ResponseBody body = ResponseBody.create(OperationSupport.JSON, "{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{},\"status\":\"Failure\",\"message\":\"Kafka." + Constants.RESOURCE_GROUP_NAME + " \\\"my-cluster\\\" is invalid: apiVersion: Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"reason\":\"Invalid\",\"details\":{\"name\":\"my-cluster\",\"group\":\"" + Constants.RESOURCE_GROUP_NAME + "\",\"kind\":\"Kafka\",\"causes\":[{\"reason\":\"FieldValueInvalid\",\"message\":\"Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"field\":\"apiVersion\"}]},\"code\":422}");
Response response = new Response.Builder().code(422).request(new Request.Builder().url(fakeUrl).build()).body(body).message("Unprocessable Entity").protocol(Protocol.HTTP_1_1).build();
when(mockCall.execute()).thenReturn(response);
Checkpoint async = context.checkpoint();
createResourceOperations(vertx, mockClient)
.updateStatusAsync(resource())
.onComplete(context.succeeding(kafka -> async.flag()));
}
@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 portAndTargetPortTest() throws IOException, InterruptedException, KubernetesPluginException,
DockerTestException {
Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(BAL_DIRECTORY, "port_and_target_port.bal"), 0);
File yamlFile = KUBERNETES_TARGET_PATH.resolve("port_and_target_port.yaml").toFile();
Assert.assertTrue(yamlFile.exists());
KubernetesClient client = new DefaultKubernetesClient();
List<HasMetadata> k8sItems = client.load(new FileInputStream(yamlFile)).get();
for (HasMetadata data : k8sItems) {
if ("Service".equals(data.getKind())) {
Service service = (Service) data;
Assert.assertNotNull(service);
Assert.assertEquals("hello", service.getMetadata().getName());
Assert.assertEquals("port_and_target_port", service.getMetadata().getLabels().get(KubernetesConstants
.KUBERNETES_SELECTOR_KEY));
Assert.assertEquals(KubernetesConstants.ServiceType.ClusterIP.name(), service.getSpec().getType());
Assert.assertEquals(1, service.getSpec().getPorts().size());
Assert.assertEquals(8080, service.getSpec().getPorts().get(0).getPort().intValue());
Assert.assertEquals(9090, service.getSpec().getPorts().get(0).getTargetPort().getIntVal().intValue());
}
}
validateDockerfile();
validateDockerImage(DOCKER_IMAGE);
KubernetesUtils.deleteDirectory(KUBERNETES_TARGET_PATH);
KubernetesUtils.deleteDirectory(DOCKER_TARGET_PATH);
KubernetesTestUtils.deleteDockerImage(DOCKER_IMAGE);
}
@Bean
@ConditionalOnMissingBean
public KubernetesDiscoveryClient kubernetesDiscoveryClient(
KubernetesClient client, KubernetesDiscoveryProperties properties,
KubernetesClientServicesFunction kubernetesClientServicesFunction,
DefaultIsServicePortSecureResolver isServicePortSecureResolver) {
return new KubernetesDiscoveryClient(client, properties,
kubernetesClientServicesFunction, isServicePortSecureResolver);
}
@Test
public void testEditMissing() {
Assertions.assertThrows(KubernetesClientException.class, () -> {
server.expect().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(404, "error message from kubernetes").always();
KubernetesClient client = server.getClient();
client.pods().withName("pod1").edit();
});
}
@Bean
public ServicesController servicesController(
final KubernetesClient client,
@Qualifier("LABELS_TO_WATCH") final Map<String, String> labelsToWatch
) {
return new ServicesController(client, labelsToWatch);
}
public Session(KubernetesClient kubeClient, Config config) {
this.kubeClient = kubeClient;
this.config = config;
StringBuilder sb = new StringBuilder(System.lineSeparator());
for (Config.Value<?> v: Config.keys()) {
sb.append("\t").append(v.key).append(": ").append(Util.maskPassword(v.key, config.get(v).toString())).append(System.lineSeparator());
}
LOGGER.info("Using config:{}", sb.toString());
this.metricsRegistry = (PrometheusMeterRegistry) BackendRegistries.getDefaultNow();
}
@Test
public void testList() {
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/ingresses").andReturn(200, new IngressListBuilder().build()).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/ingresses").andReturn(200, new IngressListBuilder()
.addNewItem().and()
.addNewItem().and().build()).once();
server.expect().withPath("/apis/extensions/v1beta1/ingresses").andReturn(200, new IngressListBuilder()
.addNewItem().and()
.addNewItem().and()
.addNewItem()
.and().build()).once();
KubernetesClient client = server.getClient();
IngressList ingressList = client.extensions().ingress().list();
assertNotNull(ingressList);
assertEquals(0, ingressList.getItems().size());
ingressList = client.extensions().ingress().inNamespace("ns1").list();
assertNotNull(ingressList);
assertEquals(2, ingressList.getItems().size());
ingressList = client.extensions().ingress().inAnyNamespace().list();
assertNotNull(ingressList);
assertEquals(3, ingressList.getItems().size());
}
@BeforeEach
public void setup(@Client KubernetesClient kubernetesClient) {
// Configure the kubernetes master url to point to the mock server
System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY,
kubernetesClient.getConfiguration().getMasterUrl());
System.setProperty(Config.KUBERNETES_TRUST_CERT_SYSTEM_PROPERTY, "true");
System.setProperty(Config.KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY, "false");
System.setProperty(Config.KUBERNETES_AUTH_TRYSERVICEACCOUNT_SYSTEM_PROPERTY,
"false");
System.setProperty(Config.KUBERNETES_HTTP2_DISABLE, "true");
}
@Disabled
@Test
public void testUpdate() {
ReplicaSet repl1 = new ReplicaSetBuilder()
.withNewMetadata()
.withName("repl1")
.withNamespace("test")
.endMetadata()
.withNewSpec()
.withReplicas(1)
.withNewTemplate()
.withNewMetadata().withLabels(new HashMap<String, String>()).endMetadata()
.withNewSpec()
.addNewContainer()
.withImage("img1")
.endContainer()
.endSpec()
.endTemplate()
.endSpec()
.withNewStatus().withReplicas(1).endStatus()
.build();
server.expect().withPath("/apis/apps/v1/namespaces/test/replicasets/repl1").andReturn(200, repl1).once();
server.expect().put().withPath("/apis/apps/v1/namespaces/test/replicasets/repl1").andReturn(200, repl1).once();
server.expect().get().withPath("/apis/apps/v1/namespaces/test/replicasets").andReturn(200, new ReplicaSetListBuilder().withItems(repl1).build()).once();
server.expect().post().withPath("/apis/apps/v1/namespaces/test/replicasets").andReturn(201, repl1).once();
server.expect().withPath("/apis/apps/v1/namespaces/test/pods").andReturn(200, new KubernetesListBuilder().build()).once();
KubernetesClient client = server.getClient();
repl1 = client.apps().replicaSets().withName("repl1")
.rolling()
.withTimeout(5, TimeUnit.MINUTES)
.updateImage("");
assertNotNull(repl1);
}