VMWare Restore operation platform and Unit Tests

This commit is contained in:
Subrahmanyam Mandavilli 2015-12-18 16:29:42 +05:30
Родитель 38e06c3dbb
Коммит c8b26d82cb
9 изменённых файлов: 373 добавлений и 86 удалений

Просмотреть файл

@ -12,10 +12,17 @@ public interface IVMWare {
public void restoreSnapshot(String vmList, String snapshotName, ConnectionData connData) throws Exception;
/**
* Checks whether snapshot exists on given VM
* @param vmName name of the virtual machine
* @param snapshotName name of the snapshot to check
* @return true if snapshot exists, else false
* Gets the current active snapshot information for the VM
* @param vmName Name of the virtual machine
* @return current snapshot name
* @throws Exception
*/
public Boolean snapshotExists(String vmName, String snapshotName);
public String getCurrentSnapshot(String vmName, ConnectionData connData) throws Exception;
/**
*
* @param connData
* @throws Exception
*/
public void connect(ConnectionData connData) throws Exception;
}

Просмотреть файл

@ -13,48 +13,63 @@ public class VMWareImpl implements IVMWare {
private UserSession userSession;
private ManagedObjectReference rootFolder;
public Boolean snapshotExists(String vmName, String snapshotName) {
//TODO: Implement later to query for snapshot
return false;
public String getCurrentSnapshot(String vmName, ConnectionData connData) throws Exception {
System.out.println("Getting current snapshot name for virtual machine ( " + vmName + " )" );
connect(connData);
ManagedObjectReference vmMor = getVMMorByName(vmName);
return getCurrentSnapshotName(vmMor, vmName);
}
public void restoreSnapshot(String vmList, String snapshotName, ConnectionData connData) throws Exception {
Init(connData);
connect(connData);
String [] vmNames = vmList.split(",");
String failedVmList = "";
for (String vmName : vmNames) {
System.out.printf("Restoring snapshot(%s) on virtual machine (%s)", snapshotName, vmName);
Map<String, ManagedObjectReference> vmsMap = getObjectsInContainerByType(this.rootFolder, "VirtualMachine");
vmName = vmName.trim();
System.out.printf("Restoring snapshot (%s) on virtual machine (%s)\n", snapshotName, vmName);
ManagedObjectReference vmMor = null;
if(!vmsMap.containsKey(vmName))
{
System.out.printf("##vso[task.logissue type=error;code=USERINPUT_VmNotFound;TaskId=%s;]", taskId);
System.err.println("Virtual machine with name " + vmName + "not found.");
try {
vmMor = getVMMorByName(vmName);
}
catch(Exception exp) {
failedVmList += vmName;
continue;
}
ManagedObjectReference vmMor = vmsMap.get(vmName);
ManagedObjectReference cpMor = getSnapshotReference(vmMor, vmName, snapshotName);
ManagedObjectReference task = vimPort.revertToSnapshotTask(cpMor, null, true);
if (waitAndGetTaskResult(task)) {
System.out.printf("Successfully reverted to snapshot [%s] On virtual machine [%s]", snapshotName, vmName);
System.out.printf("Successfully reverted to snapshot [%s] On virtual machine [%s]\n", snapshotName, vmName);
} else {
System.err.printf("Failed to revert snapshot [%s] on virtual machine [%s]", snapshotName, vmName) ;
System.err.printf("Failed to revert snapshot [%s] on virtual machine [%s]\n", snapshotName, vmName) ;
failedVmList += vmName;
}
}
if(!failedVmList.isEmpty()) {
System.err.printf("Failed to revert snapshot [%s] on virtual machines [%s]", snapshotName, failedVmList);
System.err.printf("Failed to revert snapshot [%s] on virtual machines [%s]\n", snapshotName, failedVmList);
throw new Exception();
}
return;
}
private ManagedObjectReference getVMMorByName(String vmName) throws Exception {
Map<String, ManagedObjectReference> vmsMap = getObjectsInContainerByType(this.rootFolder, "VirtualMachine");
if(!vmsMap.containsKey(vmName))
{
System.out.printf("##vso[task.logissue type=error;code=USERINPUT_VmNotFound;TaskId=%s;]\n", taskId);
System.err.println("Virtual machine with name " + vmName + " not found.");
throw new Exception("Virtual machine with name " + vmName + " not found.");
}
return vmsMap.get(vmName);
}
private boolean waitAndGetTaskResult(ManagedObjectReference task) throws Exception {
boolean retVal = false;
@ -117,7 +132,7 @@ public class VMWareImpl implements IVMWare {
return filterVals;
}
catch(Exception exp) {
System.out.printf("##vso[task.logissue type=error;code=PREREQ_WaitForResultFailed;TaskId=%s;]", taskId);
System.out.printf("##vso[task.logissue type=error;code=PREREQ_WaitForResultFailed;TaskId=%s;]\n", taskId);
System.err.println("Failed to get operation result: " + exp.getMessage());
throw exp;
}
@ -136,39 +151,78 @@ public class VMWareImpl implements IVMWare {
}
private ManagedObjectReference getSnapshotReference(ManagedObjectReference vmMor, String vmName, String snapshotName) throws Exception {
System.out.printf("Querying snapshot information for virtual machine (%s)", vmName);
VirtualMachineSnapshotInfo snapshotInfo = (VirtualMachineSnapshotInfo) getMorProperties(vmMor, new String[] { "snapshot" }).get("snapshot");
System.out.printf("Querying snapshot information for virtual machine (%s)\n", vmName);
VirtualMachineSnapshotInfo vmSnapshotInfo = (VirtualMachineSnapshotInfo) getMorProperties(vmMor, new String[] { "snapshot" }).get("snapshot");
ManagedObjectReference snapshotMor = null;
String snapshotNotFoundErr = "No snapshot found on virtual machine " + vmName + "with name " + snapshotName;
String snapshotNotFoundErr = "No snapshot found on virtual machine (" + vmName + ") with name " + snapshotName;
if (vmSnapshotInfo != null) {
List<VirtualMachineSnapshotTree> vmRootSnapshotList = vmSnapshotInfo.getRootSnapshotList();
snapshotMor = findSnapshotInTree(vmRootSnapshotList, snapshotName);
if (snapshotInfo != null) {
List<VirtualMachineSnapshotTree> vmSnapshotList = snapshotInfo.getRootSnapshotList();
snapshotMor = findSnapshotInTree(vmSnapshotList, snapshotName);
if (snapshotMor == null) {
System.out.printf("##vso[task.logissue type=error;code=USERINPUT_SnapshotNotFound;TaskId=%s;]", taskId);
System.out.printf("##vso[task.logissue type=error;code=USERINPUT_SnapshotNotFound;TaskId=%s;]\n", taskId);
System.err.println(snapshotNotFoundErr);
throw new Exception();
}
} else {
System.out.printf("##vso[task.logissue type=error;code=USERINPUT_SnapshotNotFound;TaskId=%s;]", taskId);
System.out.printf("##vso[task.logissue type=error;code=USERINPUT_SnapshotNotFound;TaskId=%s;]\n", taskId);
System.err.println(snapshotNotFoundErr);
throw new Exception();
}
return snapshotMor;
}
private String getCurrentSnapshotName(ManagedObjectReference vmMor, String vmName) throws Exception {
System.out.printf("Querying snapshot information for virtual machine (%s)\n", vmName);
VirtualMachineSnapshotInfo vmSnapshotInfo = (VirtualMachineSnapshotInfo) getMorProperties(vmMor, new String[] { "snapshot" }).get("snapshot");
String currentSnapshotName = "";
if (vmSnapshotInfo != null) {
System.out.println("Searching for current snapshot in snapshot tree.");
List<VirtualMachineSnapshotTree> vmRootSnapshotList = vmSnapshotInfo.getRootSnapshotList();
ManagedObjectReference currentSnapshotMor = vmSnapshotInfo.getCurrentSnapshot();
currentSnapshotName = getCurrentSnapshotNameFromTree(vmRootSnapshotList, currentSnapshotMor);
}
else {
System.out.println("Snapshot info is null!!");
}
return currentSnapshotName;
}
private String getCurrentSnapshotNameFromTree(List<VirtualMachineSnapshotTree> vmRootSnapshotList, ManagedObjectReference currentSnapshotMor) {
String currentSnapshotName = "";
if (vmRootSnapshotList == null) {
System.out.println("No snapshot found!!");
return currentSnapshotName;
}
for (VirtualMachineSnapshotTree vmSnapshot : vmRootSnapshotList) {
System.out.printf("Current CP Name: %s\n", vmSnapshot.getName());
if (vmSnapshot.getSnapshot().getValue().equals(currentSnapshotMor.getValue())) {
System.out.println("Found current snapshot in tree ( " + vmSnapshot.getName() + " )");
return vmSnapshot.getName();
} else {
List<VirtualMachineSnapshotTree> childTree = vmSnapshot.getChildSnapshotList();
currentSnapshotName = getCurrentSnapshotNameFromTree(childTree, currentSnapshotMor);
}
}
return currentSnapshotName;
}
private ManagedObjectReference findSnapshotInTree(List<VirtualMachineSnapshotTree> vmSnapshotList, String snapshotName) {
ManagedObjectReference snapshotMor = null;
if (vmSnapshotList == null) {
System.out.printf("Snapshot(%s) not found for virtual machine", snapshotName);
System.out.printf("Snapshot(%s) not found for virtual machine\n", snapshotName);
return snapshotMor;
}
for (VirtualMachineSnapshotTree vmSnapshot : vmSnapshotList) {
if (vmSnapshot.getName().equalsIgnoreCase(snapshotName)) {
System.out.printf("Found snapshot(%s) for virtual machine", snapshotName);
System.out.printf("Found snapshot (%s) for virtual machine\n", snapshotName);
return vmSnapshot.getSnapshot();
} else {
List<VirtualMachineSnapshotTree> childTree = vmSnapshot.getChildSnapshotList();
@ -184,7 +238,7 @@ public class VMWareImpl implements IVMWare {
try {
results = vimPort.retrievePropertiesEx(serviceContent.getPropertyCollector(), Arrays.asList(propFilterSpec), new RetrieveOptions());
} catch(Exception exp) {
System.out.printf("##vso[task.logissue type=error;code=PREREQ_RetriveObjectPropertiesFailed;TaskId=%s;]", taskId);
System.out.printf("##vso[task.logissue type=error;code=PREREQ_RetriveObjectPropertiesFailed;TaskId=%s;]\n", taskId);
System.err.println("Failed to properties for managed object : " + exp.getMessage());
throw exp;
}
@ -217,10 +271,10 @@ public class VMWareImpl implements IVMWare {
}
private Map<String, ManagedObjectReference> getObjectsInContainerByType(ManagedObjectReference container, String morefType) throws Exception {
PropertyFilterSpec propertyFilterSpecs = createRecursiveFilterSpec(container, morefType, new String [] { "name" });
PropertyFilterSpec propertyFilterSpecs = createRecursiveFilterSpec(container, morefType, new String [] {"config" });
try {
System.out.printf("Querying %s objects on vCenter server", morefType);
System.out.printf("Querying %s objects on vCenter server.\n", morefType);
RetrieveResult results = vimPort.retrievePropertiesEx(serviceContent.getPropertyCollector(), Arrays.asList(propertyFilterSpecs), new RetrieveOptions());
String token = null;
final Map<String, ManagedObjectReference> morMap = new HashMap<String, ManagedObjectReference>();
@ -232,7 +286,7 @@ public class VMWareImpl implements IVMWare {
}
return morMap;
} catch (Exception exp) {
System.out.printf("##vso[task.logissue type=error;code=PREREQ_QueryObjectsFailed;TaskId=%s;]", taskId);
System.out.printf("##vso[task.logissue type=error;code=PREREQ_QueryObjectsFailed;TaskId=%s;]\n", taskId);
System.err.println("Failed to fetch objects: " + exp.getMessage());
throw exp;
}
@ -240,17 +294,17 @@ public class VMWareImpl implements IVMWare {
private String createMap(final RetrieveResult results, final Map<String, ManagedObjectReference> morMap) {
String token = null;
if(results != null) {
token = results.getToken();
String objName = null;
for (ObjectContent objectContent : results.getObjects()) {
ManagedObjectReference mor = objectContent.getObj();
objName = (String) objectContent.getPropSet().get(0).getVal();
morMap.put(objName, mor);
VirtualMachineConfigInfo vmConfig = (VirtualMachineConfigInfo) objectContent.getPropSet().get(0).getVal();
if (vmConfig != null && !vmConfig.isTemplate()) {
morMap.put(vmConfig.getName(), mor);
}
}
}
return token;
}
@ -286,13 +340,13 @@ public class VMWareImpl implements IVMWare {
return propertyFilterSpec;
}
catch(Exception exp) {
System.out.printf("##vso[task.logissue type=error;code=PREREQ_CreateFilterSpecFailed;TaskId=%s;]", taskId);
System.out.printf("##vso[task.logissue type=error;code=PREREQ_CreateFilterSpecFailed;TaskId=%s;]\n", taskId);
System.err.println("Failed to create filter spec: " + exp.getMessage());
throw exp;
}
}
private void Init(ConnectionData connData) throws Exception {
public void connect(ConnectionData connData) throws Exception {
try {
if(!isSessionActive()) {
System.out.println("No active session found.. establishing new session.");
@ -313,9 +367,10 @@ public class VMWareImpl implements IVMWare {
}
catch (Exception exp) {
System.err.println("Failed to connect: " + exp.getMessage());
System.out.printf("##vso[task.logissue type=error;code=PREREQ_ConnectionFailed;TaskId=%s;]", taskId);
System.out.printf("##vso[task.logissue type=error;code=USERINPUT_ConnectionFailed;TaskId=%s;]\n", taskId);
throw exp;
}
System.out.println("Successfully established session with vCenter server.");
return;
}

Просмотреть файл

@ -28,30 +28,30 @@ public class VmOpsTool {
public void executeAction(String[] args) throws Exception {
Map<String, String> argsMap = parseCmdLine(args);
String vCenterUrl = argsMap.get("-vCenterUrl");
String vCenterUserName = argsMap.get("-vCenterUserName");
String vCenterPassword = argsMap.get("-vCenterPassword");
String vmList = argsMap.get("-vmList");
ConnectionData connData = new ConnectionData(vCenterUrl, vCenterUserName, vCenterPassword);
if(argsMap.containsKey("-snapshotOps")) {
String actionName = argsMap.get("-snapshotOps");
String snapshotName = argsMap.get("-snapshotName");
if(actionName.equalsIgnoreCase("restore")) {
System.out.printf("Initiating restore snapshot operation on vmList[%s]", vmList);
System.out.printf("Initiating restore snapshot operation on vmList[%s]\n", vmList);
vmWareImpl.restoreSnapshot(vmList, snapshotName, connData);
}
else {
System.out.printf("##vso[task.logissue type=error;code=INFRA_InvalidSnapshotOperation;TaskId=%s;]", taskId );
System.err.printf("Invalid action name(%s) for snapshot operation", actionName);
System.out.printf("##vso[task.logissue type=error;code=INFRA_InvalidSnapshotOperation;TaskId=%s;]\n", taskId );
System.err.printf("Invalid action name(%s) for snapshot operation\n", actionName);
throw new Exception("Invalid action name(" + actionName + ") for snapshot operation");
}
}
else {
System.out.printf("##vso[task.logissue type=error;code=INFRA_Operation;TaskId=%s;]", taskId );
System.err.printf("Invalid action input for the operation.");
System.out.printf("##vso[task.logissue type=error;code=INFRA_InvalidOperation;TaskId=%s;]\n", taskId );
System.err.printf("Invalid action input for the operation.\n");
throw new Exception("Invalid action input for the operation.");
}
}

Просмотреть файл

@ -54,6 +54,7 @@
<configuration>
<includes>
<include>**/*UnitTests.java</include>
<include>**/*PlatformTests.java</include>
</includes>
<reportsDirectory>../../_build/testReports/vmOpsTool</reportsDirectory>
<testClassesDirectory>../../_build/tests/tools/vmOpsTool</testClassesDirectory>
@ -66,7 +67,7 @@
<version>2.16</version>
<configuration>
<includes>
<include>**/*IntegrationTest.java</include>
<include>**/*IntegrationTests.java</include>
</includes>
<reportsDirectory>../../_build/testReports/vmOpsTool</reportsDirectory>
<testClassesDirectory>../../_build/tests/tools/vmOpsTool</testClassesDirectory>

Просмотреть файл

@ -1,6 +1,4 @@
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import vmOpsTool.ConnectionData;
@ -8,26 +6,72 @@ import vmOpsTool.IVMWare;
public class InMemoryVMWareImpl implements IVMWare {
private List<String> knownVmList = Arrays.asList("vm1", "vm2");
private Map<String, String> activeSnapshotInfo = new HashMap<String, String>();
private Map<String, Map<String, Integer>> vmSnapshotInfo = new HashMap<String, Map<String, Integer>>();
private Map<String, Integer> snapshotMap = new HashMap<String, Integer>();
public InMemoryVMWareImpl() {
snapshotMap.put("Snapshot1", 0);
snapshotMap.put("Snapshot2", 1);
vmSnapshotInfo.put("TestVM1", snapshotMap);
vmSnapshotInfo.put("PoweredOffVM", snapshotMap);
vmSnapshotInfo.put("DuplicateVMName", snapshotMap);
vmSnapshotInfo.put("TemplateVM", snapshotMap);
vmSnapshotInfo.put("VMTemplate", snapshotMap);
vmSnapshotInfo.put("VMInDC1", snapshotMap);
vmSnapshotInfo.put("VMInDC2", snapshotMap);
vmSnapshotInfo.put("vm1", snapshotMap);
vmSnapshotInfo.put("vm2", snapshotMap);
}
public void restoreSnapshot(String vmList, String snapshotName, ConnectionData connData) throws Exception {
String[] vms = vmList.split(",");
Map<String, Integer> cpMap = null;
for (String vm : vms) {
vm = vm.trim();
if(knownVmList.contains(vm)) {
activeSnapshotInfo.put(vm, snapshotName);
if(vmSnapshotInfo.containsKey(vm)) {
cpMap = vmSnapshotInfo.get(vm);
if(!cpMap.containsKey(snapshotName)) {
System.out.println("Snapshot does not exist: " + snapshotName);
throw new Exception("Snapshot does not exist: " + snapshotName);
}
for (Map.Entry<String, Integer> mapEntry : cpMap.entrySet()) {
if(mapEntry.getKey().equalsIgnoreCase(snapshotName)) {
mapEntry.setValue(1);
System.out.println("Restored snapshot " + snapshotName);
}
else {
mapEntry.setValue(0);
}
}
}
else {
throw new Exception("VM not found.");
}
}
return;
}
public Boolean snapshotExists(String vmName, String snapshotName) {
if(activeSnapshotInfo.containsKey(vmName)) {
return activeSnapshotInfo.get(vmName).equalsIgnoreCase(snapshotName);
public void connect(ConnectionData connData) throws Exception {
if(connData.password.equals("InvalidPassword")) {
throw new Exception();
}
return false;
}
}
public String getCurrentSnapshot(String vmName, ConnectionData connData) {
Map<String, Integer> cpMap = null;
String currentSnapshotName = null;
cpMap = vmSnapshotInfo.get(vmName);
for (Map.Entry<String, Integer> mapEntry : cpMap.entrySet()) {
if(mapEntry.getValue().equals(1)) {
currentSnapshotName = mapEntry.getKey();
}
}
return currentSnapshotName;
}
}

Просмотреть файл

@ -0,0 +1,14 @@
import vmOpsTool.IVMWare;
public class InMemoryVMWareImplPlatformTests extends VMWarePlatformTests{
@Override
public IVMWare getVmWareImpl() {
return new InMemoryVMWareImpl();
}
@Override
public String getvCenterUrl() {
return "http://localhost:8080/sdk/vimservice";
}
}

Просмотреть файл

@ -0,0 +1,18 @@
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import vmOpsTool.IVMWare;
import vmOpsTool.VMWareImpl;
public class VMWareImplPlatformTests extends VMWarePlatformTests {
@Override
public IVMWare getVmWareImpl() {
return new VMWareImpl();
}
@Override
public String getvCenterUrl() {
return "https://idcvstt-lab325.fareast.corp.microsoft.com/sdk/vimservice";
}
}

Просмотреть файл

@ -0,0 +1,139 @@
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import org.junit.Test;
import vmOpsTool.ConnectionData;
import vmOpsTool.IVMWare;
import static org.assertj.core.api.Assertions.*;
public abstract class VMWarePlatformTests {
private String vCenterUserName = "Administrator@vsphere.local";
private String vCenterPassword = "Password~1";
private String vCenterUrl = getvCenterUrl();
private ConnectionData connData = new ConnectionData(vCenterUrl, vCenterUserName, vCenterPassword);
private IVMWare vmWareImpl = getVmWareImpl();
private String snapshotOne = "Snapshot1";
private String snapshotTwo = "Snapshot2";
public abstract IVMWare getVmWareImpl();
public abstract String getvCenterUrl();
// Common for all Operations
// The following two scenarios needs to be validated during stress testing
// restoreSnapshotShouldUseASessionTimeoutOfSixtyMinutes
// restoreSnapshotShouldThrowIfWaitTimesOut
@Test
public void connectShouldThrowConnectionToServerFailsAuthentication() {
Exception exp = null;
try {
vmWareImpl.connect(new ConnectionData(vCenterUrl, vCenterUserName, "InvalidPassword"));
} catch (Exception e) {
exp = e;
}
assertThat(exp).isNotNull();
}
@Test
public void connectShouldNotThrowOnSuccessfulAuthentication() throws Exception {
vmWareImpl.connect(connData);
}
// Common for restore/delete snapshot operations
@Test
public void restoreSnapshotShouldThrowIfSnapshotDoesNotExist() {
Exception exp = null;
try {
vmWareImpl.restoreSnapshot("TestVM1", "InvalidSnapshot", connData);
} catch (Exception e) {
exp = e;
}
assertThat(exp).isNotNull();
}
// Common for Snapshot operations
@Test
public void restoreSnapshotShouldThrowIfVmDoesNotExist() {
Exception exp = null;
try {
vmWareImpl.restoreSnapshot("InvalidVM", snapshotOne, connData);
} catch (Exception e) {
exp = e;
}
assertThat(exp).isNotNull();
}
@Test
public void restoreSnapshotShouldRestoreSnapshotIfVmIsShutdown() throws Exception {
String vmName = "PoweredOffVM";
vmWareImpl.restoreSnapshot(vmName, snapshotOne, connData);
assertThat(vmWareImpl.getCurrentSnapshot(vmName, connData)).isEqualTo(snapshotOne);
vmWareImpl.restoreSnapshot(vmName, snapshotTwo, connData);
assertThat(vmWareImpl.getCurrentSnapshot(vmName, connData)).isEqualTo(snapshotTwo);
}
@Test
public void restoreSnapshotShouldRestoreSnapshotForTwoVms() throws Exception {
String vmList = "PoweredOffVM, TestVM1";
vmWareImpl.restoreSnapshot(vmList, snapshotOne, connData);
assertThat(vmWareImpl.getCurrentSnapshot("PoweredOffVM", connData)).isEqualTo(snapshotOne);
assertThat(vmWareImpl.getCurrentSnapshot("TestVM1", connData)).isEqualTo(snapshotOne);
vmWareImpl.restoreSnapshot(vmList, snapshotTwo, connData);
assertThat(vmWareImpl.getCurrentSnapshot("PoweredOffVM", connData)).isEqualTo(snapshotTwo);
assertThat(vmWareImpl.getCurrentSnapshot("TestVM1", connData)).isEqualTo(snapshotTwo);
}
@Test
public void restoreSnapshotShouldRestoreSnapshotIfMultipleVmWithSameNameExist() throws Exception {
String vmName = "DuplicateVMName";
vmWareImpl.restoreSnapshot(vmName, snapshotOne, connData);
assertThat(vmWareImpl.getCurrentSnapshot(vmName, connData)).isEqualTo(snapshotOne);
vmWareImpl.restoreSnapshot(vmName, snapshotTwo, connData);
assertThat(vmWareImpl.getCurrentSnapshot(vmName, connData)).isEqualTo(snapshotTwo);
}
@Test
public void restoreSnapshotShouldRestoreSnapshotIfTemplateAndVmHaveSameName() throws Exception {
String vmName1 = "TemplateVM";
String vmName2 = "VMTemplate";
vmWareImpl.restoreSnapshot(vmName1, snapshotOne, connData);
vmWareImpl.restoreSnapshot(vmName2, snapshotOne, connData);
assertThat(vmWareImpl.getCurrentSnapshot(vmName1, connData)).isEqualTo(snapshotOne);
assertThat(vmWareImpl.getCurrentSnapshot(vmName2, connData)).isEqualTo(snapshotOne);
vmWareImpl.restoreSnapshot(vmName1, snapshotTwo, connData);
vmWareImpl.restoreSnapshot(vmName2, snapshotTwo, connData);
assertThat(vmWareImpl.getCurrentSnapshot(vmName1, connData)).isEqualTo(snapshotTwo);
assertThat(vmWareImpl.getCurrentSnapshot(vmName2, connData)).isEqualTo(snapshotTwo);
}
@Test
public void restoreSnapshotShouldRestoreSnapshotForVMsDiffDataCenters() throws Exception {
String vmName1 = "VMInDC1";
String vmName2 = "VMInDC2";
vmWareImpl.restoreSnapshot(vmName1, "Snapshot1", connData);
vmWareImpl.restoreSnapshot(vmName2, "Snapshot1", connData);
assertThat(vmWareImpl.getCurrentSnapshot(vmName1, connData)).isEqualTo(snapshotOne);
assertThat(vmWareImpl.getCurrentSnapshot(vmName2, connData)).isEqualTo(snapshotOne);
vmWareImpl.restoreSnapshot(vmName1, "Snapshot2", connData);
vmWareImpl.restoreSnapshot(vmName2, "Snapshot2", connData);
assertThat(vmWareImpl.getCurrentSnapshot(vmName1, connData)).isEqualTo(snapshotTwo);
assertThat(vmWareImpl.getCurrentSnapshot(vmName2, connData)).isEqualTo(snapshotTwo);
}
}

Просмотреть файл

@ -1,16 +1,21 @@
import java.util.*;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import vmOpsTool.VMWareImpl;
import vmOpsTool.VmOpsTool;
import java.util.Map;
import vmOpsTool.ConnectionData;
import vmOpsTool.IVMWare;
import vmOpsTool.VmOpsTool;
public class VmOpsToolUnitTests {
private InMemoryVMWareImpl vmWareImpl = new InMemoryVMWareImpl();
private VmOpsTool vmOpsTool = new VmOpsTool(vmWareImpl);
private String vCenterUrl = "https://localhost:8080/sdk/vimservice";
private String vCenterUserName = "Administrator";
private String vCenterPassword = "Password~1";
private ConnectionData connData = new ConnectionData(vCenterUrl, vCenterUserName, vCenterPassword);
@Test
public void parseCmdArgsWithAllRequiredInputs() {
@ -27,38 +32,34 @@ public class VmOpsToolUnitTests {
@Test
public void executeActionShouldRestoreSnapshotForRestoreOperation() throws Exception {
String[] cmdArgs = new String[] {"vmOpsTool", "-vCenterUrl", "http://localhost:8080", "-vCenterUserName", "dummyuser",
"-vCenterPassword", "dummypassword", "-vmList", "vm1, vm2", "-snapshotOps", "restore",
"-snapshotName", "dummySnapshot"};
String[] cmdArgs = getCmdArgs("vm1, vm2", "-snapshotOps", "restore", "Snapshot1");
vmOpsTool.executeAction(cmdArgs);
assertThat(vmWareImpl.snapshotExists("vm1", "dummySnapshot")).isEqualTo(true);
assertThat(vmWareImpl.snapshotExists("vm2", "dummySnapshot")).isEqualTo(true);
assertThat(vmWareImpl.getCurrentSnapshot("vm1", connData)).isEqualTo("Snapshot1");
assertThat(vmWareImpl.getCurrentSnapshot("vm2", connData)).isEqualTo("Snapshot1");
}
@Test
public void executeActionShouldThrowForRestoreSnapshotFailureOnAVM() {
String[] cmdArgs = getCmdArgs("vm1, vm3", "-snapshotOps", "restore", "Snapshot1");
Exception exp = null;
String[] cmdArgs = new String[] {"vmOpsTool", "-vCenterUrl", "http://localhost:8080", "-vCenterUserName", "dummyuser",
"-vCenterPassword", "dummypassword", "-vmList", "vm1, vm3", "-snapshotOps", "restore",
"-snapshotName", "dummySnapshot"};
try {
vmOpsTool.executeAction(cmdArgs);
} catch (Exception e) {
exp = e;
}
assertThat(exp).isNotNull();
assertThat(vmWareImpl.snapshotExists("vm1", "dummySnapshot")).isEqualTo(true);
assertThat(vmWareImpl.snapshotExists("vm3", "dummySnapshot")).isEqualTo(false);
assertThat(vmWareImpl.getCurrentSnapshot("vm1", connData)).isEqualTo("Snapshot1");
}
@Test
public void executeActionInvalidSnapshotOperationShouldFail() {
String[] cmdArgs = new String[] {"vmOpsTool", "-vCenterUrl", "http://localhost:8080", "-vCenterUserName", "dummyuser",
"-vCenterPassword", "dummypassword", "-vmList", "vm1, vm2", "-snapshotOps", "invalid",
"-snapshotName", "dummySnapshot"};
String[] cmdArgs = getCmdArgs("vm1, vm2", "-snapshotOps", "invalid", "Snapshot1");
Exception exp = null;
try {
vmOpsTool.executeAction(cmdArgs);
} catch (Exception e) {
@ -69,10 +70,9 @@ public class VmOpsToolUnitTests {
@Test
public void executeActionForInvalidActionNameShouldFail() {
String[] cmdArgs = new String[] {"vmOpsTool", "-vCenterUrl", "http://localhost:8080", "-vCenterUserName", "dummyuser",
"-vCenterPassword", "dummypassword", "-vmList", "vm1, vm2", "-invalidOps", "restore",
"-snapshotName", "dummySnapshot"};
String[] cmdArgs = getCmdArgs("vm1, vm2", "-invalidOps", "restore", "Snapshot1");
Exception exp = null;
try {
vmOpsTool.executeAction(cmdArgs);
} catch (Exception e) {
@ -85,11 +85,20 @@ public class VmOpsToolUnitTests {
public void executeActionShouldIfRequiredInputIsNotPresent() {
String[] cmdArgs = new String[] {"vmOpsTool"};
Exception exp = null;
try {
vmOpsTool.executeAction(cmdArgs);
} catch (Exception e) {
exp = e;
}
}
assertThat(exp).isNotNull();
}
private String[] getCmdArgs(String vmList, String actionName , String actionOption, String snapshotName) {
String[] cmdArgs = new String[] {"vmOpsTool", "-vCenterUrl", "http://localhost:8080",
"-vCenterUserName", "dummyuser", "-vCenterPassword", "dummypassword", "-vmList",
vmList, actionName, actionOption, "-snapshotName", snapshotName};
return cmdArgs;
}
}