下面列出了org.junit.rules.TestName#io.fabric8.kubernetes.api.model.NamespaceBuilder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void initialize(boolean updateStatus) {
k8sClient = new DefaultKubernetesClient();
log.info("Initializing integration test in namespace {}", TEST_NAMESPACE);
CustomResourceDefinition crd = loadYaml(CustomResourceDefinition.class, "test-crd.yaml");
k8sClient.customResourceDefinitions().createOrReplace(crd);
controller = new TestCustomResourceController(k8sClient, updateStatus);
Class doneableClass = getCustomResourceDoneableClass(controller);
crOperations = k8sClient.customResources(crd, TestCustomResource.class, CustomResourceList.class, doneableClass);
crOperations.inNamespace(TEST_NAMESPACE).delete(crOperations.list().getItems());
if (k8sClient.namespaces().withName(TEST_NAMESPACE).get() == null) {
k8sClient.namespaces().create(new NamespaceBuilder()
.withMetadata(new ObjectMetaBuilder().withName(TEST_NAMESPACE).build()).build());
}
operator = new Operator(k8sClient);
operator.registerController(controller, TEST_NAMESPACE);
log.info("Operator is running with TestCustomeResourceController");
}
@Test
public void shouldReturnDefaultNamespaceWhenItExistsAndUserDefinedIsNotAllowed()
throws Exception {
prepareNamespaceToBeFoundByName(
"che-default",
new NamespaceBuilder()
.withNewMetadata()
.withName("che-default")
.endMetadata()
.withNewStatus()
.withNewPhase("Active")
.endStatus()
.build());
namespaceFactory =
new KubernetesNamespaceFactory(
"predefined", "", "", "che-default", false, clientFactory, userManager, pool);
List<KubernetesNamespaceMeta> availableNamespaces = namespaceFactory.list();
assertEquals(availableNamespaces.size(), 1);
KubernetesNamespaceMeta defaultNamespace = availableNamespaces.get(0);
assertEquals(defaultNamespace.getName(), "che-default");
assertEquals(defaultNamespace.getAttributes().get(DEFAULT_ATTRIBUTE), "true");
assertEquals(defaultNamespace.getAttributes().get(PHASE_ATTRIBUTE), "Active");
}
@Test
public void testDeleteMulti() {
Namespace namespace1 = new NamespaceBuilder().withNewMetadata().withName("namespace1").and().build();
Namespace namespace2 = new NamespaceBuilder().withNewMetadata().withName("namespace2").and().build();
Namespace namespace3 = new NamespaceBuilder().withNewMetadata().withName("namespace3").and().build();
server.expect().withPath("/api/v1/namespaces/namespace1").andReturn(200, namespace1).once();
server.expect().withPath("/api/v1/namespaces/namespace2").andReturn(200, namespace2).once();
KubernetesClient client = server.getClient();
Boolean deleted = client.namespaces().delete(namespace1, namespace2);
assertTrue(deleted);
deleted = client.namespaces().delete(namespace3);
assertFalse(deleted);
}
public static void main(String[] args) {
String master = "https://localhost:8443/";
if (args.length == 1) {
master = args[0];
}
Config config = new ConfigBuilder().withMasterUrl(master).build();
KubernetesClient client = new DefaultKubernetesClient(config);
try {
log("Create namespace:", client.namespaces().create(new NamespaceBuilder().withNewMetadata().withName("thisisatest").endMetadata().build()));
log("Deleted namespace:", client.namespaces().withName("test").delete());
log("Deleted testPod:", client.pods().inNamespace("thisisatest").withName("testpod").delete());
log("Deleted pod by label:", client.pods().withLabel("this", "works").delete());
} catch (KubernetesClientException e) {
logger.error(e.getMessage(), e);
} finally {
client.namespaces().withName("thisisatest").delete();
client.close();
}
}
@BeforeClass
public static void configureCloud() throws Exception {
// do not run if minikube is not running
assumeMiniKube();
cloud.setServerUrl(miniKubeUrl().toExternalForm());
cloud.setNamespace(TESTING_NAMESPACE);
KubernetesClient client = cloud.connect();
// Run in our own testing namespace
client.namespaces().createOrReplace(
new NamespaceBuilder().withNewMetadata().withName(TESTING_NAMESPACE).endMetadata().build());
}
public void createNamespace(String namespace, Map<String, String> labels) {
if (!namespaceExists(namespace)) {
log.info("Following namespace will be created = {}", namespace);
var builder = new NamespaceBuilder().withNewMetadata().withName(namespace);
if (labels != null) {
builder.withLabels(labels);
}
Namespace ns = builder.endMetadata().build();
client.namespaces().create(ns);
} else {
log.info("Namespace {} already exists", namespace);
}
}
public static String deployMessagingClientApp(String namespace) throws Exception {
if (!kube.namespaceExists(namespace)) {
if (namespace.equals("allowed-namespace")) {
Namespace allowedNamespace = new NamespaceBuilder().withNewMetadata()
.withName("allowed-namespace").addToLabels("allowed", "true").endMetadata().build();
kube.getClient().namespaces().create(allowedNamespace);
} else {
kube.createNamespace(namespace);
}
}
kube.createDeploymentFromResource(namespace, getMessagingAppDeploymentResource(namespace));
TestUtils.waitForExpectedReadyPods(kube, namespace, 1, new TimeoutBudget(5, TimeUnit.MINUTES));
return getMessagingAppPodName(namespace);
}
private Namespace createNamespace(String name, String phase) {
return new NamespaceBuilder()
.withNewMetadata()
.withName(name)
.endMetadata()
.withNewStatus()
.withNewPhase(phase)
.endStatus()
.build();
}
private Resource prepareNamespaceResource(String namespaceName) {
Resource namespaceResource = mock(Resource.class);
doReturn(namespaceResource).when(namespaceOperation).withName(namespaceName);
doReturn(namespaceResource).when(namespaceResource).withPropagationPolicy(eq("Background"));
when(namespaceResource.get())
.thenReturn(
new NamespaceBuilder().withNewMetadata().withName(namespaceName).endMetadata().build());
kubernetesClient.namespaces().withName(namespaceName).get();
return namespaceResource;
}
public static KubernetesCloud setupCloud(Object test, TestName name) throws KubernetesAuthException, IOException {
KubernetesCloud cloud = new KubernetesCloud("kubernetes");
// unique labels per test
cloud.setPodLabels(PodLabel.fromMap(getLabels(cloud, test, name)));
KubernetesClient client = cloud.connect();
// Run in our own testing namespace
// if there is a namespace specific for this branch (ie. kubernetes-plugin-test-master), use it
String branch = System.getenv("BRANCH_NAME");
if (StringUtils.isNotBlank(branch)) {
String namespaceWithBranch = String.format("%s-%s", DEFAULT_TESTING_NAMESPACE, branch);
LOGGER.log(FINE, "Trying to use namespace: {0}", testingNamespace);
try {
if (client.namespaces().withName(namespaceWithBranch).get() != null) {
testingNamespace = namespaceWithBranch;
}
} catch (KubernetesClientException e) {
// nothing to do
}
}
if (testingNamespace == null) {
testingNamespace = DEFAULT_TESTING_NAMESPACE;
if (client.namespaces().withName(testingNamespace).get() == null) {
LOGGER.log(INFO, "Creating namespace: {0}", testingNamespace);
client.namespaces().create(
new NamespaceBuilder().withNewMetadata().withName(testingNamespace).endMetadata().build());
}
}
LOGGER.log(INFO, "Using namespace {0} for branch {1}", new String[] { testingNamespace, branch });
cloud.setNamespace(testingNamespace);
client = cloud.connect();
return cloud;
}
@Test
public void testCreateWithNameMismatch() {
Assertions.assertThrows(KubernetesClientException.class, () -> {
Namespace ns1 = new NamespaceBuilder().withNewMetadata().withName("ns1").and().build();
KubernetesClient client = server.getClient();
client.namespaces().withName("myns1").create(ns1);
});
}
@Test
public void testCreateWithHandler() {
server.expect().post().withPath("/api/v1/namespaces")
.andReturn(200, new NamespaceBuilder()
.withNewMetadata()
.withName("namespace-test")
.endMetadata()
.build()).once();
KubernetesClient client = server.getClient();
List<HasMetadata> nsList = client.load(getClass().getResourceAsStream("/test-namespace.yml")).createOrReplace();
assertNotNull(nsList);
assertEquals(1, nsList.size());
assertEquals("namespace-test", nsList.get(0).getMetadata().getName());
}
@Test
public void testGet() {
server.expect().withPath("/api/v1/namespaces/namespace1").andReturn(200, new NamespaceBuilder().build()).once();
server.expect().withPath("/api/v1/namespaces/namespace2").andReturn(200, new NamespaceBuilder().build()).once();
KubernetesClient client = server.getClient();
Namespace namespace = client.namespaces().withName("namespace1").get();
assertNotNull(namespace);
namespace = client.namespaces().withName("namespace2").get();
assertNotNull(namespace);
namespace = client.namespaces().withName("namespace2").get();
assertNull(namespace);
}
@Test
public void testDelete() {
server.expect().withPath("/api/v1/namespaces/namespace1").andReturn(200, new NamespaceBuilder().build()).once();
KubernetesClient client = server.getClient();
Boolean deleted = client.namespaces().withName("namespace1").delete();
assertTrue(deleted);
}
public static void main(String[] args) {
String master = "https://localhost:8443/";
if (args.length == 1) {
master = args[0];
}
Config config = new ConfigBuilder().withMasterUrl(master).build();
try (KubernetesClient client = new DefaultKubernetesClient(config)) {
try {
log("Create namespace:", client.namespaces().create(new NamespaceBuilder().withNewMetadata().withName("thisisatest").endMetadata().build()));
Pod createdPod = client.pods().inNamespace("thisisatest").createNew()
.withNewMetadata()
.withName("testpod")
.addToLabels("server", "nginx")
.endMetadata()
.withNewSpec()
.addNewContainer().withName("nginx").withImage("nginx")
.addNewPort().withContainerPort(80).endPort()
.endContainer()
.endSpec().done();
log("Created testPod:", createdPod);
Pod updatedPod = client.pods().inNamespace("thisisatest").withName("testpod").edit()
.editMetadata()
.addToLabels("server2", "nginx2")
.and().done();
log("Replaced testPod:", updatedPod);
} catch (KubernetesClientException e) {
logger.error(e.getMessage(), e);
} finally {
client.namespaces().withName("thisisatest").delete();
}
}
}
public void createNamespace(String name) {
Namespace ns = new NamespaceBuilder().withNewMetadata().withName(name).endMetadata().build();
client.namespaces().createOrReplace(ns);
}
public static Namespace getDefault() {
return new NamespaceBuilder().withNewMetadata().withName("enmasse-app").endMetadata().build();
}
protected void createNamespaceIfNotExist(KubernetesClient client, String namespace) {
if (client.namespaces().withName(namespace).get() == null) {
client.namespaces().createOrReplace(
new NamespaceBuilder().withNewMetadata().withName(namespace).endMetadata().build());
}
}
public static void main(String[] args) throws InterruptedException {
Config config = new ConfigBuilder().build();
KubernetesClient client = new DefaultKubernetesClient(config);
try {
// Create a namespace for all our stuff
Namespace ns = new NamespaceBuilder().withNewMetadata().withName("thisisatest").addToLabels("this", "rocks").endMetadata().build();
log("Created namespace", client.namespaces().createOrReplace(ns));
ServiceAccount fabric8 = new ServiceAccountBuilder().withNewMetadata().withName("fabric8").endMetadata().build();
client.serviceAccounts().inNamespace("thisisatest").createOrReplace(fabric8);
for (int i = 0; i < 2; i++) {
System.err.println("Iteration:" + (i+1));
Deployment deployment = new DeploymentBuilder()
.withNewMetadata()
.withName("nginx")
.endMetadata()
.withNewSpec()
.withReplicas(1)
.withNewTemplate()
.withNewMetadata()
.addToLabels("app", "nginx")
.endMetadata()
.withNewSpec()
.addNewContainer()
.withName("nginx")
.withImage("nginx")
.addNewPort()
.withContainerPort(80)
.endPort()
.endContainer()
.endSpec()
.endTemplate()
.withNewSelector()
.addToMatchLabels("app", "nginx")
.endSelector()
.endSpec()
.build();
deployment = client.apps().deployments().inNamespace("thisisatest").create(deployment);
log("Created deployment", deployment);
System.err.println("Scaling up:" + deployment.getMetadata().getName());
client.apps().deployments().inNamespace("thisisatest").withName("nginx").scale(2, true);
log("Created replica sets:", client.apps().replicaSets().inNamespace("thisisatest").list().getItems());
System.err.println("Deleting:" + deployment.getMetadata().getName());
client.resource(deployment).delete();
}
log("Done.");
}finally {
client.namespaces().withName("thisisatest").delete();
client.close();
}
}