http://git-wip-us.apache.org/repos/asf/stratos/blob/86fd5cf2/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/TemplateApiLiveTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/TemplateApiLiveTest.java b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/TemplateApiLiveTest.java new file mode 100644 index 0000000..d85cd05 --- /dev/null +++ b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/TemplateApiLiveTest.java @@ -0,0 +1,217 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jclouds.cloudstack.features; + +import static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.zoneId; +import static org.jclouds.util.Predicates2.retry; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import java.net.URI; +import java.net.URLDecoder; +import java.util.Set; + +import org.jclouds.cloudstack.domain.AsyncCreateResponse; +import org.jclouds.cloudstack.domain.AsyncJob; +import org.jclouds.cloudstack.domain.ExtractMode; +import org.jclouds.cloudstack.domain.Network; +import org.jclouds.cloudstack.domain.OSType; +import org.jclouds.cloudstack.domain.Template; +import org.jclouds.cloudstack.domain.TemplateExtraction; +import org.jclouds.cloudstack.domain.TemplateMetadata; +import org.jclouds.cloudstack.domain.VirtualMachine; +import org.jclouds.cloudstack.domain.Volume; +import org.jclouds.cloudstack.domain.Zone; +import org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest; +import org.jclouds.cloudstack.options.CreateTemplateOptions; +import org.jclouds.cloudstack.options.ListNetworksOptions; +import org.jclouds.cloudstack.options.ListVolumesOptions; +import org.jclouds.cloudstack.options.RegisterTemplateOptions; +import org.jclouds.logging.Logger; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.Test; + +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; + +/** + * Tests behavior of {@code TemplateApi} + */ +@Test(groups = "live", singleThreaded = true, testName = "TemplateApiLiveTest") +public class TemplateApiLiveTest extends BaseCloudStackApiLiveTest { + + private static final String IMPORT_VHD_URL = "http://www.frontiertown.co.uk/jclouds/empty.vhd"; + private VirtualMachine vmForCreation; + private VirtualMachine vmForRegistration; + private Template createdTemplate; + private Template registeredTemplate; + + @Test + public void testListTemplates() throws Exception { + Set<Template> response = client.getTemplateApi().listTemplates(); + assert null != response; + long templateCount = response.size(); + assertTrue(templateCount >= 0); + for (Template template : response) { + Template newDetails = Iterables.getOnlyElement(client.getTemplateApi().listTemplates( + zoneId(template.getZoneId()).id(template.getId()))); + Logger.CONSOLE.info("Checking template: " + template); + + assertEquals(template, newDetails); + assertEquals(template, client.getTemplateApi().getTemplateInZone(template.getId(), template.getZoneId())); + assert template.getId() != null : template; + assert template.getName() != null : template; + assert template.getDisplayText() != null : template; + assert template.getCreated() != null : template; + assert template.getFormat() != null && template.getFormat() != Template.Format.UNRECOGNIZED : template; + assert template.getOSType() != null : template; + assert template.getOSTypeId() != null : template; + assert template.getAccount() != null : template; + assert template.getZone() != null : template; + assert template.getZoneId() != null : template; + assert template.getStatus() == null || + template.getStatus() == Template.Status.DOWNLOADED : template; + assert template.getType() != null && template.getType() != Template.Type.UNRECOGNIZED : template; + assert template.getHypervisor() != null : template; + assert template.getDomain() != null : template; + assert template.getDomainId() != null : template; + assert template.getSize() > 0 : template; + } + } + + @Test(enabled = true) + public void testCreateTemplate() throws Exception { + Zone zone = Iterables.getFirst(client.getZoneApi().listZones(), null); + assertNotNull(zone); + Iterable<Network> networks = client.getNetworkApi().listNetworks(ListNetworksOptions.Builder.zoneId(zone.getId()).isDefault(true)); + networks = Iterables.filter(networks, new Predicate<Network>() { + @Override + public boolean apply(Network network) { + return network != null && network.getState().equals("Implemented"); + } + }); + assertTrue(Iterables.size(networks) >= 1); + Network network = Iterables.get(networks, 0); + assertNotNull(network); + + // Create a VM and stop it + String defaultTemplate = template != null ? template.getImageId() : null; + vmForCreation = VirtualMachineApiLiveTest.createVirtualMachineInNetwork(network, defaultTemplate, client, jobComplete, virtualMachineRunning); + assertTrue(jobComplete.apply(client.getVirtualMachineApi().stopVirtualMachine(vmForCreation.getId())), vmForCreation.toString()); + + // Work out the VM's volume + Set<Volume> volumes = client.getVolumeApi().listVolumes(ListVolumesOptions.Builder.virtualMachineId(vmForCreation.getId())); + assertEquals(volumes.size(), 1); + Volume volume = Iterables.getOnlyElement(volumes); + + // Create a template + CreateTemplateOptions options = CreateTemplateOptions.Builder.volumeId(volume.getId()); + AsyncCreateResponse response = client.getTemplateApi().createTemplate(TemplateMetadata.builder().name(prefix + "-createTemplate").osTypeId(vmForCreation.getGuestOSId()).displayText("jclouds live testCreateTemplate").build(), options); + assertTrue(jobComplete.apply(response.getJobId()), vmForCreation.toString()); + createdTemplate = client.getTemplateApi().getTemplateInZone(response.getId(), vmForCreation.getZoneId()); + + // Assertions + assertNotNull(createdTemplate); + } + + @Test(enabled = true, dependsOnMethods = "testRegisterTemplate") + public void testExtractTemplate() throws Exception { + // Initiate the extraction and wait for it to complete + AsyncCreateResponse response = client.getTemplateApi().extractTemplate(registeredTemplate.getId(), ExtractMode.HTTP_DOWNLOAD, registeredTemplate.getZoneId()); + assertTrue(jobComplete.apply(response.getJobId()), registeredTemplate.toString()); + + // Get the result + AsyncJob<TemplateExtraction> asyncJob = client.getAsyncJobApi().getAsyncJob(response.getJobId()); + TemplateExtraction extract = asyncJob.getResult(); + assertNotNull(extract); + + // Check that the URL can be retrieved + String extractUrl = extract.getUrl(); + assertNotNull(extractUrl); + URI uri = new URI(URLDecoder.decode(extractUrl, "utf-8")); + assertTrue(cloudStackContext.utils().http().exists(uri), "does not exist: " + uri); + } + + @Test(enabled = true) + public void testRegisterTemplate() throws Exception { + Zone zone = Iterables.getFirst(client.getZoneApi().listZones(), null); + assertNotNull(zone); + Iterable<Network> networks = client.getNetworkApi().listNetworks(ListNetworksOptions.Builder.zoneId(zone.getId()).isDefault(true)); + networks = Iterables.filter(networks, new Predicate<Network>() { + @Override + public boolean apply(Network network) { + return network != null && network.getName().equals("Virtual Network"); + } + }); + assertEquals(Iterables.size(networks), 1); + Network network = Iterables.getOnlyElement(networks, null); + assertNotNull(network); + Set<OSType> osTypes = client.getGuestOSApi().listOSTypes(); + OSType osType = Iterables.getFirst(osTypes, null); + + // Register a template + RegisterTemplateOptions options = RegisterTemplateOptions.Builder.bits(32).isExtractable(true); + TemplateMetadata templateMetadata = TemplateMetadata.builder().name(prefix + "-registerTemplate").osTypeId(osType.getId()).displayText("jclouds live testRegisterTemplate").build(); + Set<Template> templates = client.getTemplateApi().registerTemplate(templateMetadata, "VHD", "XenServer", IMPORT_VHD_URL, zone.getId(), options); + registeredTemplate = Iterables.getOnlyElement(templates, null); + assertNotNull(registeredTemplate); + + // Ensure it is available + final String zoneId = zone.getId(); + Predicate<Template> templateReadyPredicate = new Predicate<Template>() { + @Override + public boolean apply(Template template) { + if (template == null) return false; + Template t2 = client.getTemplateApi().getTemplateInZone(template.getId(), zoneId); + Logger.CONSOLE.info("%s", t2.getStatus()); + return t2.getStatus() == Template.Status.DOWNLOADED; + } + }; + assertTrue(retry(templateReadyPredicate, 60000).apply(registeredTemplate)); + + // Create a VM that uses this template + vmForRegistration = VirtualMachineApiLiveTest.createVirtualMachineInNetwork(network, registeredTemplate.getId(), client, jobComplete, virtualMachineRunning); + assertNotNull(vmForRegistration); + } + + + @AfterGroups(groups = "live") + @Override + protected void tearDownContext() { + if (vmForCreation != null) { + assertTrue(jobComplete.apply(client.getVirtualMachineApi().stopVirtualMachine(vmForCreation.getId())), vmForCreation.toString()); + assertTrue(jobComplete.apply(client.getVirtualMachineApi().destroyVirtualMachine(vmForCreation.getId())), vmForCreation.toString()); + assertTrue(virtualMachineDestroyed.apply(vmForCreation)); + } + if (vmForRegistration != null) { + assertTrue(jobComplete.apply(client.getVirtualMachineApi().stopVirtualMachine(vmForRegistration.getId())), vmForRegistration.toString()); + assertTrue(jobComplete.apply(client.getVirtualMachineApi().destroyVirtualMachine(vmForRegistration.getId())), vmForRegistration.toString()); + assert virtualMachineDestroyed.apply(vmForRegistration); + } + if (createdTemplate != null) { + AsyncCreateResponse deleteJob = client.getTemplateApi().deleteTemplate(createdTemplate.getId()); + assertTrue(jobComplete.apply(deleteJob.getJobId())); + } + if (registeredTemplate != null) { + AsyncCreateResponse deleteJob = client.getTemplateApi().deleteTemplate(registeredTemplate.getId()); + assertTrue(jobComplete.apply(deleteJob.getJobId())); + } + super.tearDownContext(); + } + +}
http://git-wip-us.apache.org/repos/asf/stratos/blob/86fd5cf2/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/TemplateApiTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/TemplateApiTest.java b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/TemplateApiTest.java new file mode 100644 index 0000000..002d6b0 --- /dev/null +++ b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/TemplateApiTest.java @@ -0,0 +1,400 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jclouds.cloudstack.features; + +import static org.jclouds.reflect.Reflection2.method; + +import java.io.IOException; + +import org.jclouds.Fallbacks.EmptySetOnNotFoundOr404; +import org.jclouds.Fallbacks.NullOnNotFoundOr404; +import org.jclouds.cloudstack.domain.ExtractMode; +import org.jclouds.cloudstack.domain.Template; +import org.jclouds.cloudstack.domain.TemplateFilter; +import org.jclouds.cloudstack.domain.TemplateMetadata; +import org.jclouds.cloudstack.internal.BaseCloudStackApiTest; +import org.jclouds.cloudstack.options.AccountInDomainOptions; +import org.jclouds.cloudstack.options.CreateTemplateOptions; +import org.jclouds.cloudstack.options.DeleteTemplateOptions; +import org.jclouds.cloudstack.options.ExtractTemplateOptions; +import org.jclouds.cloudstack.options.ListTemplatesOptions; +import org.jclouds.cloudstack.options.RegisterTemplateOptions; +import org.jclouds.cloudstack.options.UpdateTemplateOptions; +import org.jclouds.cloudstack.options.UpdateTemplatePermissionsOptions; +import org.jclouds.fallbacks.MapHttp4xxCodesToExceptions; +import org.jclouds.functions.IdentityFunction; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.functions.ParseFirstJsonValueNamed; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.testng.annotations.Test; + +import com.google.common.base.Functions; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import com.google.common.reflect.Invokable; +/** + * Tests behavior of {@code TemplateApi} + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "TemplateApiTest") +public class TemplateApiTest extends BaseCloudStackApiTest<TemplateApi> { + + public void testCreateTemplate() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "createTemplate", TemplateMetadata.class, CreateTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(TemplateMetadata.builder().name("thename").osTypeId("10").displayText("description").build())); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=createTemplate&name=thename&ostypeid=10&displaytext=description HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + public void testCreateTemplateOptions() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "createTemplate", TemplateMetadata.class, CreateTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(TemplateMetadata.builder().name("thename").osTypeId("10").displayText("description").build(), CreateTemplateOptions.Builder.bits(32).isFeatured(true).isPublic(true).passwordEnabled(true).requiresHVM(true).snapshotId("11").volumeId("12"))); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=createTemplate&bits=32&isfeatured=true&ispublic=true&passwordenabled=true&requireshvm=true&snapshotid=11&volumeid=12&name=thename&ostypeid=10&displaytext=description HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + HttpRequest registerTemplate = HttpRequest.builder().method("GET") + .endpoint("http://localhost:8080/client/api") + .addQueryParam("response", "json") + .addQueryParam("command", "registerTemplate") + .addQueryParam("format", "QCOW2") + .addQueryParam("hypervisor", "xen") + .addQueryParam("url", "http%3A//example.com/") + .addQueryParam("zoneid", "20") + .addQueryParam("name", "thename") + .addQueryParam("ostypeid", "10") + .addQueryParam("displaytext", "description").build(); + + public void testRegisterTemplate() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "registerTemplate", TemplateMetadata.class, String.class, String.class, String.class, String.class, RegisterTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(TemplateMetadata.builder().name("thename").osTypeId("10").displayText("description").build(), Template.Format.QCOW2, "xen", "http://example.com/", 20)); + + assertRequestLineEquals(httpRequest, registerTemplate.getRequestLine()); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + HttpRequest registerTemplateOptions = HttpRequest.builder().method("GET") + .endpoint("http://localhost:8080/client/api") + .addQueryParam("response", "json") + .addQueryParam("command", "registerTemplate") + .addQueryParam("format", "QCOW2") + .addQueryParam("hypervisor", "xen") + .addQueryParam("url", "http%3A//example.com/") + .addQueryParam("zoneid", "20") + .addQueryParam("account", "mydomain") + .addQueryParam("domainid", "3") + .addQueryParam("bits", "32") + .addQueryParam("checksum", "ABC") + .addQueryParam("isextractable", "true") + .addQueryParam("isfeatured", "true") + .addQueryParam("ispublic", "true") + .addQueryParam("passwordenabled", "true") + .addQueryParam("requireshvm", "true") + .addQueryParam("name", "thename") + .addQueryParam("ostypeid", "10") + .addQueryParam("displaytext", "description").build(); + + public void testRegisterTemplateOptions() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "registerTemplate", TemplateMetadata.class, String.class, String.class, String.class, String.class, RegisterTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(TemplateMetadata.builder().name("thename").osTypeId("10").displayText("description").build(), Template.Format.QCOW2, "xen", "http://example.com/", 20, + RegisterTemplateOptions.Builder.accountInDomain("mydomain", "3").bits(32).checksum("ABC").isExtractable(true).isFeatured(true).isPublic(true).passwordEnabled(true).requiresHVM(true))); + + assertRequestLineEquals(httpRequest, registerTemplateOptions.getRequestLine()); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + public void testUpdateTemplate() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "updateTemplate", String.class, UpdateTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17)); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=updateTemplate&id=17 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + public void testUpdateTemplateOptions() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "updateTemplate", String.class, UpdateTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, UpdateTemplateOptions.Builder.bootable(true).displayText("description").format(Template.Format.VHD).name("thename").osTypeId("12").passwordEnabled(true))); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=updateTemplate&id=17&bootable=true&displaytext=description&format=VHD&name=thename&ostypeid=12&passwordenabled=true HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + HttpRequest copyTemplate = HttpRequest.builder().method("GET") + .endpoint("http://localhost:8080/client/api") + .addQueryParam("response", "json") + .addQueryParam("command", "copyTemplate") + .addQueryParam("id", "17") + .addQueryParam("sourcezoneid", "18") + .addQueryParam("destzoneid", "19").build(); + + public void testCopyTemplate() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "copyTemplateToZone", String.class, String.class, String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, 18, 19)); + + assertRequestLineEquals(httpRequest, copyTemplate.getRequestLine()); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + public void testDeleteTemplate() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "deleteTemplate", String.class, DeleteTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17)); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=deleteTemplate&id=17 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + public void testDeleteTemplateOptions() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "deleteTemplate", String.class, DeleteTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, DeleteTemplateOptions.Builder.zoneId("8"))); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=deleteTemplate&id=17&zoneid=8 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + public void testListTemplates() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(TemplateApi.class, "listTemplates"); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=listTemplates&listAll=true&templatefilter=executable HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testListTemplatesOptions() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(TemplateApi.class, "listTemplates", ListTemplatesOptions.class); + GeneratedHttpRequest httpRequest = processor + .createRequest( + method, ImmutableList.<Object> of( + ListTemplatesOptions.Builder.accountInDomain("adrian", "6").hypervisor("xen") + .filter(TemplateFilter.FEATURED))); + + assertRequestLineEquals( + httpRequest, + "GET http://localhost:8080/client/api?response=json&command=listTemplates&listAll=true&account=adrian&domainid=6&hypervisor=xen&templatefilter=featured HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testGetTemplate() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(TemplateApi.class, "getTemplateInZone", String.class, String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5, 1)); + + assertRequestLineEquals( + httpRequest, + "GET http://localhost:8080/client/api?response=json&command=listTemplates&listAll=true&templatefilter=executable&id=5&zoneid=1 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, + Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass()); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, NullOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testUpdateTemplatePermissions() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "updateTemplatePermissions", String.class, UpdateTemplatePermissionsOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17)); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=updateTemplatePermissions&id=17 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, ""); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + public void testUpdateTemplatePermissionsOptions() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "updateTemplatePermissions", String.class, UpdateTemplatePermissionsOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, UpdateTemplatePermissionsOptions.Builder.accounts(ImmutableSet.of("5", "6")).isExtractable(true).isFeatured(true).isPublic(true).op(UpdateTemplatePermissionsOptions.Operation.add))); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=updateTemplatePermissions&id=17&accounts=5,6&isextractable=true&isfeatured=true&ispublic=true&op=add HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, ""); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + public void testListTemplatePermissions() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "listTemplatePermissions", String.class, AccountInDomainOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17)); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=listTemplatePermissions&listAll=true&id=17 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + public void testListTemplatePermissionsOptions() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "listTemplatePermissions", String.class, AccountInDomainOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, AccountInDomainOptions.Builder.accountInDomain("fred", "8"))); + + assertRequestLineEquals(httpRequest, "GET http://localhost:8080/client/api?response=json&command=listTemplatePermissions&listAll=true&id=17&account=fred&domainid=8 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + HttpRequest extractTemplate = HttpRequest.builder().method("GET") + .endpoint("http://localhost:8080/client/api") + .addQueryParam("response", "json") + .addQueryParam("command", "extractTemplate") + .addQueryParam("id", "3") + .addQueryParam("mode", "HTTP_DOWNLOAD") + .addQueryParam("zoneid", "5").build(); + + public void testExtractTemplate() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "extractTemplate", String.class, ExtractMode.class, String.class, ExtractTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, ExtractMode.HTTP_DOWNLOAD, 5)); + + assertRequestLineEquals(httpRequest, extractTemplate.getRequestLine()); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } + + HttpRequest extractTemplateOptions = HttpRequest.builder().method("GET") + .endpoint("http://localhost:8080/client/api") + .addQueryParam("response", "json") + .addQueryParam("command", "extractTemplate") + .addQueryParam("id", "3") + .addQueryParam("mode", "HTTP_DOWNLOAD") + .addQueryParam("zoneid", "5") + .addQueryParam("url", "http%3A//example.com/").build(); + + public void testExtractTemplateOptions() throws NoSuchMethodException { + Invokable<?, ?> method = method(TemplateApi.class, "extractTemplate", String.class, ExtractMode.class, String.class, ExtractTemplateOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, ExtractMode.HTTP_DOWNLOAD, 5, ExtractTemplateOptions.Builder.url("http://example.com/"))); + + assertRequestLineEquals(httpRequest, extractTemplateOptions.getRequestLine()); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/86fd5cf2/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VMGroupApiLiveTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VMGroupApiLiveTest.java b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VMGroupApiLiveTest.java new file mode 100644 index 0000000..3037502 --- /dev/null +++ b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VMGroupApiLiveTest.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jclouds.cloudstack.features; + +import static org.testng.Assert.assertEquals; + +import java.util.Random; +import java.util.Set; + +import org.jclouds.cloudstack.domain.VMGroup; +import org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest; +import org.jclouds.cloudstack.options.ListVMGroupsOptions; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.Test; + +import com.google.common.collect.Iterables; + +/** + * Tests behavior of {@code VMGroupApi} + */ +@Test(groups = "live", singleThreaded = true, testName = "VMGroupApiLiveTest") +public class VMGroupApiLiveTest extends BaseCloudStackApiLiveTest { + + private VMGroup groupCreated; + + public VMGroupApiLiveTest() { + prefix += "2"; + } + + @Test + public void testCreateListDestroyVMGroup() { + VMGroupApi vmGroupClient = client.getVMGroupApi(); + String name = "jclouds-test-" + (Integer.toHexString(new Random().nextInt())); + groupCreated = vmGroupClient.createInstanceGroup(name); + assertEquals(groupCreated.getName(), name); + + Set<VMGroup> search = vmGroupClient.listInstanceGroups(ListVMGroupsOptions.Builder.name(name)); + assertEquals(1, search.size()); + VMGroup groupFound = Iterables.getOnlyElement(search); + assertEquals(groupFound, groupCreated); + + vmGroupClient.deleteInstanceGroup(groupCreated.getId()); + groupCreated = null; + } + + @AfterGroups(groups = "live") + @Override + protected void tearDownContext() { + if (groupCreated != null) { + client.getVMGroupApi().deleteInstanceGroup(groupCreated.getId()); + } + super.tearDownContext(); + } + +} http://git-wip-us.apache.org/repos/asf/stratos/blob/86fd5cf2/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VMGroupApiTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VMGroupApiTest.java b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VMGroupApiTest.java new file mode 100644 index 0000000..b534557 --- /dev/null +++ b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VMGroupApiTest.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jclouds.cloudstack.features; + +import static org.jclouds.reflect.Reflection2.method; + +import java.io.IOException; + +import org.jclouds.Fallbacks.EmptySetOnNotFoundOr404; +import org.jclouds.Fallbacks.NullOnNotFoundOr404; +import org.jclouds.Fallbacks.VoidOnNotFoundOr404; +import org.jclouds.cloudstack.internal.BaseCloudStackApiTest; +import org.jclouds.cloudstack.options.CreateVMGroupOptions; +import org.jclouds.cloudstack.options.ListVMGroupsOptions; +import org.jclouds.cloudstack.options.UpdateVMGroupOptions; +import org.jclouds.fallbacks.MapHttp4xxCodesToExceptions; +import org.jclouds.functions.IdentityFunction; +import org.jclouds.http.functions.ParseFirstJsonValueNamed; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.testng.annotations.Test; + +import com.google.common.base.Functions; +import com.google.common.collect.ImmutableList; +import com.google.common.reflect.Invokable; +/** + * Tests behavior of {@code VMGroupApi} + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "VMGroupApiTest") +public class VMGroupApiTest extends BaseCloudStackApiTest<VMGroupApi> { + + public void testListVMGroups() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VMGroupApi.class, "listInstanceGroups", ListVMGroupsOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=listInstanceGroups&listAll=true HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testListVMGroupsOptions() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VMGroupApi.class, "listInstanceGroups", ListVMGroupsOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListVMGroupsOptions.Builder.account("fred") + .domainId("5").id("6"))); + + assertRequestLineEquals( + httpRequest, + "GET http://localhost:8080/client/api?response=json&command=listInstanceGroups&listAll=true&account=fred&domainid=5&id=6 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testGetVMGroup() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VMGroupApi.class, "getInstanceGroup", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5)); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=listInstanceGroups&listAll=true&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, + Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass()); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, NullOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testCreateVMGroup() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VMGroupApi.class, "createInstanceGroup", String.class, CreateVMGroupOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("goo")); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=createInstanceGroup&name=goo HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testCreateVMGroupOptions() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VMGroupApi.class, "createInstanceGroup", String.class, CreateVMGroupOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("goo", CreateVMGroupOptions.Builder.account("foo").domainId("42"))); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=createInstanceGroup&name=goo&account=foo&domainid=42 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testUpdateVMGroup() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VMGroupApi.class, "updateInstanceGroup", String.class, UpdateVMGroupOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5, UpdateVMGroupOptions.Builder.name("fred"))); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=updateInstanceGroup&id=5&name=fred HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testDeleteVMGroup() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VMGroupApi.class, "deleteInstanceGroup", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5)); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=deleteInstanceGroup&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, ""); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, VoidOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/86fd5cf2/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiExpectTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiExpectTest.java b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiExpectTest.java new file mode 100644 index 0000000..3b8b043 --- /dev/null +++ b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiExpectTest.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jclouds.cloudstack.features; + +import static org.testng.Assert.assertEquals; + +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + +import org.jclouds.cloudstack.CloudStackContext; +import org.jclouds.cloudstack.domain.AsyncCreateResponse; +import org.jclouds.cloudstack.domain.EncryptedPasswordAndPrivateKey; +import org.jclouds.cloudstack.functions.WindowsLoginCredentialsFromEncryptedData; +import org.jclouds.cloudstack.internal.BaseCloudStackExpectTest; +import org.jclouds.encryption.internal.JCECrypto; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.testng.annotations.Test; + +/** + * Test the CloudStack VirtualMachineApiClient + */ +@Test(groups = "unit", testName = "VirtualMachineApiExpectTest") +public class VirtualMachineApiExpectTest extends BaseCloudStackExpectTest<VirtualMachineApi> { + + public void testGetPasswordForVirtualMachineWhenResponseIs2xx() throws NoSuchAlgorithmException, CertificateException { + String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" + + "MIICXgIBAAKBgQDnaPKhTNgw7qPJVp3qsT+7XhhAbip25a0AnUgq8Fb9LPcZk00p\n" + + "jm+m4JrKmDWKZWrHMNBhCNHMzvV9KrAXUMzL4s7mdEicbxTKratTYoyJM7a87bcZ\n" + + "xr+Gtoq4tm031Cix3LKyJUB0iSVU5V/Zx4QcaF5+FWcYMVI26x2Eaz+O7wIDAQAB\n" + + "AoGBAOI8sDkSL6pnJKmKjQkOEQjVjVAwZEOpd+HJ4uxX3DPY6huO7zlZj77Oh4ba\n" + + "GD4duK7VAmRbgwGAtHCSc2XYEN7ICnfkQrm+3Q8nS824Sz21WlzdCxKDFkDcC1wK\n" + + "RjE7SwXN1Kj8Xq8Vpf+z6OzHatSRZD85JM3u0/QCksOJTVIBAkEA9OpycYTuUYjC\n" + + "2pLrO5kkl0nIHbNPvFNZyle19AsHH0z/ClV8DiFtGQpwhqwCoWT0cTmSACPD/quA\n" + + "hdc2mvV+4QJBAPHiBi/7qDpJldLLvK5ALbn1yRaPSDXLccvFV4FkSS9b/2+mOM2a\n" + + "8JkolVCzImxAm0ZZDZeAGKJj1RZDsMIP188CQCfZKWus7DWZ4dI8S0e0IA75czTZ\n" + + "4uRKT3arlLAzRyJhnbFpvThzWdPULgDLZdYqndb6PfYF27LI5q1gGcNWpCECQQCB\n" + + "r8/ldiZyafW8eaQGQT7DD7brM5Nh1FyFBp+uLljW3ZqNADBAfKw3Uf0MsZ7pL5KR\n" + + "GzogWnvaxXAAafahdeEdAkEAzBT+UcxFmcPUO33PnuuiX5KIqThc6aHjjH5O7yzO\n" + + "m4Et9JwQiSgcPBmNY5NKPgmcpvUi9jDylSUV0VUu436RpQ==\n" + + "-----END RSA PRIVATE KEY-----"; + + VirtualMachineApi client = requestSendsResponse( + HttpRequest.builder().method("GET") + .endpoint("http://localhost:8080/client/api?response=json&command=getVMPassword&id=1&apiKey=identity&signature=SVA2r1KRj4yG03rATMLPZWS%2BKnw%3D") + .addHeader("Accept", "application/json") + .build(), + HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/getvmpasswordresponse.json")) + .build()); + + String actual = client.getEncryptedPasswordForVirtualMachine("1"); + String expected = "EFOwm8icZ4sEib4y6ntVHUKHZJQrGBdyPkL1L9lpFHYhs3JfAtL5E5bxBP5Er27bJyOZPjKFcInX\r\n" + + "pQ0LZlQBZDd5/ac0NSoM6tAX3H30pYxNw4t2f9u8aJ48oOEvufgGxTTHnM9qHXD04lt+Ouql6i2q\r\n" + + "HxBqCxFkMZEla3LFieE=\r\n"; + + assertEquals(actual, expected); + + WindowsLoginCredentialsFromEncryptedData passwordDecrypt = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto()); + + assertEquals(passwordDecrypt.apply( + EncryptedPasswordAndPrivateKey.builder().encryptedPassword(actual).privateKey(privateKey).build()).getOptionalPassword().get(), "bX7vvptvw"); + } + + HttpRequest deployVirtualMachineInZone = HttpRequest.builder().method("GET") + .endpoint("http://localhost:8080/client/api") + .addQueryParam("response", "json") + .addQueryParam("command", "deployVirtualMachine") + .addQueryParam("zoneid", "zone1") + .addQueryParam("serviceofferingid", "serviceOffering1") + .addQueryParam("templateid", "template1") + .addQueryParam("apiKey", "identity") + .addQueryParam("signature", "pBjjnTq7/ezN94Uj0gpy2T//cJQ%3D") + .addHeader("Accept", "application/json") + .build(); + + public void testDeployVirtualMachineIs2xxVersion3x() { + HttpResponse deployVirtualMachineInZoneResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/deployvirtualmachineresponse.json")).build(); + VirtualMachineApi client = requestSendsResponse(deployVirtualMachineInZone, deployVirtualMachineInZoneResponse); + + AsyncCreateResponse async = client.deployVirtualMachineInZone("zone1", "serviceOffering1", "template1"); + + assertEquals(async, AsyncCreateResponse.builder().id("1234").jobId("50006").build()); + } + + public void testDeployVirtualMachineIs2xxVersion4x() { + HttpResponse deployVirtualMachineInZoneResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/deployvirtualmachineresponse4x.json")).build(); + VirtualMachineApi client = requestSendsResponse(deployVirtualMachineInZone, deployVirtualMachineInZoneResponse); + + AsyncCreateResponse async = client.deployVirtualMachineInZone("zone1", "serviceOffering1", "template1"); + + assertEquals( + async, + AsyncCreateResponse.builder().id("1cce6cb7-2268-47ff-9696-d9e610f6619a") + .jobId("13330fc9-8b3e-4582-aa3e-90883c041ff0").build()); + } + + @Override + protected VirtualMachineApi clientFrom(CloudStackContext context) { + return context.getApi().getVirtualMachineApi(); + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/86fd5cf2/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiLiveTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiLiveTest.java b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiLiveTest.java new file mode 100644 index 0000000..2ca160c --- /dev/null +++ b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiLiveTest.java @@ -0,0 +1,397 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jclouds.cloudstack.features; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.in; +import static com.google.common.collect.Iterables.find; +import static com.google.common.collect.Iterables.get; +import static com.google.common.collect.Iterables.getFirst; +import static com.google.common.collect.Iterables.getOnlyElement; +import static com.google.common.collect.Sets.filter; +import static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.isDefault; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.logging.Logger; + +import org.jclouds.cloudstack.CloudStackApi; +import org.jclouds.cloudstack.domain.AsyncCreateResponse; +import org.jclouds.cloudstack.domain.AsyncJob; +import org.jclouds.cloudstack.domain.GuestIPType; +import org.jclouds.cloudstack.domain.NIC; +import org.jclouds.cloudstack.domain.Network; +import org.jclouds.cloudstack.domain.NetworkOffering; +import org.jclouds.cloudstack.domain.ServiceOffering; +import org.jclouds.cloudstack.domain.Template; +import org.jclouds.cloudstack.domain.VirtualMachine; +import org.jclouds.cloudstack.domain.Zone; +import org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest; +import org.jclouds.cloudstack.options.CreateNetworkOptions; +import org.jclouds.cloudstack.options.DeployVirtualMachineOptions; +import org.jclouds.cloudstack.options.ListNetworkOfferingsOptions; +import org.jclouds.cloudstack.options.ListNetworksOptions; +import org.jclouds.cloudstack.options.ListTemplatesOptions; +import org.jclouds.cloudstack.options.ListVirtualMachinesOptions; +import org.jclouds.util.InetAddresses2; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Throwables; +import com.google.common.collect.ComparisonChain; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.collect.Maps; +import com.google.common.collect.Ordering; +import com.google.common.net.HostAndPort; +import com.google.common.net.HostSpecifier; + +/** + * Tests behavior of {@code VirtualMachineApiLiveTest} + */ +@Test(groups = "live", singleThreaded = true, testName = "VirtualMachineApiLiveTest") +public class VirtualMachineApiLiveTest extends BaseCloudStackApiLiveTest { + private static final Logger logger = Logger.getAnonymousLogger(); + + private VirtualMachine vm = null; + + static final Ordering<ServiceOffering> DEFAULT_SIZE_ORDERING = new Ordering<ServiceOffering>() { + public int compare(ServiceOffering left, ServiceOffering right) { + return ComparisonChain.start().compare(left.getCpuNumber(), right.getCpuNumber()) + .compare(left.getMemory(), right.getMemory()).result(); + } + }; + + public static VirtualMachine createVirtualMachine(CloudStackApi client, String defaultTemplate, + Predicate<String> jobComplete, Predicate<VirtualMachine> virtualMachineRunning) { + Set<Network> networks = client.getNetworkApi().listNetworks(isDefault(true)); + if (!networks.isEmpty()) { + Network network = get(filter(networks, new Predicate<Network>() { + @Override + public boolean apply(Network network) { + return network != null && network.getState().equals("Implemented"); + } + }), 0); + return createVirtualMachineInNetwork(network, + defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), client, jobComplete, + virtualMachineRunning); + } else { + String zoneId = find(client.getZoneApi().listZones(), new Predicate<Zone>() { + + @Override + public boolean apply(Zone arg0) { + return arg0.isSecurityGroupsEnabled(); + } + + }).getId(); + return createVirtualMachineWithSecurityGroupInZone(zoneId, + defaultTemplateOrPreferredInZone(defaultTemplate, client, zoneId), + get(client.getSecurityGroupApi().listSecurityGroups(), 0).getId(), client, jobComplete, + virtualMachineRunning); + } + } + + public static VirtualMachine createVirtualMachineWithSecurityGroupInZone(String zoneId, String templateId, String groupId, + CloudStackApi client, Predicate<String> jobComplete, + Predicate<VirtualMachine> virtualMachineRunning) { + return createVirtualMachineWithOptionsInZone(new DeployVirtualMachineOptions().securityGroupId(groupId), zoneId, + templateId, client, jobComplete, virtualMachineRunning); + } + + public static VirtualMachine createVirtualMachineInNetwork(Network network, String templateId, + CloudStackApi client, Predicate<String> jobComplete, + Predicate<VirtualMachine> virtualMachineRunning) { + DeployVirtualMachineOptions options = new DeployVirtualMachineOptions(); + String zoneId = network.getZoneId(); + options.networkId(network.getId()); + return createVirtualMachineWithOptionsInZone(options, zoneId, templateId, client, jobComplete, + virtualMachineRunning); + } + + public static VirtualMachine createVirtualMachineInNetworkWithIp( + CloudStackApi client, String templateId, Set<Network> networks, Map<String, String> ipToNetwork, + Predicate<String> jobComplete, Predicate<VirtualMachine> virtualMachineRunning) { + + DeployVirtualMachineOptions options = new DeployVirtualMachineOptions(); + + String zoneId = getFirst(networks, null).getZoneId(); + options.networkIds(Iterables.transform(networks, new Function<Network, String>() { + @Override + public String apply(Network network) { + return network.getId(); + } + })); + options.ipsToNetworks(ipToNetwork); + + return createVirtualMachineWithOptionsInZone(options, zoneId, templateId, + client, jobComplete, virtualMachineRunning); + } + + public static VirtualMachine createVirtualMachineWithOptionsInZone(DeployVirtualMachineOptions options, String zoneId, + String templateId, CloudStackApi client, Predicate<String> jobComplete, + Predicate<VirtualMachine> virtualMachineRunning) { + String serviceOfferingId = DEFAULT_SIZE_ORDERING.min(client.getOfferingApi().listServiceOfferings()).getId(); + + System.out.printf("serviceOfferingId %s, templateId %s, zoneId %s, options %s%n", serviceOfferingId, templateId, + zoneId, options); + AsyncCreateResponse job = client.getVirtualMachineApi().deployVirtualMachineInZone(zoneId, serviceOfferingId, + templateId, options); + assertTrue(jobComplete.apply(job.getJobId())); + AsyncJob<VirtualMachine> jobWithResult = client.getAsyncJobApi().<VirtualMachine> getAsyncJob(job.getJobId()); + if (jobWithResult.getError() != null) + Throwables.propagate(new ExecutionException(String.format("job %s failed with exception %s", job.getId(), + jobWithResult.getError().toString())) { + }); + VirtualMachine vm = jobWithResult.getResult(); + if (vm.isPasswordEnabled()) { + assert vm.getPassword() != null : vm; + } + assertTrue(virtualMachineRunning.apply(vm)); + assertEquals(vm.getServiceOfferingId(), serviceOfferingId); + assertEquals(vm.getTemplateId(), templateId); + assertEquals(vm.getZoneId(), zoneId); + return vm; + } + + @Test + public void testCreateVirtualMachine() throws Exception { + String defaultTemplate = template != null ? template.getImageId() : null; + vm = createVirtualMachine(client, defaultTemplate, jobComplete, virtualMachineRunning); + if (vm.getPassword() != null) { + conditionallyCheckSSH(); + } + assert in(ImmutableSet.of("ROOT", "NetworkFilesystem", "IscsiLUN", "VMFS", "PreSetup")) + .apply(vm.getRootDeviceType()) : vm; + checkVm(vm); + } + + @Test + public void testCreateVirtualMachineWithSpecificIp() throws Exception { + skipIfNotGlobalAdmin(); + + String defaultTemplate = template != null ? template.getImageId() : null; + Network network = null; + + try { + Template template = getOnlyElement( + client.getTemplateApi().listTemplates(ListTemplatesOptions.Builder.id(defaultTemplate))); + logger.info("Using template: " + template); + + Set<Network> allSafeNetworksInZone = adminClient.getNetworkApi().listNetworks( + ListNetworksOptions.Builder.zoneId(template.getZoneId()).isSystem(false)); + for (Network net : allSafeNetworksInZone) { + if (net.getName().equals(prefix + "-ip-network")) { + logger.info("Deleting VMs in network: " + net); + + Set<VirtualMachine> machinesInNetwork = adminClient.getVirtualMachineApi().listVirtualMachines( + ListVirtualMachinesOptions.Builder.networkId(net.getId())); + + for (VirtualMachine machine : machinesInNetwork) { + if (machine.getState().equals(VirtualMachine.State.RUNNING)) { + logger.info("Deleting VM: " + machine); + destroyMachine(machine); + } + } + + assertTrue(adminJobComplete.apply( + adminClient.getNetworkApi().deleteNetwork(net.getId())), net.toString()); + } + } + + NetworkOffering offering = getFirst( + client.getOfferingApi().listNetworkOfferings( + ListNetworkOfferingsOptions.Builder.zoneId(template.getZoneId()).specifyVLAN(true)), null); + checkNotNull(offering, "No network offering found"); + logger.info("Using network offering: " + offering); + + network = adminClient.getNetworkApi().createNetworkInZone( + template.getZoneId(), offering.getId(), prefix + "-ip-network", "", + CreateNetworkOptions.Builder.startIP("192.168.0.1").endIP("192.168.0.5") + .netmask("255.255.255.0").gateway("192.168.0.1").vlan("21")); + logger.info("Created network: " + network); + + Network requiredNetwork = getOnlyElement(filter(adminClient.getNetworkApi().listNetworks( + ListNetworksOptions.Builder.zoneId(template.getZoneId())), new Predicate<Network>() { + @Override + public boolean apply(Network network) { + return network.isDefault() && + network.getGuestIPType() == GuestIPType.VIRTUAL; + } + })); + logger.info("Required network: " + requiredNetwork); + + String ipAddress = "192.168.0.4"; + + Map<String, String> ipsToNetworks = Maps.newHashMap(); + ipsToNetworks.put(ipAddress, network.getId()); + + vm = createVirtualMachineInNetworkWithIp( + adminClient, defaultTemplate, ImmutableSet.of(requiredNetwork, network), + ipsToNetworks, adminJobComplete, adminVirtualMachineRunning); + logger.info("Created VM: " + vm); + + boolean hasStaticIpNic = false; + for (NIC nic : vm.getNICs()) { + if (nic.getNetworkId() == network.getId()) { + hasStaticIpNic = true; + assertEquals(nic.getIPAddress(), ipAddress); + } + } + assert hasStaticIpNic; + checkVm(vm); + + } finally { + if (vm != null) { + destroyMachine(vm); + vm = null; + } + if (network != null) { + String jobId = adminClient.getNetworkApi().deleteNetwork(network.getId()); + adminJobComplete.apply(jobId); + network = null; + } + } + } + + private void destroyMachine(VirtualMachine virtualMachine) { + assertTrue(adminJobComplete.apply( + adminClient.getVirtualMachineApi().destroyVirtualMachine(virtualMachine.getId())), virtualMachine.toString()); + assertTrue(adminVirtualMachineDestroyed.apply(virtualMachine)); + } + + private void conditionallyCheckSSH() { + if (vm.getPassword() != null && !loginCredentials.getOptionalPassword().isPresent()) + loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build(); + assert HostSpecifier.isValid(vm.getIPAddress()); + if (!InetAddresses2.isPrivateIPAddress(vm.getIPAddress())) { + // not sure if the network is public or not, so we have to test + HostAndPort socket = HostAndPort.fromParts(vm.getIPAddress(), 22); + System.err.printf("testing socket %s%n", socket); + System.err.printf("testing ssh %s%n", socket); + checkSSH(socket); + } else { + System.err.printf("skipping ssh %s, as private%n", vm.getIPAddress()); + } + } + + @Test(dependsOnMethods = "testCreateVirtualMachine") + public void testLifeCycle() throws Exception { + String job = client.getVirtualMachineApi().stopVirtualMachine(vm.getId()); + assertTrue(jobComplete.apply(job)); + vm = client.getVirtualMachineApi().getVirtualMachine(vm.getId()); + assertEquals(vm.getState(), VirtualMachine.State.STOPPED); + + if (vm.isPasswordEnabled()) { + job = client.getVirtualMachineApi().resetPasswordForVirtualMachine(vm.getId()); + assertTrue(jobComplete.apply(job)); + vm = client.getAsyncJobApi().<VirtualMachine> getAsyncJob(job).getResult(); + if (vm.getPassword() != null) { + conditionallyCheckSSH(); + } + } + + job = client.getVirtualMachineApi().startVirtualMachine(vm.getId()); + assertTrue(jobComplete.apply(job)); + vm = client.getVirtualMachineApi().getVirtualMachine(vm.getId()); + assertEquals(vm.getState(), VirtualMachine.State.RUNNING); + + job = client.getVirtualMachineApi().rebootVirtualMachine(vm.getId()); + assertTrue(jobComplete.apply(job)); + vm = client.getVirtualMachineApi().getVirtualMachine(vm.getId()); + assertEquals(vm.getState(), VirtualMachine.State.RUNNING); + } + + @AfterGroups(groups = "live") + @Override + protected void tearDownContext() { + if (vm != null) { + destroyMachine(vm); + vm = null; + } + super.tearDownContext(); + } + + @Test + public void testListVirtualMachines() throws Exception { + Set<VirtualMachine> response = client.getVirtualMachineApi().listVirtualMachines(); + assert null != response; + assertTrue(response.size() >= 0); + for (VirtualMachine vm : response) { + VirtualMachine newDetails = getOnlyElement(client.getVirtualMachineApi().listVirtualMachines( + ListVirtualMachinesOptions.Builder.id(vm.getId()))); + assertEquals(vm.getId(), newDetails.getId()); + checkVm(vm); + } + } + + protected void checkVm(VirtualMachine vm) { + assertEquals(vm.getId(), client.getVirtualMachineApi().getVirtualMachine(vm.getId()).getId()); + assert vm.getId() != null : vm; + assert vm.getName() != null : vm; + // vm.getDisplayName() can be null, so skip that check. + assert vm.getAccount() != null : vm; + assert vm.getDomain() != null : vm; + assert vm.getDomainId() != null : vm; + assert vm.getCreated() != null : vm; + assert vm.getState() != null : vm; + assert vm.getZoneId() != null : vm; + assert vm.getZoneName() != null : vm; + assert vm.getTemplateId() != null : vm; + assert vm.getTemplateName() != null : vm; + assert vm.getServiceOfferingId() != null : vm; + assert vm.getServiceOfferingName() != null : vm; + assert vm.getCpuCount() > 0 : vm; + assert vm.getCpuSpeed() > 0 : vm; + assert vm.getMemory() > 0 : vm; + assert vm.getGuestOSId() != null : vm; + assert vm.getRootDeviceId() != null : vm; + // assert vm.getRootDeviceType() != null : vm; + if (vm.getJobId() != null) + assert vm.getJobStatus() != null : vm; + assert vm.getNICs() != null && !vm.getNICs().isEmpty() : vm; + for (NIC nic : vm.getNICs()) { + assert nic.getId() != null : vm; + assert nic.getNetworkId() != null : vm; + assert nic.getTrafficType() != null : vm; + assert nic.getGuestIPType() != null : vm; + switch (vm.getState()) { + case RUNNING: + assert nic.getNetmask() != null : vm; + assert nic.getGateway() != null : vm; + assert nic.getIPAddress() != null : vm; + break; + case STARTING: + assert nic.getNetmask() == null : vm; + assert nic.getGateway() == null : vm; + assert nic.getIPAddress() == null : vm; + break; + default: + assert nic.getNetmask() != null : vm; + assert nic.getGateway() != null : vm; + assert nic.getIPAddress() != null : vm; + } + + } + assert vm.getSecurityGroups() != null && vm.getSecurityGroups().size() >= 0 : vm; + assert vm.getHypervisor() != null : vm; + } +} http://git-wip-us.apache.org/repos/asf/stratos/blob/86fd5cf2/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiTest.java ---------------------------------------------------------------------- diff --git a/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiTest.java b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiTest.java new file mode 100644 index 0000000..c06c08b --- /dev/null +++ b/dependencies/jclouds/apis/cloudstack/1.8.0-stratos/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiTest.java @@ -0,0 +1,259 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jclouds.cloudstack.features; + +import static org.jclouds.reflect.Reflection2.method; + +import java.io.IOException; + +import org.jclouds.Fallbacks.EmptySetOnNotFoundOr404; +import org.jclouds.Fallbacks.NullOnNotFoundOr404; +import org.jclouds.fallbacks.MapHttp4xxCodesToExceptions; +import org.jclouds.cloudstack.internal.BaseCloudStackApiTest; +import org.jclouds.cloudstack.options.AssignVirtualMachineOptions; +import org.jclouds.cloudstack.options.ListVirtualMachinesOptions; +import org.jclouds.cloudstack.options.StopVirtualMachineOptions; +import org.jclouds.functions.IdentityFunction; +import org.jclouds.http.functions.ParseFirstJsonValueNamed; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.testng.annotations.Test; + +import com.google.common.base.Functions; +import com.google.common.collect.ImmutableList; +import com.google.common.reflect.Invokable; +/** + * Tests behavior of {@code VirtualMachineApi} + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "VirtualMachineApiTest") +public class VirtualMachineApiTest extends BaseCloudStackApiTest<VirtualMachineApi> { + public void testListVirtualMachines() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "listVirtualMachines", + ListVirtualMachinesOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=listVirtualMachines&listAll=true HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testListVirtualMachinesOptions() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "listVirtualMachines", + ListVirtualMachinesOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of( + ListVirtualMachinesOptions.Builder.accountInDomain("adrian", "6").usesVirtualNetwork(true))); + + assertRequestLineEquals( + httpRequest, + "GET http://localhost:8080/client/api?response=json&command=listVirtualMachines&listAll=true&account=adrian&domainid=6&forvirtualnetwork=true HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testGetVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "getVirtualMachine", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5)); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=listVirtualMachines&listAll=true&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, + Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass()); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, NullOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testRebootVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "rebootVirtualMachine", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5)); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=rebootVirtualMachine&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testStartVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "startVirtualMachine", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5)); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=startVirtualMachine&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testStopVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "stopVirtualMachine", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("5")); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=stopVirtualMachine&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testStopVirtualMachineForced() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "stopVirtualMachine", String.class, + StopVirtualMachineOptions.class); + + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("5", + StopVirtualMachineOptions.Builder.forced(true))); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=stopVirtualMachine&id=5&forced=true HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testResetPasswordForVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "resetPasswordForVirtualMachine", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5)); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=resetPasswordForVirtualMachine&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testChangeServiceForVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "changeServiceForVirtualMachine", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5)); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=changeServiceForVirtualMachine&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testUpdateVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "updateVirtualMachine", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5)); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=updateVirtualMachine&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } + + public void testDestroyVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "destroyVirtualMachine", String.class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5)); + + assertRequestLineEquals(httpRequest, + "GET http://localhost:8080/client/api?response=json&command=destroyVirtualMachine&id=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, NullOnNotFoundOr404.class); + + checkFilters(httpRequest); + + } + + public void testAssignVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Invokable<?, ?> method = method(VirtualMachineApi.class, "assignVirtualMachine", String.class, + AssignVirtualMachineOptions[].class); + GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("abcd", + AssignVirtualMachineOptions.Builder.accountInDomain("adrian", "6"))); + + assertRequestLineEquals( + httpRequest, + "GET http://localhost:8080/client/api?response=json&command=assignVirtualMachine&virtualmachineid=abcd&account=adrian&domainid=6 HTTP/1.1"); + assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); + assertPayloadEquals(httpRequest, null, null, false); + + assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class); + assertSaxResponseParserClassEquals(method, null); + assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(httpRequest); + + } +}
