Better error checking and logging in test tear down/clean up methods

This commit is contained in:
Andrew Donald Kennedy 2012-04-11 12:12:01 +01:00
parent 98a89aa68d
commit b786178a90
15 changed files with 172 additions and 108 deletions

View File

@ -18,6 +18,8 @@
*/
package org.jclouds.vcloud.director.v1_5.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
@ -34,7 +36,7 @@ import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* Test a {@link Task} to see if it has succeeded.
* Test a {@link Task} status is in a particular set of {@link Task.Status statuses}.
*
* @author grkvlt@apache.org
*/
@ -61,6 +63,7 @@ public class TaskStatusEquals implements Predicate<Task> {
/** @see Predicate#apply(Object) */
@Override
public boolean apply(Task task) {
checkNotNull(task, "task");
logger.trace("looking for status on task %s", task);
// TODO shouldn't we see if it's already done before getting it from API server?

View File

@ -18,6 +18,10 @@
*/
package org.jclouds.vcloud.director.v1_5.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.EnumSet;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Singleton;
@ -30,7 +34,7 @@ import org.jclouds.vcloud.director.v1_5.features.TaskClient;
import com.google.common.base.Predicate;
/**
* Test a {@link Task} to see if it has succeeded.
* Test a {@link Task} to see if it has {@link Task.Status#SUCCESS succeeded}.
*
* @author grkvlt@apache.org
*/
@ -50,21 +54,19 @@ public class TaskSuccess implements Predicate<Task> {
/** @see Predicate#apply(Object) */
@Override
public boolean apply(Task task) {
logger.trace("looking for status on task %s", task);
checkNotNull(task, "task");
logger.trace("looking for status on task %s", task.getOperationName());
// TODO shouldn't we see if it's already done before getting it from API server?
task = taskClient.getTask(task.getHref());
// perhaps task isn't available, yet
if (task == null) return false;
logger.trace("%s: looking for status %s: currently: %s", task, Task.Status.SUCCESS, task.getStatus());
if (task.getStatus().equals(Task.Status.ERROR))
logger.trace("%s: looking for status %s: currently: %s", task.getOperationName(), Task.Status.SUCCESS, task.getStatus());
if (EnumSet.of(Task.Status.ERROR, Task.Status.CANCELED, Task.Status.ABORTED).contains(task.getStatus())) {
throw new VCloudDirectorException(task);
if (task.getStatus().equals(Task.Status.CANCELED))
throw new VCloudDirectorException(task);
if (task.getStatus().equals(Task.Status.ABORTED))
throw new VCloudDirectorException(task);
return task.getStatus().equals(Task.Status.SUCCESS);
} else return task.getStatus().equals(Task.Status.SUCCESS);
}
@Override

View File

@ -582,6 +582,8 @@ public class Checks {
}
public static void checkVmPendingQuestion(VmPendingQuestion question) {
assertNotNull(question, String.format(NOT_NULL_OBJ_FMT, "VmPendingQuestion"));
// Check required fields
assertNotNull(question.getQuestion(), String.format(OBJ_FIELD_REQ, "VmPendingQuestion", "Question"));
assertNotNull(question.getQuestionId(), String.format(OBJ_FIELD_REQ, "VmPendingQuestion", "QuestionId"));

View File

@ -25,7 +25,6 @@ import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.O
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.REF_REQ_LIVE;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.TASK_COMPLETE_TIMELY;
import static org.jclouds.vcloud.director.v1_5.domain.Checks.checkCatalogItem;
import static org.jclouds.vcloud.director.v1_5.domain.Checks.checkError;
import static org.jclouds.vcloud.director.v1_5.domain.Checks.checkMetadata;
import static org.jclouds.vcloud.director.v1_5.domain.Checks.checkMetadataValue;
import static org.jclouds.vcloud.director.v1_5.domain.Checks.checkTask;
@ -35,9 +34,7 @@ import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.jclouds.vcloud.director.v1_5.VCloudDirectorException;
import org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType;
import org.jclouds.vcloud.director.v1_5.domain.AdminCatalog;
import org.jclouds.vcloud.director.v1_5.domain.CatalogItem;
@ -112,22 +109,29 @@ public class CatalogClientLiveTest extends BaseVCloudDirectorClientLiveTest {
@AfterClass(alwaysRun = true)
public void tearDown() {
if (catalogItem != null)
catalogClient.deleteCatalogItem(catalogItem.getHref());
if (media != null)
context.getApi().getMediaClient().deleteMedia(media.getHref());
if (adminCatalog != null) {
adminContext.getApi().getCatalogClient().deleteCatalog(adminCatalog.getHref());
if (catalogItem != null) {
try {
catalogClient.getCatalog(catalogRef.getHref());
fail("The Catalog should have been deleted");
} catch (VCloudDirectorException vcde) {
checkError(vcde.getError());
assertEquals(vcde.getError().getMajorErrorCode(), Integer.valueOf(403), "The majorErrorCode should be 403 since the item has been deleted");
catalogClient.deleteCatalogItem(catalogItem.getHref());
} catch (Exception e) {
logger.warn(e, "Error when deleting catalog item '%s'", catalogItem.getName());
}
}
if (media != null) {
try {
Task delete = context.getApi().getMediaClient().deleteMedia(media.getHref());
taskDoneEventually(delete);
} catch (Exception e) {
logger.warn(e, "Error when deleting media '%s'", media.getName());
}
}
if (adminContext != null && adminCatalog != null) {
try {
adminContext.getApi().getCatalogClient().deleteCatalog(adminCatalog.getHref());
} catch (Exception e) {
logger.warn(e, "Error when deleting catalog '%s'", adminCatalog.getName());
}
}
// TODO wait for tasks
}
@Test(description = "GET /catalog/{id}")

View File

@ -42,18 +42,15 @@ import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Set;
import org.jclouds.io.Payloads;
import org.jclouds.vcloud.director.v1_5.VCloudDirectorException;
import org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType;
import org.jclouds.vcloud.director.v1_5.domain.Checks;
import org.jclouds.vcloud.director.v1_5.domain.CloneMediaParams;
import org.jclouds.vcloud.director.v1_5.domain.Error;
import org.jclouds.vcloud.director.v1_5.domain.File;
import org.jclouds.vcloud.director.v1_5.domain.Link;
import org.jclouds.vcloud.director.v1_5.domain.Media;
@ -108,10 +105,20 @@ public class MediaClientLiveTest extends BaseVCloudDirectorClientLiveTest {
@AfterClass(alwaysRun = true)
protected void tidyUp() {
if (media != null) {
assertTaskSucceeds(mediaClient.deleteMedia(media.getHref()));
try {
Task delete = mediaClient.deleteMedia(media.getHref());
taskDoneEventually(delete);
} catch (Exception e) {
logger.warn(e, "Error when deleting media '%s': %s", media.getName());
}
}
if (oldMedia != null) {
assertTaskSucceeds(mediaClient.deleteMedia(oldMedia.getHref()));
try {
Task delete = mediaClient.deleteMedia(oldMedia.getHref());
taskDoneEventually(delete);
} catch (Exception e) {
logger.warn(e, "Error when deleting media '%s': %s", oldMedia.getName());
}
}
}

View File

@ -36,6 +36,7 @@ import org.jclouds.vcloud.director.v1_5.domain.MetadataEntry;
import org.jclouds.vcloud.director.v1_5.domain.MetadataValue;
import org.jclouds.vcloud.director.v1_5.domain.Network;
import org.jclouds.vcloud.director.v1_5.domain.OrgNetwork;
import org.jclouds.vcloud.director.v1_5.domain.Task;
import org.jclouds.vcloud.director.v1_5.internal.BaseVCloudDirectorClientLiveTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
@ -67,10 +68,14 @@ public class NetworkClientLiveTest extends BaseVCloudDirectorClientLiveTest {
}
@AfterClass(alwaysRun = true)
public void cleanUp() throws Exception {
public void cleanUp() {
if (metadataSet) {
adminContext.getApi().getNetworkClient().getMetadataClient()
.deleteMetadataEntry(toAdminUri(networkURI), "key");
try {
Task delete = adminContext.getApi().getNetworkClient().getMetadataClient().deleteMetadataEntry(toAdminUri(networkURI), "key");
taskDoneEventually(delete);
} catch (Exception e) {
logger.warn(e, "Error when deleting metadata");
}
}
}

View File

@ -40,6 +40,7 @@ import org.jclouds.vcloud.director.v1_5.domain.MetadataValue;
import org.jclouds.vcloud.director.v1_5.domain.Org;
import org.jclouds.vcloud.director.v1_5.domain.OrgList;
import org.jclouds.vcloud.director.v1_5.domain.Reference;
import org.jclouds.vcloud.director.v1_5.domain.Task;
import org.jclouds.vcloud.director.v1_5.internal.BaseVCloudDirectorClientLiveTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
@ -73,11 +74,17 @@ public class OrgClientLiveTest extends BaseVCloudDirectorClientLiveTest {
@AfterClass(alwaysRun = true)
public void cleanUp() throws Exception {
if (adminMembersSet) {
adminContext.getApi().getOrgClient().getMetadataClient()
.deleteMetadataEntry(toAdminUri(orgURI), "KEY");
adminContext.getApi().getCatalogClient()
.deleteCatalog(catalogRef);
try {
Task delete = adminContext.getApi().getOrgClient().getMetadataClient().deleteMetadataEntry(toAdminUri(orgURI), "KEY");
taskDoneEventually(delete);
} catch (Exception e) {
logger.warn(e, "Error when deleting metadata entry");
}
try {
adminContext.getApi().getCatalogClient().deleteCatalog(catalogRef);
} catch (Exception e) {
logger.warn(e, "Error when deleting catalog'%s': %s", catalogRef);
}
}
}

View File

@ -76,9 +76,7 @@ public class QueryClientLiveTest extends BaseVCloudDirectorClientLiveTest {
@AfterClass(alwaysRun = true)
public void cleanUp() throws Exception {
if (vApp != null) {
cleanUpVApp(vApp);
}
if (vApp != null) cleanUpVApp(vApp);
}
@Override

View File

@ -134,46 +134,46 @@ public class VAppClientLiveTest extends AbstractVAppClientLiveTest {
private MetadataValue metadataValue;
private String key;
private URI mediaURI;
private URI testUserURI;
private boolean mediaCreated = false;
private boolean testUserCreated = false;
@Override
@BeforeClass(alwaysRun = true)
protected void setupRequiredClients() {
super.setupRequiredClients();
@BeforeClass(alwaysRun = true, dependsOnMethods = { "setupRequiredClients" })
protected void setupRequiredEntities() {
Set<Link> links = vdcClient.getVdc(vdcURI).getLinks();
Predicate<Link> addMediaLink = and(relEquals("add"), typeEquals(VCloudDirectorMediaType.MEDIA));
if (contains(links, addMediaLink)) {
Link addMedia = find(links, addMediaLink);
byte[] iso = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
if (mediaURI == null) {
Predicate<Link> addMediaLink = and(relEquals(Link.Rel.ADD), typeEquals(VCloudDirectorMediaType.MEDIA));
Media sourceMedia = Media.builder()
.type(VCloudDirectorMediaType.MEDIA)
.name("Test media "+random.nextInt())
.size(iso.length)
.imageType(Media.ImageType.ISO)
.description("Test media generated by vAppClientLiveTest")
.build();
Media media = context.getApi().getMediaClient().createMedia(addMedia.getHref(), sourceMedia);
if (contains(links, addMediaLink)) {
Link addMedia = find(links, addMediaLink);
byte[] iso = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
Link uploadLink = getFirst(getFirst(media.getFiles(), null).getLinks(), null);
context.getApi().getUploadClient().upload(uploadLink.getHref(), Payloads.newByteArrayPayload(iso));
Media sourceMedia = Media.builder()
.type(VCloudDirectorMediaType.MEDIA)
.name("Test media "+random.nextInt())
.size(iso.length)
.imageType(Media.ImageType.ISO)
.description("Test media generated by vAppClientLiveTest")
.build();
Media media = context.getApi().getMediaClient().createMedia(addMedia.getHref(), sourceMedia);
media = context.getApi().getMediaClient().getMedia(media.getHref());
Link uploadLink = getFirst(getFirst(media.getFiles(), null).getLinks(), null);
context.getApi().getUploadClient().upload(uploadLink.getHref(), Payloads.newByteArrayPayload(iso));
if (media.getTasks().size() == 1) {
Task uploadTask = Iterables.getOnlyElement(media.getTasks());
Checks.checkTask(uploadTask);
assertEquals(uploadTask.getStatus(), Task.Status.RUNNING);
assertTrue(retryTaskSuccess.apply(uploadTask), String.format(TASK_COMPLETE_TIMELY, "uploadTask"));
media = context.getApi().getMediaClient().getMedia(media.getHref());
}
mediaURI = media.getHref();
} else {
mediaURI = super.mediaURI;
if (media.getTasks().size() == 1) {
Task uploadTask = Iterables.getOnlyElement(media.getTasks());
Checks.checkTask(uploadTask);
assertEquals(uploadTask.getStatus(), Task.Status.RUNNING);
assertTrue(retryTaskSuccess.apply(uploadTask), String.format(TASK_COMPLETE_TIMELY, "uploadTask"));
media = context.getApi().getMediaClient().getMedia(media.getHref());
}
mediaURI = media.getHref();
mediaCreated = true;
}
}
if (adminContext != null) {
@ -187,8 +187,20 @@ public class VAppClientLiveTest extends AbstractVAppClientLiveTest {
@Override
@AfterClass(alwaysRun = true)
public void cleanUp() {
if (adminContext != null && mediaURI != null) {
assertTaskDoneEventually(context.getApi().getMediaClient().deleteMedia(mediaURI));
if (adminContext != null && mediaCreated && mediaURI != null) {
try {
Task delete = context.getApi().getMediaClient().deleteMedia(mediaURI);
taskDoneEventually(delete);
} catch (Exception e) {
logger.warn("Error when deleting media: %s", e.getMessage());
}
}
if (adminContext != null && testUserCreated && testUserURI != null) {
try {
adminContext.getApi().getUserClient().deleteUser(testUserURI);
} catch (Exception e) {
logger.warn("Error when deleting user: %s", e.getMessage());
}
}
}

View File

@ -93,7 +93,12 @@ public class VAppTemplateClientLiveTest extends AbstractVAppClientLiveTest {
@AfterClass(alwaysRun = true)
protected void tidyUp() {
if (key != null) {
assertTaskSucceeds(vAppTemplateClient.getMetadataClient().deleteMetadataEntry(vAppTemplateURI, key));
try {
Task delete = vAppTemplateClient.getMetadataClient().deleteMetadataEntry(vAppTemplateURI, key);
taskDoneEventually(delete);
} catch (Exception e) {
logger.warn(e, "Error when deleting metadata entry '%s'", key);
}
}
}

View File

@ -118,8 +118,12 @@ public class VdcClientLiveTest extends BaseVCloudDirectorClientLiveTest {
}
if (metadataSet) {
adminContext.getApi().getVdcClient().getMetadataClient()
.deleteMetadataEntry(toAdminUri(vdcURI), "key");
try {
Task delete = adminContext.getApi().getVdcClient().getMetadataClient().deleteMetadataEntry(toAdminUri(vdcURI), "key");
taskDoneEventually(delete);
} catch (Exception e) {
logger.warn(e, "Error deleting metadata entry");
}
}
}

View File

@ -83,13 +83,10 @@ public class AdminCatalogClientLiveTest extends BaseVCloudDirectorClientLiveTest
@AfterClass(alwaysRun = true)
protected void tidyUp() {
if (catalog != null) {
catalogClient.deleteCatalog(catalog.getHref());
try { //TODO: predicate to retry for a short while?
catalogClient.getCatalog(catalog.getHref());
fail("The Catalog should have been deleted");
} catch (VCloudDirectorException vcde) {
checkError(vcde.getError());
assertEquals(vcde.getError().getMajorErrorCode(), Integer.valueOf(403), "The majorErrorCode should be 403 since the item has been deleted");
try {
catalogClient.deleteCatalog(catalog.getHref());
} catch (Exception e) {
logger.warn(e, "Error deleting admin catalog '%s'", catalog.getName());
}
}
}

View File

@ -75,7 +75,7 @@ public class AdminVdcClientLiveTest extends BaseVCloudDirectorClientLiveTest {
if (metadataKey != null) {
try {
Task task = metadataClient.deleteMetadataEntry(adminVdcUri, metadataKey);
assertTaskSucceeds(task);
taskDoneEventually(task);
} catch (VCloudDirectorException e) {
logger.warn(e, "Error deleting metadata-value (perhaps it doesn't exist?); continuing...");
}

View File

@ -30,7 +30,6 @@ import static org.testng.AssertJUnit.assertFalse;
import java.net.URI;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.vcloud.director.v1_5.VCloudDirectorException;
import org.jclouds.vcloud.director.v1_5.domain.OrgPasswordPolicySettings;
import org.jclouds.vcloud.director.v1_5.domain.Reference;
import org.jclouds.vcloud.director.v1_5.domain.Role.DefaultRoles;
@ -77,8 +76,8 @@ public class UserClientLiveTest extends BaseVCloudDirectorClientLiveTest {
if (user != null) {
try {
userClient.deleteUser(user.getHref());
} catch (VCloudDirectorException e) {
// ignore; user probably already deleted
} catch (Exception e) {
logger.warn(e, "Error deleting user '%s'", user.getName());
}
}
}
@ -177,11 +176,13 @@ public class UserClientLiveTest extends BaseVCloudDirectorClientLiveTest {
assertTrue(settings.isAccountLockoutEnabled());
for (int i=0; i<settings.getInvalidLoginsBeforeLockout()+1; i++) {
for (int i = 0; i < settings.getInvalidLoginsBeforeLockout() + 1; i++) {
try {
sessionClient.loginUserInOrgWithPassword(URI.create(endpoint + "/sessions"), user.getName(), orgRef.getName(), "wrongpassword!");
fail("Managed to login using the wrong password!");
} catch(AuthorizationException ex) {
} catch (AuthorizationException e) {
} catch (Exception e) {
fail("Expected AuthorizationException", e);
}
}
@ -191,7 +192,9 @@ public class UserClientLiveTest extends BaseVCloudDirectorClientLiveTest {
try {
sessionClient.loginUserInOrgWithPassword(URI.create(endpoint + "/sessions"), user.getName(), orgRef.getName(), "newPassword");
fail("Managed to login to locked account!");
} catch(AuthorizationException ex) {
} catch (AuthorizationException e) {
} catch (Exception e) {
fail("Expected AuthorizationException", e);
}
userClient.unlockUser(user.getHref());

View File

@ -303,21 +303,31 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseVersionedServ
assertTrue(retryTaskSuccessLong.apply(task), String.format(TASK_COMPLETE_TIMELY, task));
}
protected void assertTaskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) {
protected boolean taskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) {
TaskClient taskClient = context.getApi().getTaskClient();
TaskStatusEquals predicate = new TaskStatusEquals(taskClient, running, immutableSet);
RetryablePredicate<Task> retryablePredicate = new RetryablePredicate<Task>(predicate, TASK_TIMEOUT_SECONDS * 1000L);
assertTrue(retryablePredicate.apply(task), "Task must enter status "+running);
return retryablePredicate.apply(task);
}
protected void assertTaskDoneEventually(Task task) {
protected void assertTaskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) {
assertTrue(taskStatusEventually(task, running, immutableSet),
String.format("Task '%s' must reach status %s", task.getOperationName(), running));
}
protected boolean taskDoneEventually(Task task) {
TaskClient taskClient = context.getApi().getTaskClient();
TaskStatusEquals predicate = new TaskStatusEquals(
taskClient,
ImmutableSet.of(Task.Status.ABORTED, Task.Status.CANCELED, Task.Status.ERROR, Task.Status.SUCCESS),
Collections.<Task.Status>emptySet());
RetryablePredicate<Task> retryablePredicate = new RetryablePredicate<Task>(predicate, LONG_TASK_TIMEOUT_SECONDS * 1000L);
assertTrue(retryablePredicate.apply(task), "Task must be done");
return retryablePredicate.apply(task);
}
protected void assertTaskDoneEventually(Task task) {
assertTrue(taskDoneEventually(task),
String.format("Task '%s' must complete", task.getOperationName()));
}
/**
@ -407,10 +417,13 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseVersionedServ
protected void cleanUpVAppTemplate(VAppTemplate vAppTemplate) {
VAppTemplateClient vappTemplateClient = context.getApi().getVAppTemplateClient();
Task task = vappTemplateClient.deleteVappTemplate(vAppTemplate.getHref());
assertTaskSucceeds(task);
}
try {
Task task = vappTemplateClient.deleteVappTemplate(vAppTemplate.getHref());
taskDoneEventually(task);
} catch (Exception e) {
logger.warn(e, "Error deleting template '%s'", vAppTemplate.getName());
}
}
protected void cleanUpVApp(VApp vApp) {
cleanUpVApp(vApp.getHref());
@ -434,7 +447,9 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseVersionedServ
// Otherwise, get error on delete "entity is busy completing an operation.
if (vApp.getTasks() != null) {
for (Task task : vApp.getTasks()) {
assertTaskDoneEventually(task);
if (!taskDoneEventually(task)) {
logger.warn("Task '%s' did not complete", task.getOperationName());
}
}
}
@ -442,7 +457,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseVersionedServ
if (vApp.getStatus().equals(Status.POWERED_ON.getValue())) {
try {
Task shutdownTask = vAppClient.shutdown(vAppURI);
retryTaskSuccess.apply(shutdownTask);
taskDoneEventually(shutdownTask);
} catch (Exception e) {
// keep going; cleanup as much as possible
logger.warn(e, "Continuing cleanup after error shutting down VApp %s", vApp.getName());
@ -454,7 +469,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseVersionedServ
try {
UndeployVAppParams params = UndeployVAppParams.builder().build();
Task undeployTask = vAppClient.undeploy(vAppURI, params);
retryTaskSuccess.apply(undeployTask);
taskDoneEventually(undeployTask);
} catch (Exception e) {
// keep going; cleanup as much as possible
logger.warn(e, "Continuing cleanup after error undeploying VApp %s", vApp.getName());
@ -463,7 +478,7 @@ public abstract class BaseVCloudDirectorClientLiveTest extends BaseVersionedServ
try {
Task task = vAppClient.deleteVApp(vAppURI);
assertTaskSucceeds(task);
taskDoneEventually(task);
vAppNames.remove(vApp.getName());
logger.info("Deleted VApp %s", vApp.getName());
} catch (Exception e) {