Remove powermock from kvm hypervisor plugin (#7818)

* Remove powermock from kvm hypervisor plugin

* Add @RunWith

* Remove unnecessary mocks

* Remove commented code
This commit is contained in:
Vishesh 2023-08-10 12:34:36 +05:30 committed by GitHub
parent 927818b55f
commit 82f9106633
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 829 additions and 599 deletions

View File

@ -19,22 +19,22 @@
package com.cloud.hypervisor.kvm.dpdk;
import com.cloud.utils.script.Script;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.HashMap;
import java.util.Map;
@PrepareForTest({ Script.class })
@RunWith(PowerMockRunner.class)
@RunWith(MockitoJUnitRunner.class)
public class DpdkDriverTest {
private static final int dpdkPortNumber = 7;
@ -43,14 +43,24 @@ public class DpdkDriverTest {
private Map<String, String> extraConfig;
private MockedStatic<Script> scriptMockedStatic;
private AutoCloseable closeable;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(Script.class);
closeable = MockitoAnnotations.openMocks(this);
scriptMockedStatic = Mockito.mockStatic(Script.class);
Mockito.when(Script.runSimpleBashScript(Matchers.anyString())).thenReturn(null);
extraConfig = new HashMap<>();
}
@After
public void tearDown() throws Exception {
scriptMockedStatic.close();
closeable.close();
}
@Test
public void testGetDpdkLatestPortNumberUsedNoDpdkPorts() {
Assert.assertEquals(0, driver.getDpdkLatestPortNumberUsed());

View File

@ -22,7 +22,10 @@ import org.junit.Test;
import com.cloud.agent.api.to.NicTO;
import com.cloud.network.Networks;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class BridgeVifDriverTest {
private BridgeVifDriver driver;

View File

@ -21,12 +21,11 @@ package com.cloud.hypervisor.kvm.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
@ -47,7 +46,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.UUID;
import java.util.Vector;
@ -92,13 +90,12 @@ import org.libvirt.jna.virDomainMemoryStats;
import org.mockito.ArgumentCaptor;
import org.mockito.BDDMockito;
import org.mockito.Mock;
import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
@ -226,9 +223,7 @@ import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.PowerState;
import com.cloud.vm.VirtualMachine.Type;
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {MemStat.class, SshHelper.class, AgentPropertiesFileHandler.class, AgentProperties.class, Script.class})
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*"})
@RunWith(MockitoJUnitRunner.class)
public class LibvirtComputingResourceTest {
@Mock
@ -271,15 +266,12 @@ public class LibvirtComputingResourceTest {
final static String publicIp = "10.10.10.10";
final static Integer port = 8080;
final Script scriptMock = Mockito.mock(Script.class);
final OneLineParser statsParserMock = Mockito.mock(OneLineParser.class);
@Before
public void setup() throws Exception {
libvirtComputingResourceSpy._qemuSocketsPath = new File("/var/run/qemu");
libvirtComputingResourceSpy.parser = parserMock;
Scanner scanner = new Scanner(memInfo);
PowerMockito.whenNew(Scanner.class).withAnyArguments().thenReturn(scanner);
LibvirtComputingResource.s_logger = loggerMock;
}
@ -923,12 +915,12 @@ public class LibvirtComputingResourceTest {
String uuid = "1";
final LibvirtComputingResource lcr = new LibvirtComputingResource();
uuid = lcr.getUuid(uuid);
Assert.assertTrue(!uuid.equals("1"));
assertNotEquals("1", uuid);
final String oldUuid = UUID.randomUUID().toString();
uuid = oldUuid;
uuid = lcr.getUuid(uuid);
Assert.assertTrue(uuid.equals(oldUuid));
assertEquals(uuid, oldUuid);
}
private static final String VMNAME = "test";
@ -1092,9 +1084,7 @@ public class LibvirtComputingResourceTest {
@SuppressWarnings("unchecked")
@Test
public void testStopCommandCheckException1() {
final Connect conn = Mockito.mock(Connect.class);
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
final Domain vm = Mockito.mock(Domain.class);
final DomainInfo info = Mockito.mock(DomainInfo.class);
final DomainState state = DomainInfo.DomainState.VIR_DOMAIN_RUNNING;
info.state = state;
@ -1105,10 +1095,6 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try {
when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
when(conn.domainLookupByName(command.getVmName())).thenReturn(vm);
when(vm.getInfo()).thenReturn(info);
} catch (final LibvirtException e) {
fail(e.getMessage());
}
@ -1608,9 +1594,7 @@ public class LibvirtComputingResourceTest {
}
when(vm.getNics()).thenReturn(new NicTO[]{nicTO});
when(nicTO.getType()).thenReturn(TrafficType.Guest);
when(libvirtComputingResourceMock.getVifDriver(nicTO.getType())).thenReturn(vifDriver);
when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolManager);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
@ -1711,13 +1695,6 @@ public class LibvirtComputingResourceTest {
BDDMockito.given(libvirtComputingResourceMock.getVifDriver(nicTO.getType(), nicTO.getName())).willAnswer(invocationOnMock -> {throw new InternalErrorException("Exception Occurred");});
when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolManager);
try {
when(libvirtComputingResourceMock.getVolumePath(conn, volume)).thenReturn("/path");
} catch (final LibvirtException e) {
fail(e.getMessage());
} catch (final URISyntaxException e) {
fail(e.getMessage());
}
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -1775,7 +1752,6 @@ public class LibvirtComputingResourceTest {
try {
when(conn.domainLookupByName(vmName)).thenReturn(dm);
when(libvirtComputingResourceMock.getPrivateIp()).thenReturn("127.0.0.1");
when(dm.getXMLDesc(8)).thenReturn("<domain type='kvm' id='3'>" + " <devices>" + " <graphics type='vnc' port='5900' autoport='yes' listen='10.10.10.1'>"
+ " <listen type='address' address='10.10.10.1'/>" + " </graphics>" + " </devices>" + "</domain>");
when(dm.getXMLDesc(1)).thenReturn("<domain type='kvm' id='3'>" + " <devices>" + " <graphics type='vnc' port='5900' autoport='yes' listen='10.10.10.1'>"
@ -1903,8 +1879,6 @@ public class LibvirtComputingResourceTest {
fail(e.getMessage());
}
when(libvirtComputingResourceMock.getVmState(conn, command.getVmName())).thenReturn(PowerState.PowerOn);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -2338,7 +2312,6 @@ public class LibvirtComputingResourceTest {
when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool);
when(secondaryPool.listPhysicalDisks()).thenReturn(disks);
when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool);
when(storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0)).thenReturn(primaryVol);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -2374,8 +2347,6 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr);
when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool);
when(secondaryPool.listPhysicalDisks()).thenReturn(disks);
when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool);
when(storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0)).thenReturn(primaryVol);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -2414,9 +2385,6 @@ public class LibvirtComputingResourceTest {
when(secondaryPool.listPhysicalDisks()).thenReturn(spiedDisks);
when(spiedDisks.isEmpty()).thenReturn(false);
when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool);
when(storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0)).thenReturn(primaryVol);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -2450,7 +2418,6 @@ public class LibvirtComputingResourceTest {
when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool);
when(secondaryPool.getPhysicalDisk("template.qcow2")).thenReturn(tmplVol);
when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool);
when(storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0)).thenReturn(primaryVol);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -3250,8 +3217,6 @@ public class LibvirtComputingResourceTest {
final String bridge = command.getNetworkName();
when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(bridge)).thenReturn(false);
when(libvirtComputingResourceMock.configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
command.getNetworkName())).thenReturn(true);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -3280,7 +3245,6 @@ public class LibvirtComputingResourceTest {
final String bridge = command.getNetworkName();
when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(bridge)).thenReturn(true);
when(libvirtComputingResourceMock.configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
command.getNetworkName())).thenThrow(Exception.class);
@ -3440,15 +3404,6 @@ public class LibvirtComputingResourceTest {
fail(e.getMessage());
}
when(ingressRuleSet[0].getProto()).thenReturn("tcp");
when(ingressRuleSet[0].getStartPort()).thenReturn(22);
when(ingressRuleSet[0].getEndPort()).thenReturn(22);
when(ingressRuleSet[0].getAllowedCidrs()).thenReturn(cidrs);
when(egressRuleSet[0].getProto()).thenReturn("tcp");
when(egressRuleSet[0].getStartPort()).thenReturn(22);
when(egressRuleSet[0].getEndPort()).thenReturn(22);
when(egressRuleSet[0].getAllowedCidrs()).thenReturn(cidrs);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -3556,7 +3511,6 @@ public class LibvirtComputingResourceTest {
nics.add(interfaceDef);
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics);
try {
when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
} catch (final LibvirtException e) {
@ -3596,8 +3550,6 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics);
when(intDef.getDevName()).thenReturn("eth0");
when(intDef.getBrName()).thenReturn("br0");
when(intDef.getMacAddress()).thenReturn("00:00:00:00");
when(nic.getMac()).thenReturn("00:00:00:00");
@ -3645,8 +3597,6 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics);
when(intDef.getDevName()).thenReturn("eth0");
when(intDef.getBrName()).thenReturn("br0");
when(intDef.getMacAddress()).thenReturn("00:00:00:00");
when(nic.getMac()).thenReturn("00:00:00:01");
@ -3743,8 +3693,6 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics);
when(intDef.getDevName()).thenReturn("eth0");
when(intDef.getBrName()).thenReturn("br0");
when(intDef.getMacAddress()).thenReturn("00:00:00:00");
when(nic.getMac()).thenReturn("00:00:00:01");
@ -3792,7 +3740,6 @@ public class LibvirtComputingResourceTest {
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
final Connect conn = Mockito.mock(Connect.class);
final Domain vm = Mockito.mock(Domain.class);
final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
@ -3805,7 +3752,6 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics);
when(intDef.getDevName()).thenReturn("eth0");
when(intDef.getBrName()).thenReturn("br0");
when(intDef.getMacAddress()).thenReturn("00:00:00:00");
@ -3814,16 +3760,7 @@ public class LibvirtComputingResourceTest {
try {
when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
when(libvirtComputingResourceMock.getDomain(conn, instanceName)).thenReturn(vm);
when(interfaceDef.toString()).thenReturn("Interface");
final String interfaceDefStr = interfaceDef.toString();
doNothing().when(vm).detachDevice(interfaceDefStr);
when(libvirtComputingResourceMock.getAllVifDrivers()).thenReturn(drivers);
doNothing().when(vifDriver).unplug(intDef, true);
} catch (final LibvirtException e) {
fail(e.getMessage());
}
@ -4362,16 +4299,12 @@ public class LibvirtComputingResourceTest {
final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(tmplName);
try {
when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenThrow(ConfigurationException.class);
when(qcow2Processor.process(tmplPath, null, tmplName)).thenReturn(info);
} catch (final ConfigurationException e) {
fail(e.getMessage());
} catch (final InternalErrorException e) {
fail(e.getMessage());
}
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
@ -4435,7 +4368,6 @@ public class LibvirtComputingResourceTest {
final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(tmplName);
try {
@ -4621,7 +4553,6 @@ public class LibvirtComputingResourceTest {
when(secondary.createFolder(volumeDestPath)).thenReturn(true);
when(storagePoolMgr.deleteStoragePool(secondary.getType(), secondary.getUuid())).thenReturn(true);
when(storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolURL + volumeDestPath)).thenReturn(secondary);
when(storagePoolMgr.copyPhysicalDisk(disk, destVolumeName, secondary, 0)).thenReturn(disk);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -4663,8 +4594,6 @@ public class LibvirtComputingResourceTest {
when(secondary.getType()).thenReturn(StoragePoolType.ManagedNFS);
when(secondary.getUuid()).thenReturn("60d979d8-d132-4181-8eca-8dfde50d7df6");
when(storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolURL + volumeDestPath)).thenReturn(secondary);
when(primary.getPhysicalDisk(command.getVolumePath() + ".qcow2")).thenReturn(disk);
when(storagePoolMgr.copyPhysicalDisk(disk, destVolumeName, primary, 0)).thenReturn(disk);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -4780,8 +4709,6 @@ public class LibvirtComputingResourceTest {
when(secondary.getType()).thenReturn(StoragePoolType.ManagedNFS);
when(secondary.getUuid()).thenReturn("60d979d8-d132-4181-8eca-8dfde50d7df6");
when(storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolURL + volumeDestPath)).thenReturn(secondary);
when(primary.getPhysicalDisk(command.getVolumePath() + ".qcow2")).thenReturn(disk);
when(storagePoolMgr.copyPhysicalDisk(disk, destVolumeName, primary, 0)).thenReturn(disk);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
@ -4892,7 +4819,6 @@ public class LibvirtComputingResourceTest {
when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool);
when(storagePool.getPhysicalDisk(path)).thenReturn(vol);
when(vol.getPath()).thenReturn(path);
when(libvirtComputingResourceMock.getResizeScriptType(storagePool, vol)).thenReturn("FILE");
when(storagePool.getType()).thenReturn(StoragePoolType.RBD);
when(vol.getFormat()).thenReturn(PhysicalDiskFormat.FILE);
@ -4953,7 +4879,6 @@ public class LibvirtComputingResourceTest {
when(storagePool.getPhysicalDisk(path)).thenReturn(vol);
when(vol.getPath()).thenReturn(path);
when(storagePool.getType()).thenReturn(StoragePoolType.Linstor);
when(vol.getFormat()).thenReturn(PhysicalDiskFormat.RAW);
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try {
@ -5051,7 +4976,6 @@ public class LibvirtComputingResourceTest {
when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool);
when(storagePool.getPhysicalDisk(path)).thenReturn(vol);
when(vol.getPath()).thenReturn(path);
when(libvirtComputingResourceMock.getResizeScriptType(storagePool, vol)).thenReturn("FILE");
when(storagePool.getType()).thenReturn(StoragePoolType.RBD);
when(vol.getFormat()).thenReturn(PhysicalDiskFormat.FILE);
@ -5213,8 +5137,6 @@ public class LibvirtComputingResourceTest {
final String vmName = "Test";
when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr);
when(vmSpec.getNics()).thenReturn(nics);
when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
when(vmSpec.getName()).thenReturn(vmName);
when(libvirtComputingResourceMock.createVMFromSpec(vmSpec)).thenReturn(vmDef);
@ -5344,8 +5266,6 @@ public class LibvirtComputingResourceTest {
@Test
public void testStartCommand() throws Exception {
PowerMockito.mockStatic(SshHelper.class);
PowerMockito.doNothing().when(SshHelper.class, "scpTo", Mockito.anyString(), Mockito.anyInt(), Mockito.anyString(), Mockito.any(File.class), nullable(String.class), Mockito.anyString(), Mockito.any(String[].class), Mockito.anyString());
final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
final com.cloud.host.Host host = Mockito.mock(com.cloud.host.Host.class);
final boolean executeInSequence = false;
@ -5360,7 +5280,6 @@ public class LibvirtComputingResourceTest {
final NicTO nic = Mockito.mock(NicTO.class);
final NicTO[] nics = new NicTO[]{nic};
final int[] vms = new int[0];
final String vmName = "Test";
final String controlIp = "127.0.0.1";
@ -5374,7 +5293,6 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try {
when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
when(conn.listDomains()).thenReturn(vms);
doNothing().when(libvirtComputingResourceMock).createVbd(conn, vmSpec, vmName, vmDef);
} catch (final LibvirtException e) {
fail(e.getMessage());
@ -5404,12 +5322,18 @@ public class LibvirtComputingResourceTest {
fail(e.getMessage());
}
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
try (MockedStatic<SshHelper> sshHelperMockedStatic = Mockito.mockStatic(SshHelper.class)) {
sshHelperMockedStatic.when(() -> SshHelper.scpTo(
Mockito.anyString(), Mockito.anyInt(),
Mockito.anyString(), Mockito.any(File.class), nullable(String.class), Mockito.anyString(),
Mockito.any(String[].class), Mockito.anyString())).thenAnswer(invocation -> null);
final Answer answer = wrapper.execute(command, libvirtComputingResourceMock);
assertTrue(answer.getResult());
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(command, libvirtComputingResourceMock);
assertTrue(answer.getResult());
}
verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr();
verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper();
try {
@ -5421,8 +5345,6 @@ public class LibvirtComputingResourceTest {
@Test
public void testStartCommandIsolationEc2() throws Exception {
PowerMockito.mockStatic(SshHelper.class);
PowerMockito.doNothing().when(SshHelper.class, "scpTo", Mockito.anyString(), Mockito.anyInt(), Mockito.anyString(), Mockito.any(File.class), nullable(String.class), Mockito.anyString(), Mockito.any(String[].class), Mockito.anyString());
final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
final com.cloud.host.Host host = Mockito.mock(com.cloud.host.Host.class);
final boolean executeInSequence = false;
@ -5437,7 +5359,6 @@ public class LibvirtComputingResourceTest {
final NicTO nic = Mockito.mock(NicTO.class);
final NicTO[] nics = new NicTO[]{nic};
final int[] vms = new int[0];
final String vmName = "Test";
final String controlIp = "127.0.0.1";
@ -5451,7 +5372,6 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try {
when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
when(conn.listDomains()).thenReturn(vms);
doNothing().when(libvirtComputingResourceMock).createVbd(conn, vmSpec, vmName, vmDef);
} catch (final LibvirtException e) {
fail(e.getMessage());
@ -5467,9 +5387,6 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResourceMock.startVM(conn, vmName, vmDef.toString())).thenReturn("SUCCESS");
when(nic.isSecurityGroupEnabled()).thenReturn(true);
when(nic.getIsolationUri()).thenReturn(new URI("ec2://test"));
when(vmSpec.getBootArgs()).thenReturn("ls -lart");
when(libvirtComputingResourceMock.passCmdLine(vmName, vmSpec.getBootArgs())).thenReturn(true);
@ -5483,22 +5400,26 @@ public class LibvirtComputingResourceTest {
fail(e.getMessage());
} catch (final LibvirtException e) {
fail(e.getMessage());
} catch (final URISyntaxException e) {
fail(e.getMessage());
}
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
try (MockedStatic<SshHelper> sshHelperMockedStatic = Mockito.mockStatic(SshHelper.class)) {
sshHelperMockedStatic.when(() -> SshHelper.scpTo(
Mockito.anyString(), Mockito.anyInt(),
Mockito.anyString(), Mockito.any(File.class), nullable(String.class), Mockito.anyString(),
Mockito.any(String[].class), Mockito.anyString())).thenAnswer(invocation -> null);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(command, libvirtComputingResourceMock);
assertTrue(answer.getResult());
final Answer answer = wrapper.execute(command, libvirtComputingResourceMock);
assertTrue(answer.getResult());
verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr();
verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper();
try {
verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
} catch (final LibvirtException e) {
fail(e.getMessage());
verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr();
verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper();
try {
verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
} catch (final LibvirtException e) {
fail(e.getMessage());
}
}
}
@ -5517,26 +5438,17 @@ public class LibvirtComputingResourceTest {
final NicTO nic = Mockito.mock(NicTO.class);
final NicTO[] nics = new NicTO[]{nic};
int vmId = 1;
final int[] vms = new int[]{vmId};
final Domain dm = Mockito.mock(Domain.class);
final String vmName = "Test";
when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr);
when(vmSpec.getNics()).thenReturn(nics);
when(vmSpec.getType()).thenReturn(VirtualMachine.Type.User);
when(vmSpec.getName()).thenReturn(vmName);
when(vmSpec.getMaxRam()).thenReturn(512L);
when(libvirtComputingResourceMock.createVMFromSpec(vmSpec)).thenReturn(vmDef);
when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try {
when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
when(conn.listDomains()).thenReturn(vms);
when(conn.domainLookupByID(vmId)).thenReturn(dm);
when(dm.getMaxMemory()).thenReturn(1024L);
when(dm.getName()).thenReturn(vmName);
doNothing().when(libvirtComputingResourceMock).createVbd(conn, vmSpec, vmName, vmDef);
} catch (final LibvirtException e) {
fail(e.getMessage());
@ -5695,9 +5607,7 @@ public class LibvirtComputingResourceTest {
@Test
public void testSetQuotaAndPeriodNoCpuLimitUse() {
double pct = 0.33d;
Mockito.when(vmTO.getLimitCpuUse()).thenReturn(false);
Mockito.when(vmTO.getCpuQuotaPercentage()).thenReturn(pct);
CpuTuneDef cpuTuneDef = new CpuTuneDef();
final LibvirtComputingResource lcr = new LibvirtComputingResource();
lcr.setQuotaAndPeriod(vmTO, cpuTuneDef);
@ -5746,7 +5656,7 @@ public class LibvirtComputingResourceTest {
public void testAddExtraConfigComponentEmptyExtraConfig() {
libvirtComputingResourceMock = new LibvirtComputingResource();
libvirtComputingResourceMock.addExtraConfigComponent(new HashMap<>(), vmDef);
Mockito.verify(vmDef, never()).addComp(any());
Mockito.verify(vmDef, never()).addComp(Mockito.any());
}
@Test
@ -5757,7 +5667,7 @@ public class LibvirtComputingResourceTest {
extraConfig.put("extraconfig-2", "value2");
extraConfig.put("extraconfig-3", "value3");
libvirtComputingResourceMock.addExtraConfigComponent(extraConfig, vmDef);
Mockito.verify(vmDef, times(1)).addComp(any());
Mockito.verify(vmDef, times(1)).addComp(Mockito.any());
}
public void validateGetCurrentMemAccordingToMemBallooningWithoutMemBalooning(){
@ -5871,8 +5781,6 @@ public class LibvirtComputingResourceTest {
private DiskDef configureAndTestSetDiskIoDriverTest(long hypervisorLibvirtVersion, long hypervisorQemuVersion) {
DiskDef diskDef = new DiskDef();
LibvirtComputingResource libvirtComputingResourceSpy = Mockito.spy(new LibvirtComputingResource());
Mockito.when(libvirtComputingResourceSpy.getHypervisorLibvirtVersion()).thenReturn(hypervisorLibvirtVersion);
Mockito.when(libvirtComputingResourceSpy.getHypervisorQemuVersion()).thenReturn(hypervisorQemuVersion);
libvirtComputingResourceSpy.setDiskIoDriver(diskDef, IoDriverPolicy.IO_URING);
return diskDef;
}
@ -5937,58 +5845,69 @@ public class LibvirtComputingResourceTest {
@Test
public void testConfigureLocalStorageWithMultiplePaths() throws ConfigurationException {
PowerMockito.mockStatic(AgentPropertiesFileHandler.class);
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_PATH))).thenReturn("/var/lib/libvirt/images/,/var/lib/libvirt/images2/");
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_UUID))).thenReturn(UUID.randomUUID().toString() + "," + UUID.randomUUID().toString());
try (MockedStatic<AgentPropertiesFileHandler> ignored = Mockito.mockStatic(AgentPropertiesFileHandler.class)) {
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_PATH)))
.thenReturn("/var/lib/libvirt/images/,/var/lib/libvirt/images2/");
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_UUID)))
.thenReturn(UUID.randomUUID().toString() + "," + UUID.randomUUID().toString());
libvirtComputingResourceSpy.configureLocalStorage();
libvirtComputingResourceSpy.configureLocalStorage();
}
}
@Test(expected = ConfigurationException.class)
public void testConfigureLocalStorageWithDifferentLength() throws Exception {
PowerMockito.mockStatic(AgentPropertiesFileHandler.class);
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_PATH))).thenReturn("/var/lib/libvirt/images/,/var/lib/libvirt/images2/");
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_UUID))).thenReturn(UUID.randomUUID().toString());
try (MockedStatic<AgentPropertiesFileHandler> ignored = Mockito.mockStatic(AgentPropertiesFileHandler.class)) {
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_PATH)))
.thenReturn("/var/lib/libvirt/images/,/var/lib/libvirt/images2/");
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_UUID)))
.thenReturn(UUID.randomUUID().toString());
libvirtComputingResourceSpy.configureLocalStorage();
libvirtComputingResourceSpy.configureLocalStorage();
}
}
@Test(expected = ConfigurationException.class)
public void testConfigureLocalStorageWithInvalidUUID() throws ConfigurationException {
PowerMockito.mockStatic(AgentPropertiesFileHandler.class);
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_PATH))).thenReturn("/var/lib/libvirt/images/");
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_UUID))).thenReturn("111111");
try (MockedStatic<AgentPropertiesFileHandler> ignored = Mockito.mockStatic(AgentPropertiesFileHandler.class)) {
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_PATH)))
.thenReturn("/var/lib/libvirt/images/");
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_UUID)))
.thenReturn("111111");
libvirtComputingResourceSpy.configureLocalStorage();
libvirtComputingResourceSpy.configureLocalStorage();
}
}
@Test
@PrepareForTest({AgentPropertiesFileHandler.class, NetUtils.class})
public void defineResourceNetworkInterfacesTestUseProperties() {
NetworkInterface networkInterfaceMock1 = PowerMockito.mock(NetworkInterface.class);
NetworkInterface networkInterfaceMock2 = PowerMockito.mock(NetworkInterface.class);
NetworkInterface networkInterfaceMock1 = Mockito.mock(NetworkInterface.class);
NetworkInterface networkInterfaceMock2 = Mockito.mock(NetworkInterface.class);
PowerMockito.mockStatic(AgentPropertiesFileHandler.class);
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn("cloudbr15", "cloudbr28");
try (MockedStatic<AgentPropertiesFileHandler> ignored = Mockito.mockStatic(AgentPropertiesFileHandler.class);
MockedStatic<NetUtils> netUtilsMockedStatic = Mockito.mockStatic(NetUtils.class)) {
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn("cloudbr15",
"cloudbr28");
PowerMockito.mockStatic(NetUtils.class);
PowerMockito.when(NetUtils.getNetworkInterface(Mockito.anyString())).thenReturn(networkInterfaceMock1, networkInterfaceMock2);
Mockito.when(NetUtils.getNetworkInterface(Mockito.anyString())).thenReturn(networkInterfaceMock1,
networkInterfaceMock2);
libvirtComputingResourceSpy.defineResourceNetworkInterfaces(null);
libvirtComputingResourceSpy.defineResourceNetworkInterfaces(null);
ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
PowerMockito.verifyStatic(NetUtils.class, Mockito.times(2));
NetUtils.getNetworkInterface(keyCaptor.capture());
ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
netUtilsMockedStatic.verify(() -> NetUtils.getNetworkInterface(keyCaptor.capture()), Mockito.times(2));
List<String> keys = keyCaptor.getAllValues();
Assert.assertEquals("cloudbr15", keys.get(0));
Assert.assertEquals("cloudbr28", keys.get(1));
Assert.assertEquals("cloudbr15", libvirtComputingResourceSpy._privBridgeName);
Assert.assertEquals("cloudbr28", libvirtComputingResourceSpy._publicBridgeName);
List<String> keys = keyCaptor.getAllValues();
Assert.assertEquals("cloudbr15", keys.get(0));
Assert.assertEquals("cloudbr28", keys.get(1));
Assert.assertEquals(networkInterfaceMock1, libvirtComputingResourceSpy.getPrivateNic());
Assert.assertEquals(networkInterfaceMock2, libvirtComputingResourceSpy.getPublicNic());
Assert.assertEquals("cloudbr15", libvirtComputingResourceSpy._privBridgeName);
Assert.assertEquals("cloudbr28", libvirtComputingResourceSpy._publicBridgeName);
Assert.assertEquals(networkInterfaceMock1, libvirtComputingResourceSpy.getPrivateNic());
Assert.assertEquals(networkInterfaceMock2, libvirtComputingResourceSpy.getPublicNic());
}
}
@Test
@ -6037,24 +5956,26 @@ public class LibvirtComputingResourceTest {
}
@Test
@PrepareForTest(value = {LibvirtComputingResource.class})
public void testGetHaproxyStatsMethod() throws Exception {
PowerMockito.whenNew(Script.class).withAnyArguments().thenReturn(scriptMock);
doNothing().when(scriptMock).add(Mockito.anyString());
when(scriptMock.execute()).thenReturn(null);
when(scriptMock.execute(Mockito.any())).thenReturn(null);
try (MockedConstruction<Script> scriptMockedConstruction = Mockito.mockConstruction(Script.class,
(mock, context) -> {
doNothing().when(mock).add(Mockito.anyString());
when(mock.execute()).thenReturn(null);
when(mock.execute(Mockito.any())).thenReturn(null);
});
MockedConstruction<OneLineParser> ignored = Mockito.mockConstruction(OneLineParser.class, (mock, context) -> {
when(mock.getLine()).thenReturn("result");
})) {
PowerMockito.whenNew(OneLineParser.class).withNoArguments().thenReturn(statsParserMock);
when(statsParserMock.getLine()).thenReturn("result");
String result = libvirtComputingResourceSpy.getHaproxyStats(privateIp, publicIp, port);
String result = libvirtComputingResourceSpy.getHaproxyStats(privateIp, publicIp, port);
Assert.assertEquals("result", result);
verify(scriptMock, times(4)).add(anyString());
verify(scriptMock).add("get_haproxy_stats.sh");
verify(scriptMock).add(privateIp);
verify(scriptMock).add(publicIp);
verify(scriptMock).add(String.valueOf(port));
Assert.assertEquals("result", result);
verify(scriptMockedConstruction.constructed().get(0), times(4)).add(Mockito.anyString());
verify(scriptMockedConstruction.constructed().get(0)).add("get_haproxy_stats.sh");
verify(scriptMockedConstruction.constructed().get(0)).add(privateIp);
verify(scriptMockedConstruction.constructed().get(0)).add(publicIp);
verify(scriptMockedConstruction.constructed().get(0)).add(String.valueOf(port));
}
}
@Test
@ -6091,45 +6012,45 @@ public class LibvirtComputingResourceTest {
}
@Test
@PrepareForTest(value = {LibvirtComputingResource.class})
public void testNetworkUsageMethod1() throws Exception {
PowerMockito.whenNew(Script.class).withAnyArguments().thenReturn(scriptMock);
doNothing().when(scriptMock).add(Mockito.anyString());
when(scriptMock.execute()).thenReturn(null);
when(scriptMock.execute(Mockito.any())).thenReturn(null);
try (MockedConstruction<Script> scriptMockedConstruction = Mockito.mockConstruction(Script.class,
(mock, context) -> {
doNothing().when(mock).add(Mockito.anyString());
when(mock.execute()).thenReturn(null);
when(mock.execute(Mockito.any())).thenReturn(null);
}); MockedConstruction<OneLineParser> ignored2 = Mockito.mockConstruction(OneLineParser.class,
(mock, context) -> {when(mock.getLine()).thenReturn("result");})) {
PowerMockito.whenNew(OneLineParser.class).withNoArguments().thenReturn(statsParserMock);
when(statsParserMock.getLine()).thenReturn("result");
String result = libvirtComputingResourceSpy.networkUsage(privateIp, "get", "eth0", publicIp);
String result = libvirtComputingResourceSpy.networkUsage(privateIp, "get", "eth0", publicIp);
Assert.assertEquals("result", result);
verify(scriptMockedConstruction.constructed().get(0), times(3)).add(Mockito.anyString());
verify(scriptMockedConstruction.constructed().get(0)).add("netusage.sh");
verify(scriptMockedConstruction.constructed().get(0)).add(privateIp);
verify(scriptMockedConstruction.constructed().get(0)).add("-g");
Assert.assertEquals("result", result);
verify(scriptMock, times(3)).add(anyString());
verify(scriptMock).add("netusage.sh");
verify(scriptMock).add(privateIp);
verify(scriptMock).add("-g");
verify(scriptMock).add("-l", publicIp);
verify(scriptMockedConstruction.constructed().get(0)).add("-l", publicIp);
}
}
@Test
@PrepareForTest(value = {LibvirtComputingResource.class})
public void testNetworkUsageMethod2() throws Exception {
PowerMockito.whenNew(Script.class).withAnyArguments().thenReturn(scriptMock);
doNothing().when(scriptMock).add(Mockito.anyString());
when(scriptMock.execute()).thenReturn(null);
when(scriptMock.execute(Mockito.any())).thenReturn(null);
try (MockedConstruction<Script> scriptMockedConstruction = Mockito.mockConstruction(Script.class,
(mock, context) -> {
doNothing().when(mock).add(Mockito.anyString());
when(mock.execute()).thenReturn(null);
when(mock.execute(Mockito.any())).thenReturn(null);
}); MockedConstruction<OneLineParser> ignored2 = Mockito.mockConstruction(OneLineParser.class,
(mock, context) -> {when(mock.getLine()).thenReturn("result");})) {
PowerMockito.whenNew(OneLineParser.class).withNoArguments().thenReturn(statsParserMock);
when(statsParserMock.getLine()).thenReturn("result");
String result = libvirtComputingResourceSpy.networkUsage(privateIp, "get", "eth0", null);
String result = libvirtComputingResourceSpy.networkUsage(privateIp, "get", "eth0", null);
Assert.assertEquals("result", result);
verify(scriptMock, times(3)).add(anyString());
verify(scriptMock).add("netusage.sh");
verify(scriptMock).add(privateIp);
verify(scriptMock).add("-g");
Assert.assertEquals("result", result);
verify(scriptMockedConstruction.constructed().get(0), times(3)).add(Mockito.anyString());
verify(scriptMockedConstruction.constructed().get(0)).add("netusage.sh");
verify(scriptMockedConstruction.constructed().get(0)).add(privateIp);
verify(scriptMockedConstruction.constructed().get(0)).add("-g");
}
}
@Test
@ -6166,38 +6087,49 @@ public class LibvirtComputingResourceTest {
@Test
public void getCurrentVmBalloonStatsPeriodTestWhenMemBalloonIsDisabled() {
Integer expected = 0;
PowerMockito.mockStatic(AgentPropertiesFileHandler.class);
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_DISABLE))).thenReturn(true);
try (MockedStatic<AgentPropertiesFileHandler> ignored = Mockito.mockStatic(AgentPropertiesFileHandler.class)) {
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_DISABLE)))
.thenReturn(true);
Integer result = libvirtComputingResourceSpy.getCurrentVmBalloonStatsPeriod();
Integer result = libvirtComputingResourceSpy.getCurrentVmBalloonStatsPeriod();
Assert.assertEquals(expected, result);
Assert.assertEquals(expected, result);
}
}
@Test
public void getCurrentVmBalloonStatsPeriodTestWhenStatsPeriodIsZero() {
Integer expected = 0;
PowerMockito.mockStatic(AgentPropertiesFileHandler.class);
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_DISABLE))).thenReturn(false);
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_STATS_PERIOD))).thenReturn(0);
try (MockedStatic<AgentPropertiesFileHandler> ignored = Mockito.mockStatic(AgentPropertiesFileHandler.class)) {
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_DISABLE)))
.thenReturn(false);
Mockito.when(
AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_STATS_PERIOD)))
.thenReturn(0);
Integer result = libvirtComputingResourceSpy.getCurrentVmBalloonStatsPeriod();
Integer result = libvirtComputingResourceSpy.getCurrentVmBalloonStatsPeriod();
Mockito.verify(loggerMock).info(String.format("The [%s] property is set to '0', this prevents memory statistics from being displayed correctly. "
+ "Adjust (increase) the value of this parameter to correct this.", AgentProperties.VM_MEMBALLOON_STATS_PERIOD.getName()));
Assert.assertEquals(expected, result);
Mockito.verify(loggerMock).info(String.format(
"The [%s] property is set to '0', this prevents memory statistics from being displayed correctly. "
+ "Adjust (increase) the value of this parameter to correct this.",
AgentProperties.VM_MEMBALLOON_STATS_PERIOD.getName()));
Assert.assertEquals(expected, result);
}
}
@Test
public void getCurrentVmBalloonStatsPeriodTestSuccess() {
Integer expected = 60;
PowerMockito.mockStatic(AgentPropertiesFileHandler.class);
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_DISABLE))).thenReturn(false);
PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_STATS_PERIOD))).thenReturn(60);
try (MockedStatic<AgentPropertiesFileHandler> ignored = Mockito.mockStatic(AgentPropertiesFileHandler.class)) {
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_DISABLE)))
.thenReturn(false);
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.VM_MEMBALLOON_STATS_PERIOD)))
.thenReturn(60);
Integer result = libvirtComputingResourceSpy.getCurrentVmBalloonStatsPeriod();
Integer result = libvirtComputingResourceSpy.getCurrentVmBalloonStatsPeriod();
Assert.assertEquals(expected, result);
Assert.assertEquals(expected, result);
}
}
private void prepareMocksToSetupMemoryBalloonStatsPeriod(Integer currentVmBalloonStatsPeriod) throws LibvirtException {
@ -6216,12 +6148,14 @@ public class LibvirtComputingResourceTest {
memBalloonDef.defVirtioMemBalloon("60");
Mockito.when(parserMock.parseDomainXML(Mockito.anyString())).thenReturn(true);
Mockito.when(parserMock.getMemBalloon()).thenReturn(memBalloonDef);
PowerMockito.mockStatic(Script.class);
PowerMockito.when(Script.runSimpleBashScript(Mockito.any())).thenReturn(null);
try (MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
Mockito.when(Script.runSimpleBashScript(Mockito.any())).thenReturn(null);
libvirtComputingResourceSpy.setupMemoryBalloonStatsPeriod(connMock);
libvirtComputingResourceSpy.setupMemoryBalloonStatsPeriod(connMock);
Mockito.verify(loggerMock).debug("The memory balloon stats period [0] has been set successfully for the VM (Libvirt Domain) with ID [1] and name [fake-VM-name].");
Mockito.verify(loggerMock).debug(
"The memory balloon stats period [0] has been set successfully for the VM (Libvirt Domain) with ID [1] and name [fake-VM-name].");
}
}
@Test
@ -6231,13 +6165,16 @@ public class LibvirtComputingResourceTest {
memBalloonDef.defVirtioMemBalloon("0");
Mockito.when(parserMock.parseDomainXML(Mockito.anyString())).thenReturn(true);
Mockito.when(parserMock.getMemBalloon()).thenReturn(memBalloonDef);
PowerMockito.mockStatic(Script.class);
PowerMockito.when(Script.runSimpleBashScript(Mockito.eq("virsh dommemstat 1 --period 60 --live"))).thenReturn("some-fake-error");
try (MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
Mockito.when(Script.runSimpleBashScript(Mockito.eq("virsh dommemstat 1 --period 60 --live")))
.thenReturn("some-fake-error");
libvirtComputingResourceSpy.setupMemoryBalloonStatsPeriod(connMock);
libvirtComputingResourceSpy.setupMemoryBalloonStatsPeriod(connMock);
Mockito.verify(loggerMock).error("Unable to set up memory balloon stats period for VM (Libvirt Domain) with ID [1] due to an error when running the [virsh "
+ "dommemstat 1 --period 60 --live] command. Output: [some-fake-error].");
Mockito.verify(loggerMock).error(
"Unable to set up memory balloon stats period for VM (Libvirt Domain) with ID [1] due to an error when running the [virsh "
+ "dommemstat 1 --period 60 --live] command. Output: [some-fake-error].");
}
}
@Test
@ -6247,14 +6184,16 @@ public class LibvirtComputingResourceTest {
memBalloonDef.defVirtioMemBalloon("0");
Mockito.when(parserMock.parseDomainXML(Mockito.anyString())).thenReturn(true);
Mockito.when(parserMock.getMemBalloon()).thenReturn(memBalloonDef);
PowerMockito.mockStatic(Script.class);
PowerMockito.when(Script.runSimpleBashScript(Mockito.eq("virsh dommemstat 1 --period 60 --live"))).thenReturn(null);
try (MockedStatic<Script> scriptMockedStatic = Mockito.mockStatic(Script.class)) {
Mockito.when(Script.runSimpleBashScript(Mockito.eq("virsh dommemstat 1 --period 60 --live")))
.thenReturn(null);
libvirtComputingResourceSpy.setupMemoryBalloonStatsPeriod(connMock);
libvirtComputingResourceSpy.setupMemoryBalloonStatsPeriod(connMock);
PowerMockito.verifyStatic(Script.class);
Script.runSimpleBashScript("virsh dommemstat 1 --period 60 --live");
Mockito.verify(loggerMock, Mockito.never()).error(Mockito.anyString());
scriptMockedStatic.verify(() -> Script.runSimpleBashScript("virsh dommemstat 1 --period 60 --live"),
Mockito.times(1));
Mockito.verify(loggerMock, Mockito.never()).error(Mockito.anyString());
}
}
@Test

View File

@ -31,9 +31,14 @@ import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef;
import junit.framework.TestCase;
import org.apache.cloudstack.utils.qemu.QemuObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class LibvirtDomainXMLParserTest extends TestCase {
@Test
public void testDomainXMLParser() {
int vncPort = 5900;

View File

@ -20,12 +20,18 @@ package com.cloud.hypervisor.kvm.resource;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
@RunWith(MockitoJUnitRunner.class)
public class LibvirtKvmAgentHookTest extends TestCase {
private final String source = "<xml />";
@ -47,20 +53,21 @@ public class LibvirtKvmAgentHookTest extends TestCase {
"new BaseTransform()\n" +
"\n";
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
super.setUp();
PrintWriter pw = new PrintWriter(new File(dir, script));
pw.println(testImpl);
pw.close();
}
@Override
protected void tearDown() throws Exception {
@After
public void tearDown() throws Exception {
new File(dir, script).delete();
super.tearDown();
}
@Test
public void testTransform() throws IOException, ResourceException, ScriptException {
LibvirtKvmAgentHook t = new LibvirtKvmAgentHook(dir, script, method);
assertEquals(t.isInitialized(), true);
@ -68,24 +75,28 @@ public class LibvirtKvmAgentHookTest extends TestCase {
assertEquals(result, source + source);
}
@Test
public void testWrongMethod() throws IOException, ResourceException, ScriptException {
LibvirtKvmAgentHook t = new LibvirtKvmAgentHook(dir, script, "methodX");
assertEquals(t.isInitialized(), true);
assertEquals(t.handle(source), source);
}
@Test
public void testNullMethod() throws IOException, ResourceException, ScriptException {
LibvirtKvmAgentHook t = new LibvirtKvmAgentHook(dir, script, methodNull);
assertEquals(t.isInitialized(), true);
assertEquals(t.handle(source), null);
}
@Test
public void testWrongScript() throws IOException, ResourceException, ScriptException {
LibvirtKvmAgentHook t = new LibvirtKvmAgentHook(dir, "wrong-script.groovy", method);
assertEquals(t.isInitialized(), false);
assertEquals(t.handle(source), source);
}
@Test
public void testWrongDir() throws IOException, ResourceException, ScriptException {
LibvirtKvmAgentHook t = new LibvirtKvmAgentHook("/" + UUID.randomUUID().toString() + "-dir", script, method);
assertEquals(t.isInitialized(), false);

View File

@ -21,9 +21,14 @@ package com.cloud.hypervisor.kvm.resource;
import junit.framework.TestCase;
import com.cloud.hypervisor.kvm.resource.LibvirtSecretDef.Usage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class LibvirtSecretDefTest extends TestCase {
@Test
public void testVolumeSecretDef() {
String uuid = "db66f42b-a79e-4666-9910-9dfc8a024427";
String name = "myEncryptedQCOW2";
@ -38,6 +43,7 @@ public class LibvirtSecretDefTest extends TestCase {
assertEquals(expectedXml, def.toString());
}
@Test
public void testCephSecretDef() {
String uuid = "a9febe83-ac5c-467a-bf19-eb75325ec23c";
String name = "admin";

View File

@ -23,9 +23,13 @@ import junit.framework.TestCase;
import com.cloud.hypervisor.kvm.resource.LibvirtStoragePoolDef.PoolType;
import com.cloud.hypervisor.kvm.resource.LibvirtStoragePoolDef.AuthenticationType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class LibvirtStoragePoolDefTest extends TestCase {
@Test
public void testSetGetStoragePool() {
PoolType type = PoolType.NETFS;
String name = "myNFSPool";
@ -45,6 +49,7 @@ public class LibvirtStoragePoolDefTest extends TestCase {
assertEquals(targetPath, pool.getTargetPath());
}
@Test
public void testNfsStoragePool() {
PoolType type = PoolType.NETFS;
String name = "myNFSPool";
@ -62,6 +67,7 @@ public class LibvirtStoragePoolDefTest extends TestCase {
assertEquals(expectedXml, pool.toString());
}
@Test
public void testRbdStoragePool() {
PoolType type = PoolType.RBD;
String name = "myRBDPool";
@ -83,6 +89,7 @@ public class LibvirtStoragePoolDefTest extends TestCase {
assertEquals(expectedXml, pool.toString());
}
@Test
public void testRbdStoragePoolWithoutPort() {
PoolType type = PoolType.RBD;
String name = "myRBDPool";

View File

@ -21,9 +21,14 @@ package com.cloud.hypervisor.kvm.resource;
import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class LibvirtStoragePoolXMLParserTest extends TestCase {
@Test
public void testParseNfsStoragePoolXML() {
String poolXML = "<pool type='netfs'>\n" +
" <name>feff06b5-84b2-3258-b5f9-1953217295de</name>\n" +
@ -52,6 +57,7 @@ public class LibvirtStoragePoolXMLParserTest extends TestCase {
Assert.assertEquals("10.11.12.13", pool.getSourceHost());
}
@Test
public void testParseRbdStoragePoolXMLWithMultipleHosts() {
String poolXML = "<pool type='rbd'>\n" +
" <name>feff06b5-84b2-3258-b5f9-1953217295de</name>\n" +
@ -77,6 +83,7 @@ public class LibvirtStoragePoolXMLParserTest extends TestCase {
Assert.assertEquals(6789, pool.getSourcePort());
}
@Test
public void testParseRbdStoragePoolXMLWithMultipleHostsIpv6() {
String poolXML = "<pool type='rbd'>\n" +
" <name>feff06b5-84b2-3258-b5f9-1953217295de</name>\n" +

View File

@ -22,7 +22,6 @@ package com.cloud.hypervisor.kvm.resource;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import junit.framework.TestCase;
@ -31,17 +30,13 @@ import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ChannelDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.MemBalloonDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SCSIDef;
import org.apache.cloudstack.utils.linux.MemStat;
import org.apache.cloudstack.utils.qemu.QemuObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {MemStat.class})
@RunWith(MockitoJUnitRunner.class)
public class LibvirtVMDefTest extends TestCase {
final String memInfo = "MemTotal: 5830236 kB\n" +
@ -52,12 +47,6 @@ public class LibvirtVMDefTest extends TestCase {
"Active: 4260808 kB\n" +
"Inactive: 949392 kB\n";
@Before
public void setup() throws Exception {
Scanner scanner = new Scanner(memInfo);
PowerMockito.whenNew(Scanner.class).withAnyArguments().thenReturn(scanner);
}
@Test
public void testInterfaceTypeUserWithNetwork() {
LibvirtVMDef.InterfaceDef interfaceDef = new LibvirtVMDef.InterfaceDef();

View File

@ -21,18 +21,16 @@ package com.cloud.hypervisor.kvm.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.eq;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.utils.linux.MemStat;
import org.junit.Before;
import org.junit.Test;
@ -41,13 +39,11 @@ import com.cloud.agent.properties.AgentPropertiesFileHandler;
import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource.BridgeType;
import com.cloud.network.Networks.TrafficType;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {MemStat.class, AgentPropertiesFileHandler.class})
@RunWith(MockitoJUnitRunner.class)
public class LibvirtVifDriverTest {
private LibvirtComputingResource res;
@ -68,8 +64,6 @@ public class LibvirtVifDriverTest {
"Inactive: 949392 kB\n";
@Before
public void setUp() throws Exception {
Scanner scanner = new Scanner(memInfo);
PowerMockito.whenNew(Scanner.class).withAnyArguments().thenReturn(scanner);
// Use a spy because we only want to override getVifDriverClass
LibvirtComputingResource resReal = new LibvirtComputingResource();
res = spy(resReal);
@ -138,43 +132,52 @@ public class LibvirtVifDriverTest {
@Test
public void configureVifDriversTestWhenSetEqualToDefault() throws Exception {
PowerMockito.mockStatic(AgentPropertiesFileHandler.class);
PowerMockito.doReturn(LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME, LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME).when(AgentPropertiesFileHandler.class, "getPropertyValue", Mockito.eq(AgentProperties.LIBVIRT_VIF_DRIVER));
try (MockedStatic<AgentPropertiesFileHandler> agentPropertiesFileHandlerMockedStatic = Mockito.mockStatic(
AgentPropertiesFileHandler.class)) {
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LIBVIRT_VIF_DRIVER)).thenReturn(
LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME,
LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME);
Map<String, Object> params = new HashMap<String, Object>();
Map<String, Object> params = new HashMap<String, Object>();
// Switch res' bridge type for test purposes
res._bridgeType = BridgeType.NATIVE;
configure(params);
checkAllSame(bridgeVifDriver);
// Switch res' bridge type for test purposes
res._bridgeType = BridgeType.NATIVE;
configure(params);
checkAllSame(bridgeVifDriver);
res._bridgeType = BridgeType.OPENVSWITCH;
configure(params);
checkAllSame(ovsVifDriver);
res._bridgeType = BridgeType.OPENVSWITCH;
configure(params);
checkAllSame(ovsVifDriver);
PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.times(2));
AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LIBVIRT_VIF_DRIVER);
agentPropertiesFileHandlerMockedStatic.verify(
() -> AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LIBVIRT_VIF_DRIVER),
Mockito.times(2));
}
}
@Test
public void configureVifDriversTestWhenSetDifferentFromDefault() throws Exception {
PowerMockito.mockStatic(AgentPropertiesFileHandler.class);
PowerMockito.doReturn(LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME, LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME).when(AgentPropertiesFileHandler.class, "getPropertyValue", Mockito.eq(AgentProperties.LIBVIRT_VIF_DRIVER));
try (MockedStatic<AgentPropertiesFileHandler> agentPropertiesFileHandlerMockedStatic = Mockito.mockStatic(
AgentPropertiesFileHandler.class)) {
Mockito.when(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LIBVIRT_VIF_DRIVER))
.thenReturn(LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME,
LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME);
// Tests when explicitly set vif driver to OVS when using regular bridges and vice versa
Map<String, Object> params = new HashMap<String, Object>();
// Tests when explicitly set vif driver to OVS when using regular bridges and vice versa
Map<String, Object> params = new HashMap<String, Object>();
// Switch res' bridge type for test purposes
res._bridgeType = BridgeType.NATIVE;
configure(params);
checkAllSame(ovsVifDriver);
// Switch res' bridge type for test purposes
res._bridgeType = BridgeType.NATIVE;
configure(params);
checkAllSame(ovsVifDriver);
res._bridgeType = BridgeType.OPENVSWITCH;
configure(params);
checkAllSame(bridgeVifDriver);
res._bridgeType = BridgeType.OPENVSWITCH;
configure(params);
checkAllSame(bridgeVifDriver);
PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.times(2));
AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LIBVIRT_VIF_DRIVER);
agentPropertiesFileHandlerMockedStatic.verify(() -> AgentPropertiesFileHandler.getPropertyValue(
AgentProperties.LIBVIRT_VIF_DRIVER), Mockito.times(2));
}
}
@Test

View File

@ -32,13 +32,13 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(PowerMockRunner.class)
@RunWith(MockitoJUnitRunner.class)
public class LibvirtGetAutoScaleMetricsCommandWrapperTest {
@Spy
@ -68,8 +68,8 @@ public class LibvirtGetAutoScaleMetricsCommandWrapperTest {
public void validateVpcStats() {
Mockito.when(getAutoScaleMetricsCommandMock.isForVpc()).thenReturn(true);
PowerMockito.when(libvirtComputingResourceMock.getVPCNetworkStats(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(vpcStats);
PowerMockito.when(libvirtComputingResourceMock.getNetworkLbStats(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(lbStats);
Mockito.when(libvirtComputingResourceMock.getVPCNetworkStats(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(vpcStats);
Mockito.when(libvirtComputingResourceMock.getNetworkLbStats(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(lbStats);
Answer answer = libvirtGetAutoScaleMetricsCommandWrapperSpy.execute(getAutoScaleMetricsCommandMock, libvirtComputingResourceMock);
assertTrue(answer instanceof GetAutoScaleMetricsAnswer);
@ -95,8 +95,8 @@ public class LibvirtGetAutoScaleMetricsCommandWrapperTest {
public void validateNetworkStats() {
Mockito.when(getAutoScaleMetricsCommandMock.isForVpc()).thenReturn(false);
PowerMockito.when(libvirtComputingResourceMock.getNetworkStats(Mockito.any(), Mockito.any())).thenReturn(networkStats);
PowerMockito.when(libvirtComputingResourceMock.getNetworkLbStats(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(lbStats);
Mockito.when(libvirtComputingResourceMock.getNetworkStats(Mockito.any(), Mockito.any())).thenReturn(networkStats);
Mockito.when(libvirtComputingResourceMock.getNetworkLbStats(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(lbStats);
Answer answer = libvirtGetAutoScaleMetricsCommandWrapperSpy.execute(getAutoScaleMetricsCommandMock, libvirtComputingResourceMock);
assertTrue(answer instanceof GetAutoScaleMetricsAnswer);

View File

@ -28,7 +28,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
@ -37,20 +36,16 @@ import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.cloudstack.utils.linux.MemStat;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.libvirt.Connect;
import org.libvirt.StorageVol;
import org.mockito.InOrder;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
@ -65,9 +60,7 @@ import com.cloud.hypervisor.kvm.resource.LibvirtConnection;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
import com.cloud.utils.exception.CloudRuntimeException;
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {LibvirtConnection.class, LibvirtMigrateCommandWrapper.class, MemStat.class})
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*", "org.xml.*"})
@RunWith(MockitoJUnitRunner.class)
public class LibvirtMigrateCommandWrapperTest {
String fullfile =
"<domain type='kvm' id='4'>\n" +
@ -454,11 +447,6 @@ public class LibvirtMigrateCommandWrapperTest {
"Active: 4260808 kB\n" +
"Inactive: 949392 kB\n";
@Before
public void setup() throws Exception {
Scanner scanner = new Scanner(memInfo);
PowerMockito.whenNew(Scanner.class).withAnyArguments().thenReturn(scanner);
}
private static final String sourcePoolUuid = "07eb495b-5590-3877-9fb7-23c6e9a40d40";
private static final String destPoolUuid = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
@ -572,7 +560,7 @@ public class LibvirtMigrateCommandWrapperTest {
public void testReplaceIpForVNCInDescFile() {
final String targetIp = "192.168.22.21";
final String result = libvirtMigrateCmdWrapper.replaceIpForVNCInDescFileAndNormalizePassword(fullfile, targetIp, null, "");
assertTrue("transformation does not live up to expectation:\n" + result, targetfile.equals(result));
assertEquals("transformation does not live up to expectation:\n" + result, targetfile, result);
}
@Test
@ -596,7 +584,7 @@ public class LibvirtMigrateCommandWrapperTest {
final String targetIp = "10.10.10.10";
final String password = "12345678";
final String result = libvirtMigrateCmdWrapper.replaceIpForVNCInDescFileAndNormalizePassword(xmlDesc, targetIp, password, "");
assertTrue("transformation does not live up to expectation:\n" + result, expectedXmlDesc.equals(result));
assertEquals("transformation does not live up to expectation:\n" + result, expectedXmlDesc, result);
}
@Test
@ -620,7 +608,7 @@ public class LibvirtMigrateCommandWrapperTest {
final String targetIp = "localhost.localdomain";
final String password = "12345678";
final String result = libvirtMigrateCmdWrapper.replaceIpForVNCInDescFileAndNormalizePassword(xmlDesc, targetIp, password, "");
assertTrue("transformation does not live up to expectation:\n" + result, expectedXmlDesc.equals(result));
assertEquals("transformation does not live up to expectation:\n" + result, expectedXmlDesc, result);
}
@Test
@ -641,21 +629,21 @@ public class LibvirtMigrateCommandWrapperTest {
@Test
public void deleteLocalVolumeTest() throws Exception {
PowerMockito.mockStatic(LibvirtConnection.class);
Connect conn = Mockito.mock(Connect.class);
PowerMockito.doReturn(conn).when(LibvirtConnection.class, "getConnection");
StorageVol storageVolLookupByPath = Mockito.mock(StorageVol.class);
Mockito.when(conn.storageVolLookupByPath("localPath")).thenReturn(storageVolLookupByPath);
try (MockedStatic<LibvirtConnection> libvirtConnectionMockedStatic = Mockito.mockStatic(LibvirtConnection.class)) {
Connect conn = Mockito.mock(Connect.class);
libvirtMigrateCmdWrapper.deleteLocalVolume("localPath");
Mockito.when(LibvirtConnection.getConnection()).thenReturn(conn);
PowerMockito.verifyStatic(LibvirtConnection.class, Mockito.times(1));
LibvirtConnection.getConnection();
InOrder inOrder = Mockito.inOrder(conn, storageVolLookupByPath);
inOrder.verify(conn, Mockito.times(1)).storageVolLookupByPath("localPath");
inOrder.verify(storageVolLookupByPath, Mockito.times(1)).delete(0);
Mockito.when(conn.storageVolLookupByPath("localPath")).thenReturn(storageVolLookupByPath);
libvirtMigrateCmdWrapper.deleteLocalVolume("localPath");
libvirtConnectionMockedStatic.verify(LibvirtConnection::getConnection, Mockito.times(1));
InOrder inOrder = Mockito.inOrder(conn, storageVolLookupByPath);
inOrder.verify(conn, Mockito.times(1)).storageVolLookupByPath("localPath");
inOrder.verify(storageVolLookupByPath, Mockito.times(1)).delete(0);
}
}
@Test
@ -679,14 +667,14 @@ public class LibvirtMigrateCommandWrapperTest {
MigrateDiskInfo returnedMigrateDiskInfo = libvirtMigrateCmdWrapper.searchDiskDefOnMigrateDiskInfoList(migrateDiskInfoList, disk);
if (isExpectedDiskInfoNull)
Assert.assertEquals(null, returnedMigrateDiskInfo);
Assert.assertNull(returnedMigrateDiskInfo);
else
Assert.assertEquals(migrateDiskInfo, returnedMigrateDiskInfo);
}
@Test
public void deleteOrDisconnectDisksOnSourcePoolTest() {
LibvirtMigrateCommandWrapper spyLibvirtMigrateCmdWrapper = PowerMockito.spy(libvirtMigrateCmdWrapper);
LibvirtMigrateCommandWrapper spyLibvirtMigrateCmdWrapper = Mockito.spy(libvirtMigrateCmdWrapper);
Mockito.doNothing().when(spyLibvirtMigrateCmdWrapper).deleteLocalVolume("volPath");
List<MigrateDiskInfo> migrateDiskInfoList = new ArrayList<>();
@ -750,7 +738,7 @@ public class LibvirtMigrateCommandWrapperTest {
mapMigrateStorage.put("/mnt/812ea6a3-7ad0-30f4-9cab-01e3f2985b98/4650a2f7-fce5-48e2-beaa-bcdf063194e6", diskInfo);
final String result = libvirtMigrateCmdWrapper.replaceStorage(fullfile, mapMigrateStorage, true);
InputStream in = IOUtils.toInputStream(result);
InputStream in = IOUtils.toInputStream(result, "UTF-8");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(in);
@ -787,7 +775,7 @@ public class LibvirtMigrateCommandWrapperTest {
final String result = libvirtMigrateCmdWrapper.replaceStorage(xmlDesc, mapMigrateStorage, false);
final String expectedSecretUuid = LibvirtComputingResource.generateSecretUUIDFromString(volumeFile);
InputStream in = IOUtils.toInputStream(result);
InputStream in = IOUtils.toInputStream(result, "UTF-8");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(in);
@ -827,7 +815,7 @@ public class LibvirtMigrateCommandWrapperTest {
mapMigrateStorage.put("/mnt/07eb495b-5590-3877-9fb7-23c6e9a40d40/bf8621b3-027c-497d-963b-06319650f048", diskInfo);
final String result = libvirtMigrateCmdWrapper.replaceStorage(xmlDesc, mapMigrateStorage, false);
InputStream in = IOUtils.toInputStream(result);
InputStream in = IOUtils.toInputStream(result, "UTF-8");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(in);
@ -839,6 +827,7 @@ public class LibvirtMigrateCommandWrapperTest {
assertXpath(doc, "/domain/devices/disk/encryption/secret/@uuid", expectedSecretUuid);
}
@Test
public void testReplaceStorageXmlDiskNotManagedStorage() throws ParserConfigurationException, TransformerException, SAXException, IOException {
final LibvirtMigrateCommandWrapper lw = new LibvirtMigrateCommandWrapper();
String destDisk1FileName = "XXXXXXXXXXXXXX";

View File

@ -25,19 +25,13 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.util.Scanner;
import org.apache.cloudstack.utils.linux.MemStat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.libvirt.Connect;
import org.libvirt.Domain;
import org.libvirt.LibvirtException;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.agent.api.routing.IpAssocVpcCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
@ -45,10 +39,9 @@ import com.cloud.agent.api.to.IpAddressTO;
import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
import com.cloud.network.Networks;
import com.cloud.utils.ExecutionResult;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {MemStat.class})
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*", "org.xml.*"})
@RunWith(MockitoJUnitRunner.class)
public class LibvirtNetworkElementCommandWrapperTest {
private static final String fullfile = "<domain type='kvm' id='143'>\n"
+ " <name>r-3-VM</name>\n"
@ -229,8 +222,6 @@ public class LibvirtNetworkElementCommandWrapperTest {
"Inactive: 949392 kB\n";
@Before
public void setUp() throws Exception {
Scanner scanner = new Scanner(memInfo);
PowerMockito.whenNew(Scanner.class).withAnyArguments().thenReturn(scanner);
// Use a spy because we only want to override getVifDriverClass
LibvirtComputingResource resReal = new LibvirtComputingResource() {
{

View File

@ -16,9 +16,6 @@
// under the License.
package com.cloud.hypervisor.kvm.resource.wrapper;
import static org.mockito.AdditionalMatchers.not;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
@ -31,9 +28,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.apache.cloudstack.utils.linux.MemStat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -42,11 +37,9 @@ import org.libvirt.Domain;
import org.libvirt.LibvirtException;
import org.mockito.BDDMockito;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.ReplugNicCommand;
@ -59,9 +52,7 @@ import com.cloud.network.Networks;
import com.cloud.utils.script.Script;
import com.cloud.vm.VirtualMachine;
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {Script.class, MemStat.class})
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*", "org.xml.*"})
@RunWith(MockitoJUnitRunner.class)
public class LibvirtReplugNicCommandWrapperTest {
@Mock
@ -206,8 +197,6 @@ public class LibvirtReplugNicCommandWrapperTest {
@Before
public void setUp() throws Exception {
Scanner scanner = new Scanner(memInfo);
PowerMockito.whenNew(Scanner.class).withAnyArguments().thenReturn(scanner);
// Use a spy because we only want to override getVifDriverClass
LibvirtComputingResource resReal = new LibvirtComputingResource();
@ -219,10 +208,9 @@ public class LibvirtReplugNicCommandWrapperTest {
when(_domain.getXMLDesc(0))
.thenReturn(fullfile)
.thenReturn(part_1 + part_3);
when(conn.domainLookupByName(anyString())).thenReturn(_domain);
when(helper.getConnectionByVmName(anyString())).thenReturn(conn);
PowerMockito.mockStatic(Script.class);
BDDMockito.given(Script.findScript(anyString(), anyString())).willReturn("dummypath/tofile.sh");
when(conn.domainLookupByName(Mockito.anyString())).thenReturn(_domain);
when(helper.getConnectionByVmName(Mockito.anyString())).thenReturn(conn);
Map<String, String> pifs = new HashMap<>();
pifs.put(GUEST_BR, "eth0");
@ -238,13 +226,16 @@ public class LibvirtReplugNicCommandWrapperTest {
doNothing().when(ovsVifDriver).getPifs();
doReturn(helper).when(res).getLibvirtUtilitiesHelper();
doReturn(bridgeVifDriver).when(res).getVifDriver(eq(Networks.TrafficType.Guest), anyString());
doReturn(ovsVifDriver).when(res).getVifDriver(Networks.TrafficType.Guest, GUEST_BR);
doReturn(bridgeVifDriver).when(res).getVifDriver(not(eq(Networks.TrafficType.Guest)));
doReturn(Arrays.asList(bridgeVifDriver, ovsVifDriver)).when(res).getAllVifDrivers();
bridgeVifDriver.configure(params);
ovsVifDriver.configure(params);
try (MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
BDDMockito.given(Script.findScript(Mockito.anyString(), Mockito.anyString())).willReturn(
"dummypath/tofile.sh");
bridgeVifDriver.configure(params);
ovsVifDriver.configure(params);
}
}
@Test
@ -292,7 +283,6 @@ public class LibvirtReplugNicCommandWrapperTest {
final Connect conn = Mockito.mock(Connect.class);
when(libvirtComputingResource.getInterfaces(conn, "")).thenReturn(ifaces);
final LibvirtReplugNicCommandWrapper wrapper = new LibvirtReplugNicCommandWrapper();
final NicTO nic = new NicTO();
nic.setType(Networks.TrafficType.Guest);

View File

@ -30,17 +30,16 @@ import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
import com.cloud.agent.api.to.DataStoreTO;
import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
@RunWith(PowerMockRunner.class)
@RunWith(MockitoJUnitRunner.class)
public class LibvirtRevertSnapshotCommandWrapperTest {
LibvirtRevertSnapshotCommandWrapper libvirtRevertSnapshotCommandWrapperSpy = Mockito.spy(LibvirtRevertSnapshotCommandWrapper.class);
@ -82,76 +81,84 @@ public class LibvirtRevertSnapshotCommandWrapperTest {
}
@Test
@PrepareForTest(LibvirtRevertSnapshotCommandWrapper.class)
public void validateReplaceVolumeWithSnapshotReplaceFiles() throws IOException {
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.copy(Mockito.any(Path.class), Mockito.any(Path.class), Mockito.any(CopyOption.class))).thenReturn(pathMock);
libvirtRevertSnapshotCommandWrapperSpy.replaceVolumeWithSnapshot("test", "test");
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class)) {
Mockito.when(Files.copy(Mockito.any(Path.class), Mockito.any(Path.class), Mockito.any(CopyOption.class)))
.thenReturn(pathMock);
libvirtRevertSnapshotCommandWrapperSpy.replaceVolumeWithSnapshot("test", "test");
}
}
@Test (expected = IOException.class)
@PrepareForTest(LibvirtRevertSnapshotCommandWrapper.class)
public void validateReplaceVolumeWithSnapshotThrowsIOException() throws IOException {
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.copy(Mockito.any(Path.class), Mockito.any(Path.class), Mockito.any(CopyOption.class))).thenThrow(IOException.class);
libvirtRevertSnapshotCommandWrapperSpy.replaceVolumeWithSnapshot("test", "test");
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class)) {
Mockito.when(
Files.copy(Mockito.any(Path.class), Mockito.any(Path.class), Mockito.any(CopyOption.class)))
.thenThrow(IOException.class);
libvirtRevertSnapshotCommandWrapperSpy.replaceVolumeWithSnapshot("test", "test");
}
}
@Test
@PrepareForTest(LibvirtRevertSnapshotCommandWrapper.class)
public void validateGetSnapshotPathExistsOnPrimaryStorage() {
String snapshotPath = "test";
Pair<String, SnapshotObjectTO> expectedResult = new Pair<>(snapshotPath, snapshotObjectToPrimaryMock);
Mockito.doReturn(snapshotPath).when(snapshotObjectToPrimaryMock).getPath();
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.exists(Mockito.any(Path.class), Mockito.any())).thenReturn(true);
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class)) {
Mockito.when(Files.exists(Mockito.any(Path.class), Mockito.any())).thenReturn(true);
Pair<String, SnapshotObjectTO> result = libvirtRevertSnapshotCommandWrapperSpy.getSnapshot(snapshotObjectToPrimaryMock, snapshotObjectToSecondaryMock,
kvmStoragePoolPrimaryMock, kvmStoragePoolSecondaryMock);
Pair<String, SnapshotObjectTO> result = libvirtRevertSnapshotCommandWrapperSpy.getSnapshot(
snapshotObjectToPrimaryMock, snapshotObjectToSecondaryMock,
kvmStoragePoolPrimaryMock, kvmStoragePoolSecondaryMock);
Assert.assertEquals(expectedResult.first(), result.first());
Assert.assertEquals(expectedResult.second(), result.second());
Assert.assertEquals(expectedResult.first(), result.first());
Assert.assertEquals(expectedResult.second(), result.second());
}
}
@Test
@PrepareForTest(LibvirtRevertSnapshotCommandWrapper.class)
public void validateGetSnapshotPathExistsOnSecondaryStorage() {
String snapshotPath = "test";
Pair<String, SnapshotObjectTO> expectedResult = new Pair<>(snapshotPath, snapshotObjectToSecondaryMock);
PowerMockito.mockStatic(Files.class, Paths.class);
PowerMockito.when(Paths.get(Mockito.any(), Mockito.any())).thenReturn(pathMock);
PowerMockito.when(Files.exists(Mockito.any(Path.class), Mockito.any())).thenReturn(false);
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class); MockedStatic<Paths> ignored2 = Mockito.mockStatic(Paths.class)) {
Mockito.doReturn(snapshotPath).when(snapshotObjectToSecondaryMock).getPath();
Mockito.doReturn(snapshotPath).when(libvirtRevertSnapshotCommandWrapperSpy).getFullPathAccordingToStorage(Mockito.any(), Mockito.any());
Mockito.when(Paths.get(Mockito.any(), Mockito.any())).thenReturn(pathMock);
Mockito.when(Files.exists(Mockito.any(Path.class), Mockito.any())).thenReturn(false);
Pair<String, SnapshotObjectTO> result = libvirtRevertSnapshotCommandWrapperSpy.getSnapshot(snapshotObjectToPrimaryMock, snapshotObjectToSecondaryMock,
kvmStoragePoolPrimaryMock, kvmStoragePoolSecondaryMock);
Mockito.doReturn(snapshotPath).when(snapshotObjectToSecondaryMock).getPath();
Mockito.doReturn(snapshotPath).when(libvirtRevertSnapshotCommandWrapperSpy).getFullPathAccordingToStorage(
Mockito.any(), Mockito.any());
Assert.assertEquals(expectedResult.first(), result.first());
Assert.assertEquals(expectedResult.second(), result.second());
Pair<String, SnapshotObjectTO> result = libvirtRevertSnapshotCommandWrapperSpy.getSnapshot(
snapshotObjectToPrimaryMock, snapshotObjectToSecondaryMock,
kvmStoragePoolPrimaryMock, kvmStoragePoolSecondaryMock);
Assert.assertEquals(expectedResult.first(), result.first());
Assert.assertEquals(expectedResult.second(), result.second());
}
}
@Test (expected = CloudRuntimeException.class)
@PrepareForTest(LibvirtRevertSnapshotCommandWrapper.class)
public void validateGetSnapshotPathDoesNotExistsOnSecondaryStorageThrows() {
PowerMockito.mockStatic(Files.class, Paths.class);
PowerMockito.when(Paths.get(Mockito.any(), Mockito.any())).thenReturn(pathMock);
PowerMockito.when(Files.exists(Mockito.any(Path.class), Mockito.any())).thenReturn(false);
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class); MockedStatic<Paths> ignored2 = Mockito.mockStatic(Paths.class)) {
Mockito.doReturn(null).when(snapshotObjectToSecondaryMock).getPath();
Mockito.when(Paths.get(Mockito.any(), Mockito.any())).thenReturn(pathMock);
Mockito.when(Files.exists(Mockito.any(Path.class), Mockito.any())).thenReturn(false);
libvirtRevertSnapshotCommandWrapperSpy.getSnapshot(snapshotObjectToPrimaryMock, snapshotObjectToSecondaryMock,
kvmStoragePoolPrimaryMock, kvmStoragePoolSecondaryMock);
Mockito.doReturn(null).when(snapshotObjectToSecondaryMock).getPath();
libvirtRevertSnapshotCommandWrapperSpy.getSnapshot(snapshotObjectToPrimaryMock,
snapshotObjectToSecondaryMock,
kvmStoragePoolPrimaryMock, kvmStoragePoolSecondaryMock);
}
}
@Test
public void validateRevertVolumeToSnapshotReplaceSuccessfully() throws IOException {
Mockito.doReturn(volumeObjectToMock).when(snapshotObjectToSecondaryMock).getVolume();
Mockito.doReturn("").when(libvirtRevertSnapshotCommandWrapperSpy).getFullPathAccordingToStorage(Mockito.any(), Mockito.anyString());
Mockito.doReturn(pairStringSnapshotObjectToMock).when(libvirtRevertSnapshotCommandWrapperSpy).getSnapshot(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
Mockito.doNothing().when(libvirtRevertSnapshotCommandWrapperSpy).replaceVolumeWithSnapshot(Mockito.any(), Mockito.any());
libvirtRevertSnapshotCommandWrapperSpy.revertVolumeToSnapshot(snapshotObjectToPrimaryMock, snapshotObjectToSecondaryMock, dataStoreToMock, kvmStoragePoolPrimaryMock,
@ -161,7 +168,6 @@ public class LibvirtRevertSnapshotCommandWrapperTest {
@Test (expected = CloudRuntimeException.class)
public void validateRevertVolumeToSnapshotReplaceVolumeThrowsIOException() throws IOException {
Mockito.doReturn(volumeObjectToMock).when(snapshotObjectToSecondaryMock).getVolume();
Mockito.doReturn("").when(libvirtRevertSnapshotCommandWrapperSpy).getFullPathAccordingToStorage(Mockito.any(), Mockito.anyString());
Mockito.doReturn(pairStringSnapshotObjectToMock).when(libvirtRevertSnapshotCommandWrapperSpy).getSnapshot(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
Mockito.doThrow(IOException.class).when(libvirtRevertSnapshotCommandWrapperSpy).replaceVolumeWithSnapshot(Mockito.any(), Mockito.any());
libvirtRevertSnapshotCommandWrapperSpy.revertVolumeToSnapshot(snapshotObjectToPrimaryMock, snapshotObjectToSecondaryMock, dataStoreToMock, kvmStoragePoolPrimaryMock,

View File

@ -23,6 +23,7 @@ import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.VirtualMachine;
import junit.framework.TestCase;
import org.apache.cloudstack.utils.bytescale.ByteScaleUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -30,14 +31,12 @@ import org.libvirt.Connect;
import org.libvirt.Domain;
import org.libvirt.LibvirtException;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(LibvirtComputingResource.class)
@RunWith(MockitoJUnitRunner.class)
public class LibvirtScaleVmCommandWrapperTest extends TestCase {
@Spy
@ -69,6 +68,8 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
String scalingDetails;
MockedStatic<LibvirtComputingResource> libvirtComputingResourceMocked;
@Before
public void init() {
wrapper = LibvirtRequestWrapper.getInstance();
@ -81,7 +82,13 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
int cpuShares = vcpus * vmTo.getSpeed();
scalingDetails = String.format("%s memory to [%s KiB], CPU cores to [%s] and cpu_shares to [%s]", vmTo.toString(), memory, vcpus, cpuShares);
PowerMockito.mockStatic(LibvirtComputingResource.class);
libvirtComputingResourceMocked = Mockito.mockStatic(LibvirtComputingResource.class);
}
@Override
@After
public void tearDown() throws Exception {
libvirtComputingResourceMocked.close();
}
@Test
@ -89,7 +96,7 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
long runningVcpus = 1;
int newVcpus = 2;
PowerMockito.when(LibvirtComputingResource.countDomainRunningVcpus(Mockito.any())).thenReturn(runningVcpus);
Mockito.when(LibvirtComputingResource.countDomainRunningVcpus(Mockito.any())).thenReturn(runningVcpus);
Mockito.doNothing().when(domainMock).setVcpus(Mockito.anyInt());
libvirtScaleVmCommandWrapperSpy.scaleVcpus(domainMock, newVcpus, scalingDetails);
@ -102,7 +109,7 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
long runningVcpus = 2;
int newVcpus = 2;
PowerMockito.when(LibvirtComputingResource.countDomainRunningVcpus(Mockito.any())).thenReturn(runningVcpus);
Mockito.when(LibvirtComputingResource.countDomainRunningVcpus(Mockito.any())).thenReturn(runningVcpus);
libvirtScaleVmCommandWrapperSpy.scaleVcpus(domainMock, newVcpus, scalingDetails);
@ -114,7 +121,7 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
long runningVcpus = 2;
int newVcpus = 1;
PowerMockito.when(LibvirtComputingResource.countDomainRunningVcpus(Mockito.any())).thenReturn(runningVcpus);
Mockito.when(LibvirtComputingResource.countDomainRunningVcpus(Mockito.any())).thenReturn(runningVcpus);
libvirtScaleVmCommandWrapperSpy.scaleVcpus(domainMock, newVcpus, scalingDetails);
@ -126,7 +133,7 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
long runningVcpus = 1;
int newVcpus = 2;
PowerMockito.when(LibvirtComputingResource.countDomainRunningVcpus(Mockito.any())).thenReturn(runningVcpus);
Mockito.when(LibvirtComputingResource.countDomainRunningVcpus(Mockito.any())).thenReturn(runningVcpus);
Mockito.doThrow(LibvirtException.class).when(domainMock).setVcpus(Mockito.anyInt());
libvirtScaleVmCommandWrapperSpy.scaleVcpus(domainMock, newVcpus, scalingDetails);
@ -139,7 +146,7 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
long currentMemory = 1l;
long newMemory = 0l;
PowerMockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
Mockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
libvirtScaleVmCommandWrapperSpy.scaleMemory(domainMock, newMemory, scalingDetails);
@ -152,7 +159,7 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
long currentMemory = 1l;
long newMemory = 1l;
PowerMockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
Mockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
libvirtScaleVmCommandWrapperSpy.scaleMemory(domainMock, newMemory, scalingDetails);
@ -165,7 +172,7 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
long currentMemory = 1l;
long newMemory = 2l;
PowerMockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
Mockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
Mockito.doReturn("").when(domainMock).getXMLDesc(Mockito.anyInt());
libvirtScaleVmCommandWrapperSpy.scaleMemory(domainMock, newMemory, scalingDetails);
@ -179,7 +186,7 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
long currentMemory = 1l;
long newMemory = 2l;
PowerMockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
Mockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
Mockito.doReturn("<maxMemory slots='16' unit='KiB'>").when(domainMock).getXMLDesc(Mockito.anyInt());
Mockito.doThrow(LibvirtException.class).when(domainMock).attachDevice(Mockito.anyString());
@ -194,7 +201,7 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
long currentMemory = 1l;
long newMemory = 2l;
PowerMockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
Mockito.when(LibvirtComputingResource.getDomainMemory(Mockito.any())).thenReturn(currentMemory);
Mockito.doReturn("<maxMemory slots='16' unit='KiB'>").when(domainMock).getXMLDesc(Mockito.anyInt());
Mockito.doNothing().when(domainMock).attachDevice(Mockito.anyString());
@ -248,11 +255,12 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
int oldShares = 2000;
int newShares = 3000;
PowerMockito.when(LibvirtComputingResource.getCpuShares(Mockito.any())).thenReturn(oldShares);
Mockito.when(LibvirtComputingResource.getCpuShares(Mockito.any())).thenReturn(oldShares);
libvirtScaleVmCommandWrapperSpy.updateCpuShares(domainMock, newShares);
PowerMockito.verifyStatic(LibvirtComputingResource.class, Mockito.times(1));
libvirtComputingResourceMock.setCpuShares(domainMock, newShares);
libvirtComputingResourceMocked.verify(() -> LibvirtComputingResource.setCpuShares(domainMock, newShares),
Mockito.times(1));
;
}
@Test
@ -260,11 +268,12 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
int oldShares = 3000;
int newShares = 2000;
PowerMockito.when(LibvirtComputingResource.getCpuShares(Mockito.any())).thenReturn(oldShares);
Mockito.when(LibvirtComputingResource.getCpuShares(Mockito.any())).thenReturn(oldShares);
libvirtScaleVmCommandWrapperSpy.updateCpuShares(domainMock, newShares);
PowerMockito.verifyStatic(LibvirtComputingResource.class, Mockito.times(0));
libvirtComputingResourceMock.setCpuShares(domainMock, newShares);
libvirtComputingResourceMocked.verify(() -> LibvirtComputingResource.setCpuShares(domainMock, newShares),
Mockito.times(0));
}
@Test
@ -272,10 +281,10 @@ public class LibvirtScaleVmCommandWrapperTest extends TestCase {
int oldShares = 2000;
int newShares = 2000;
PowerMockito.when(LibvirtComputingResource.getCpuShares(Mockito.any())).thenReturn(oldShares);
Mockito.when(LibvirtComputingResource.getCpuShares(Mockito.any())).thenReturn(oldShares);
libvirtScaleVmCommandWrapperSpy.updateCpuShares(domainMock, newShares);
PowerMockito.verifyStatic(LibvirtComputingResource.class, Mockito.times(0));
libvirtComputingResourceMock.setCpuShares(domainMock, newShares);
libvirtComputingResourceMocked.verify(() -> LibvirtComputingResource.setCpuShares(domainMock, newShares),
Mockito.times(0));
}
}

View File

@ -23,13 +23,13 @@ import org.libvirt.Connect;
import org.libvirt.LibvirtException;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
import com.cloud.utils.Pair;
import junit.framework.TestCase;
@RunWith(PowerMockRunner.class)
@RunWith(MockitoJUnitRunner.class)
public class LibvirtUtilitiesHelperTest extends TestCase {
LibvirtUtilitiesHelper libvirtUtilitiesHelperSpy = Mockito.spy(LibvirtUtilitiesHelper.class);

View File

@ -17,17 +17,24 @@
package com.cloud.hypervisor.kvm.storage;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import junit.framework.TestCase;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class KVMPhysicalDiskTest extends TestCase {
@Test
public void testRBDStringBuilder() {
assertEquals(KVMPhysicalDisk.RBDStringBuilder("ceph-monitor", 8000, "admin", "supersecret", "volume1"),
"rbd:volume1:mon_host=ceph-monitor\\:8000:auth_supported=cephx:id=admin:key=supersecret:rbd_default_format=2:client_mount_timeout=30");
}
@Test
public void testRBDStringBuilder2() {
String monHosts = "ceph-monitor1,ceph-monitor2,ceph-monitor3";
int monPort = 3300;
@ -38,6 +45,7 @@ public class KVMPhysicalDiskTest extends TestCase {
assertEquals(expected, actualResult);
}
@Test
public void testRBDStringBuilder3() {
String monHosts = "[fc00:1234::1],[fc00:1234::2],[fc00:1234::3]";
int monPort = 3300;
@ -48,6 +56,7 @@ public class KVMPhysicalDiskTest extends TestCase {
assertEquals(expected, actualResult);
}
@Test
public void testAttributes() {
String name = "3bc186e0-6c29-45bf-b2b0-ddef6f91f5ef";
String path = "/" + name;

View File

@ -39,6 +39,7 @@ import java.util.List;
import java.util.Set;
import org.apache.cloudstack.storage.to.SnapshotObjectTO;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@ -47,19 +48,15 @@ import org.libvirt.Connect;
import org.libvirt.Domain;
import org.libvirt.LibvirtException;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.junit.MockitoJUnitRunner;
@PrepareForTest({ Script.class })
@PowerMockIgnore({"javax.xml.*", "org.xml.*", "org.w3c.dom.*"})
@RunWith(PowerMockRunner.class)
@RunWith(MockitoJUnitRunner.class)
public class KVMStorageProcessorTest {
@Mock
@ -91,8 +88,6 @@ public class KVMStorageProcessorTest {
@Mock
Connect connectMock;
@Mock
LibvirtDomainXMLParser libvirtDomainXMLParserMock;
@Mock
LibvirtVMDef.DiskDef diskDefMock;
@ -100,48 +95,56 @@ public class KVMStorageProcessorTest {
private static final String directDownloadTemporaryPath = "/var/lib/libvirt/images/dd";
private static final long templateSize = 80000L;
private AutoCloseable closeable;
@Before
public void setUp() throws ConfigurationException {
MockitoAnnotations.initMocks(this);
closeable = MockitoAnnotations.openMocks(this);
storageProcessor = new KVMStorageProcessor(storagePoolManager, resource);
}
@After
public void tearDown() throws Exception {
closeable.close();
}
@Test
public void testIsEnoughSpaceForDownloadTemplateOnTemporaryLocationAssumeEnoughSpaceWhenNotProvided() {
PowerMockito.mockStatic(Script.class);
Mockito.when(resource.getDirectDownloadTemporaryDownloadPath()).thenReturn(directDownloadTemporaryPath);
boolean result = storageProcessor.isEnoughSpaceForDownloadTemplateOnTemporaryLocation(null);
Assert.assertTrue(result);
}
@Test
public void testIsEnoughSpaceForDownloadTemplateOnTemporaryLocationNotEnoughSpace() {
PowerMockito.mockStatic(Script.class);
Mockito.when(resource.getDirectDownloadTemporaryDownloadPath()).thenReturn(directDownloadTemporaryPath);
String output = String.valueOf(templateSize - 30000L);
Mockito.when(Script.runSimpleBashScript(Matchers.anyString())).thenReturn(output);
boolean result = storageProcessor.isEnoughSpaceForDownloadTemplateOnTemporaryLocation(templateSize);
Assert.assertFalse(result);
try (MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
Mockito.when(resource.getDirectDownloadTemporaryDownloadPath()).thenReturn(directDownloadTemporaryPath);
String output = String.valueOf(templateSize - 30000L);
Mockito.when(Script.runSimpleBashScript(Mockito.anyString())).thenReturn(output);
boolean result = storageProcessor.isEnoughSpaceForDownloadTemplateOnTemporaryLocation(templateSize);
Assert.assertFalse(result);
}
}
@Test
public void testIsEnoughSpaceForDownloadTemplateOnTemporaryLocationEnoughSpace() {
PowerMockito.mockStatic(Script.class);
Mockito.when(resource.getDirectDownloadTemporaryDownloadPath()).thenReturn(directDownloadTemporaryPath);
String output = String.valueOf(templateSize + 30000L);
Mockito.when(Script.runSimpleBashScript(Matchers.anyString())).thenReturn(output);
boolean result = storageProcessor.isEnoughSpaceForDownloadTemplateOnTemporaryLocation(templateSize);
Assert.assertTrue(result);
try (MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
Mockito.when(resource.getDirectDownloadTemporaryDownloadPath()).thenReturn(directDownloadTemporaryPath);
String output = String.valueOf(templateSize + 30000L);
Mockito.when(Script.runSimpleBashScript(Mockito.anyString())).thenReturn(output);
boolean result = storageProcessor.isEnoughSpaceForDownloadTemplateOnTemporaryLocation(templateSize);
Assert.assertTrue(result);
}
}
@Test
public void testIsEnoughSpaceForDownloadTemplateOnTemporaryLocationNotExistingLocation() {
PowerMockito.mockStatic(Script.class);
Mockito.when(resource.getDirectDownloadTemporaryDownloadPath()).thenReturn(directDownloadTemporaryPath);
String output = String.format("df: %s: No such file or directory", directDownloadTemporaryPath);
Mockito.when(Script.runSimpleBashScript(Matchers.anyString())).thenReturn(output);
boolean result = storageProcessor.isEnoughSpaceForDownloadTemplateOnTemporaryLocation(templateSize);
Assert.assertFalse(result);
try (MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
Mockito.when(resource.getDirectDownloadTemporaryDownloadPath()).thenReturn(directDownloadTemporaryPath);
String output = String.format("df: %s: No such file or directory", directDownloadTemporaryPath);
Mockito.when(Script.runSimpleBashScript(Mockito.anyString())).thenReturn(output);
boolean result = storageProcessor.isEnoughSpaceForDownloadTemplateOnTemporaryLocation(templateSize);
Assert.assertFalse(result);
}
}
@Test
@ -250,7 +253,6 @@ public class KVMStorageProcessorTest {
}
@Test
@PrepareForTest(KVMStorageProcessor.class)
public void validateCopySnapshotToPrimaryStorageDirFailToCopyReturnErrorMessage() throws Exception {
String baseFile = "baseFile";
String snapshotPath = "snapshotPath";
@ -258,58 +260,71 @@ public class KVMStorageProcessorTest {
String expectedResult = String.format("Unable to copy %s snapshot [%s] to [%s] due to [%s].", volumeObjectToMock, baseFile, snapshotPath, errorMessage);
Mockito.doReturn(true).when(kvmStoragePoolMock).createFolder(Mockito.anyString());
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.copy(Mockito.any(Path.class), Mockito.any(Path.class), Mockito.any())).thenThrow(new IOException(errorMessage));
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class)) {
Mockito.when(Files.copy(Mockito.any(Path.class), Mockito.any(Path.class), Mockito.any())).thenThrow(
new IOException(errorMessage));
String result = storageProcessorSpy.copySnapshotToPrimaryStorageDir(kvmStoragePoolMock, baseFile, snapshotPath, volumeObjectToMock);
String result = storageProcessorSpy.copySnapshotToPrimaryStorageDir(kvmStoragePoolMock, baseFile,
snapshotPath, volumeObjectToMock);
Assert.assertEquals(expectedResult, result);
Assert.assertEquals(expectedResult, result);
}
}
@Test
@PrepareForTest(KVMStorageProcessor.class)
public void validateCopySnapshotToPrimaryStorageDirCopySuccessReturnNull() throws Exception {
String baseFile = "baseFile";
String snapshotPath = "snapshotPath";
Mockito.doReturn(true).when(kvmStoragePoolMock).createFolder(Mockito.anyString());
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.copy(Mockito.any(Path.class), Mockito.any(Path.class), Mockito.any())).thenReturn(null);
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class)) {
Mockito.when(Files.copy(Mockito.any(Path.class), Mockito.any(Path.class), Mockito.any())).thenReturn(null);
String result = storageProcessorSpy.copySnapshotToPrimaryStorageDir(kvmStoragePoolMock, baseFile, snapshotPath, volumeObjectToMock);
String result = storageProcessorSpy.copySnapshotToPrimaryStorageDir(kvmStoragePoolMock, baseFile,
snapshotPath, volumeObjectToMock);
Assert.assertNull(result);
Assert.assertNull(result);
}
}
@Test (expected = CloudRuntimeException.class)
@PrepareForTest({Script.class, LibvirtUtilitiesHelper.class})
public void validateMergeSnapshotIntoBaseFileErrorOnMergeThrowCloudRuntimeException() throws Exception {
PowerMockito.mockStatic(Script.class, LibvirtUtilitiesHelper.class);
PowerMockito.when(Script.runSimpleBashScript(Mockito.anyString())).thenReturn("");
PowerMockito.when(LibvirtUtilitiesHelper.isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit(Mockito.any())).thenReturn(true);
try (MockedStatic<Script> ignored = Mockito.mockStatic(
Script.class); MockedStatic<LibvirtUtilitiesHelper> ignored2 = Mockito.mockStatic(
LibvirtUtilitiesHelper.class)) {
Mockito.when(Script.runSimpleBashScript(Mockito.anyString())).thenReturn("");
Mockito.when(LibvirtUtilitiesHelper.isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit(Mockito.any()))
.thenReturn(true);
storageProcessorSpy.mergeSnapshotIntoBaseFile(domainMock, "", "", "", volumeObjectToMock, connectMock);
storageProcessorSpy.mergeSnapshotIntoBaseFile(domainMock, "", "", "", volumeObjectToMock, connectMock);
}
}
@Test
@PrepareForTest({Script.class, LibvirtUtilitiesHelper.class})
public void validateMergeSnapshotIntoBaseFileMergeSuccessDoNothing() throws Exception {
PowerMockito.mockStatic(Script.class, LibvirtUtilitiesHelper.class);
PowerMockito.when(Script.runSimpleBashScript(Mockito.anyString())).thenReturn(null);
PowerMockito.when(LibvirtUtilitiesHelper.isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit(Mockito.any())).thenReturn(true);
Mockito.doNothing().when(storageProcessorSpy).manuallyDeleteUnusedSnapshotFile(Mockito.anyBoolean(), Mockito.any());
try (MockedStatic<Script> scriptMockedStatic = Mockito.mockStatic(
Script.class); MockedStatic<LibvirtUtilitiesHelper> libvirtUtilitiesHelperMockedStatic = Mockito.mockStatic(
LibvirtUtilitiesHelper.class)) {
Mockito.when(Script.runSimpleBashScript(Mockito.anyString())).thenReturn(null);
Mockito.when(LibvirtUtilitiesHelper.isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit(Mockito.any()))
.thenReturn(true);
Mockito.doNothing().when(storageProcessorSpy).manuallyDeleteUnusedSnapshotFile(Mockito.anyBoolean(),
Mockito.any());
storageProcessorSpy.mergeSnapshotIntoBaseFile(domainMock, "", "", "", volumeObjectToMock, connectMock);
storageProcessorSpy.mergeSnapshotIntoBaseFile(domainMock, "", "", "", volumeObjectToMock, connectMock);
libvirtUtilitiesHelperMockedStatic.verify(() -> LibvirtUtilitiesHelper.isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit(Mockito.any()), Mockito.times(1));
scriptMockedStatic.verify(() -> Script.runSimpleBashScript(Mockito.anyString()), Mockito.times(1));
}
}
@Test (expected = CloudRuntimeException.class)
@PrepareForTest(KVMStorageProcessor.class)
public void validateManuallyDeleteUnusedSnapshotFileLibvirtDoesNotSupportsFlagDeleteExceptionOnFileDeletionThrowsException() throws IOException {
Mockito.doReturn("").when(snapshotObjectToMock).getPath();
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.deleteIfExists(Mockito.any(Path.class))).thenThrow(IOException.class);
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class)) {
Mockito.when(Files.deleteIfExists(Mockito.any(Path.class))).thenThrow(IOException.class);
storageProcessorSpy.manuallyDeleteUnusedSnapshotFile(false, "");
storageProcessorSpy.manuallyDeleteUnusedSnapshotFile(false, "");
}
}
@Test
@ -326,77 +341,84 @@ public class KVMStorageProcessorTest {
@Test (expected = IOException.class)
public void validateValidateCopyResultFailToDeleteThrowIOException() throws CloudRuntimeException, IOException{
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.deleteIfExists(Mockito.any())).thenThrow(new IOException(""));
storageProcessorSpy.validateCopyResult("", "");
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class)) {
Mockito.when(Files.deleteIfExists(Mockito.any())).thenThrow(new IOException(""));
storageProcessorSpy.validateCopyResult("", "");
}
}
@Test (expected = CloudRuntimeException.class)
@PrepareForTest(KVMStorageProcessor.class)
public void validateValidateCopyResulResultNotNullThrowCloudRuntimeException() throws CloudRuntimeException, IOException{
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.deleteIfExists(Mockito.any())).thenReturn(true);
storageProcessorSpy.validateCopyResult("", "");
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class)) {
Mockito.when(Files.deleteIfExists(Mockito.any())).thenReturn(true);
storageProcessorSpy.validateCopyResult("", "");
}
}
@Test (expected = CloudRuntimeException.class)
@PrepareForTest(KVMStorageProcessor.class)
public void validateDeleteSnapshotFileErrorOnDeleteThrowsCloudRuntimeException() throws Exception {
Mockito.doReturn("").when(snapshotObjectToMock).getPath();
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.deleteIfExists(Mockito.any(Path.class))).thenThrow(IOException.class);
try (MockedStatic<Files> ignored = Mockito.mockStatic(Files.class)) {
Mockito.when(Files.deleteIfExists(Mockito.any(Path.class))).thenThrow(IOException.class);
storageProcessorSpy.deleteSnapshotFile(snapshotObjectToMock);
storageProcessorSpy.deleteSnapshotFile(snapshotObjectToMock);
}
}
@Test
@PrepareForTest(KVMStorageProcessor.class)
public void validateDeleteSnapshotFileSuccess () throws IOException {
Mockito.doReturn("").when(snapshotObjectToMock).getPath();
PowerMockito.mockStatic(Files.class);
PowerMockito.when(Files.deleteIfExists(Mockito.any(Path.class))).thenReturn(true);
try (MockedStatic<Files> filesMockedStatic = Mockito.mockStatic(Files.class)) {
Mockito.when(Files.deleteIfExists(Mockito.any(Path.class))).thenReturn(true);
storageProcessorSpy.deleteSnapshotFile(snapshotObjectToMock);
}
storageProcessorSpy.deleteSnapshotFile(snapshotObjectToMock);
private void checkDetachSucessTest(boolean duplicate) throws Exception {
List<LibvirtVMDef.DiskDef> disks = createDiskDefs(2, duplicate);
PowerMockito.when(domainMock.getXMLDesc(Mockito.anyInt())).thenReturn("test");
PowerMockito.whenNew(LibvirtDomainXMLParser.class).withAnyArguments().thenReturn(libvirtDomainXMLParserMock);
PowerMockito.when(libvirtDomainXMLParserMock.parseDomainXML(Mockito.anyString())).thenReturn(true);
PowerMockito.when(libvirtDomainXMLParserMock.getDisks()).thenReturn(disks);
filesMockedStatic.verify(() -> Files.deleteIfExists(Mockito.any(Path.class)), Mockito.times(1));
}
}
@Test
@PrepareForTest(KVMStorageProcessor.class)
public void checkDetachSucessTestDetachReturnTrue() throws Exception {
checkDetachSucessTest(false);
Assert.assertTrue(storageProcessorSpy.checkDetachSuccess("path", domainMock));
List<LibvirtVMDef.DiskDef> disks = createDiskDefs(2, false);
Mockito.when(domainMock.getXMLDesc(Mockito.anyInt())).thenReturn("test");
try (MockedConstruction<LibvirtDomainXMLParser> ignored = Mockito.mockConstruction(
LibvirtDomainXMLParser.class, (mock, context) -> {
Mockito.when(mock.parseDomainXML(Mockito.anyString())).thenReturn(true);
Mockito.when(mock.getDisks()).thenReturn(disks);
})) {
Assert.assertTrue(storageProcessorSpy.checkDetachSuccess("path", domainMock));
}
}
@Test
@PrepareForTest(KVMStorageProcessor.class)
public void checkDetachSucessTestDetachReturnFalse() throws Exception {
checkDetachSucessTest(true);
Assert.assertFalse(storageProcessorSpy.checkDetachSuccess("path", domainMock));
List<LibvirtVMDef.DiskDef> disks = createDiskDefs(2, true);
Mockito.when(domainMock.getXMLDesc(Mockito.anyInt())).thenReturn("test");
try (MockedConstruction<LibvirtDomainXMLParser> ignored = Mockito.mockConstruction(
LibvirtDomainXMLParser.class, (mock, context) -> {
Mockito.when(mock.parseDomainXML(Mockito.anyString())).thenReturn(true);
Mockito.when(mock.getDisks()).thenReturn(disks);
})) {
Assert.assertFalse(storageProcessorSpy.checkDetachSuccess("path", domainMock));
}
}
private void attachOrDetachDeviceTest (boolean attach, String vmName, LibvirtVMDef.DiskDef xml) throws LibvirtException, InternalErrorException {
storageProcessorSpy.attachOrDetachDevice(connectMock, attach, vmName, xml);
}
@PrepareForTest(KVMStorageProcessor.class)
private void attachOrDetachDeviceTest (boolean attach, String vmName, LibvirtVMDef.DiskDef xml, long waitDetachDevice) throws LibvirtException, InternalErrorException {
storageProcessorSpy.attachOrDetachDevice(connectMock, attach, vmName, xml, waitDetachDevice);
}
@Test (expected = LibvirtException.class)
@PrepareForTest(KVMStorageProcessor.class)
public void attachOrDetachDeviceTestThrowLibvirtException() throws LibvirtException, InternalErrorException {
Mockito.when(connectMock.domainLookupByName(Mockito.anyString())).thenThrow(LibvirtException.class);
attachOrDetachDeviceTest(true, "vmName", diskDefMock);
}
@PrepareForTest(KVMStorageProcessor.class)
@Test
public void attachOrDetachDeviceTestAttachSuccess() throws LibvirtException, InternalErrorException {
Mockito.when(connectMock.domainLookupByName("vmName")).thenReturn(domainMock);
attachOrDetachDeviceTest(true, "vmName", diskDefMock);
@ -404,7 +426,6 @@ public class KVMStorageProcessorTest {
}
@Test (expected = LibvirtException.class)
@PrepareForTest(KVMStorageProcessor.class)
public void attachOrDetachDeviceTestAttachThrowLibvirtException() throws LibvirtException, InternalErrorException {
Mockito.when(connectMock.domainLookupByName("vmName")).thenReturn(domainMock);
Mockito.when(diskDefMock.toString()).thenReturn("diskDef");
@ -414,7 +435,6 @@ public class KVMStorageProcessorTest {
}
@Test (expected = LibvirtException.class)
@PrepareForTest(KVMStorageProcessor.class)
public void attachOrDetachDeviceTestDetachThrowLibvirtException() throws LibvirtException, InternalErrorException {
Mockito.when(connectMock.domainLookupByName("vmName")).thenReturn(domainMock);
Mockito.doThrow(LibvirtException.class).when(domainMock).detachDevice(Mockito.anyString());
@ -422,10 +442,9 @@ public class KVMStorageProcessorTest {
}
@Test
@PrepareForTest(KVMStorageProcessor.class)
public void attachOrDetachDeviceTestDetachSuccess() throws LibvirtException, InternalErrorException {
Mockito.when(connectMock.domainLookupByName("vmName")).thenReturn(domainMock);
PowerMockito.doReturn(true).when(storageProcessorSpy).checkDetachSuccess(Mockito.anyString(), Mockito.any(Domain.class));
Mockito.doReturn(true).when(storageProcessorSpy).checkDetachSuccess(Mockito.anyString(), Mockito.any(Domain.class));
Mockito.when(diskDefMock.toString()).thenReturn("diskDef");
Mockito.when(diskDefMock.getDiskPath()).thenReturn("diskDef");
attachOrDetachDeviceTest( false, "vmName", diskDefMock, 10000);
@ -433,10 +452,9 @@ public class KVMStorageProcessorTest {
}
@Test (expected = InternalErrorException.class)
@PrepareForTest(KVMStorageProcessor.class)
public void attachOrDetachDeviceTestDetachThrowInternalErrorException() throws LibvirtException, InternalErrorException {
Mockito.when(connectMock.domainLookupByName("vmName")).thenReturn(domainMock);
PowerMockito.doReturn(false).when(storageProcessorSpy).checkDetachSuccess(Mockito.anyString(), Mockito.any(Domain.class));
Mockito.doReturn(false).when(storageProcessorSpy).checkDetachSuccess(Mockito.anyString(), Mockito.any(Domain.class));
Mockito.when(diskDefMock.toString()).thenReturn("diskDef");
Mockito.when(diskDefMock.getDiskPath()).thenReturn("diskDef");
attachOrDetachDeviceTest( false, "vmName", diskDefMock);

View File

@ -17,15 +17,20 @@
package com.cloud.hypervisor.kvm.storage;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.libvirt.StoragePool;
import org.mockito.Mockito;
import com.cloud.storage.Storage.StoragePoolType;
import junit.framework.TestCase;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class LibvirtStoragePoolTest extends TestCase {
@Test
public void testAttributes() {
String uuid = "4c4fb08b-373e-4f30-a120-3aa3a43f31da";
String name = "myfirstpool";
@ -52,6 +57,7 @@ public class LibvirtStoragePoolTest extends TestCase {
assertEquals(pool.getAvailable(), 1023);
}
@Test
public void testDefaultFormats() {
String uuid = "f40cbf53-1f37-4c62-8912-801edf398f47";
String name = "myfirstpool";
@ -72,6 +78,7 @@ public class LibvirtStoragePoolTest extends TestCase {
assertEquals(clvmPool.getStoragePoolType(), StoragePoolType.CLVM);
}
@Test
public void testExternalSnapshot() {
String uuid = "60b46738-c5d0-40a9-a79e-9a4fe6295db7";
String name = "myfirstpool";

View File

@ -19,7 +19,10 @@ package com.cloud.hypervisor.kvm.storage;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ScaleIOStorageAdaptorTest {
@Test
public void getUsableBytesFromRawBytesTest() {

View File

@ -33,22 +33,21 @@ import org.apache.cloudstack.storage.datastore.client.ScaleIOGatewayClient;
import org.apache.cloudstack.storage.datastore.util.ScaleIOUtil;
import org.apache.cloudstack.utils.qemu.QemuImg;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.StorageLayer;
import com.cloud.utils.script.Script;
@PrepareForTest({ScaleIOUtil.class, Script.class})
@RunWith(PowerMockRunner.class)
@RunWith(MockitoJUnitRunner.class)
public class ScaleIOStoragePoolTest {
ScaleIOStoragePool pool;
@ -70,10 +69,6 @@ public class ScaleIOStoragePoolTest {
pool = new ScaleIOStoragePool(uuid, "192.168.1.19", 443, "a519be2f00000000", type, details, adapter);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testAttributes() {
assertEquals(0, pool.getCapacity());
@ -104,12 +99,16 @@ public class ScaleIOStoragePoolTest {
Map<String,String> details = new HashMap<String, String>();
details.put(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID, systemId);
PowerMockito.mockStatic(Script.class);
when(Script.runSimpleBashScript("/opt/emc/scaleio/sdc/bin/drv_cfg --query_mdms|grep 218ce1797566a00f|awk '{print $5}'")).thenReturn(sdcId);
try (MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
when(Script.runSimpleBashScript(
"/opt/emc/scaleio/sdc/bin/drv_cfg --query_mdms|grep 218ce1797566a00f|awk '{print $5}'")).thenReturn(
sdcId);
ScaleIOStoragePool pool1 = new ScaleIOStoragePool(uuid, "192.168.1.19", 443, "a519be2f00000000", type, details, adapter);
assertEquals(systemId, pool1.getDetails().get(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID));
assertEquals(sdcId, pool1.getDetails().get(ScaleIOGatewayClient.SDC_ID));
ScaleIOStoragePool pool1 = new ScaleIOStoragePool(uuid, "192.168.1.19", 443, "a519be2f00000000", type,
details, adapter);
assertEquals(systemId, pool1.getDetails().get(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID));
assertEquals(sdcId, pool1.getDetails().get(ScaleIOGatewayClient.SDC_ID));
}
}
@Test
@ -121,13 +120,17 @@ public class ScaleIOStoragePoolTest {
Map<String,String> details = new HashMap<String, String>();
details.put(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID, systemId);
PowerMockito.mockStatic(Script.class);
when(Script.runSimpleBashScript("/opt/emc/scaleio/sdc/bin/drv_cfg --query_mdms|grep 218ce1797566a00f|awk '{print $5}'")).thenReturn(null);
when(Script.runSimpleBashScript("/opt/emc/scaleio/sdc/bin/drv_cfg --query_guid")).thenReturn(sdcGuid);
try (MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
when(Script.runSimpleBashScript(
"/opt/emc/scaleio/sdc/bin/drv_cfg --query_mdms|grep 218ce1797566a00f|awk '{print $5}'")).thenReturn(
null);
when(Script.runSimpleBashScript("/opt/emc/scaleio/sdc/bin/drv_cfg --query_guid")).thenReturn(sdcGuid);
ScaleIOStoragePool pool1 = new ScaleIOStoragePool(uuid, "192.168.1.19", 443, "a519be2f00000000", type, details, adapter);
assertEquals(systemId, pool1.getDetails().get(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID));
assertEquals(sdcGuid, pool1.getDetails().get(ScaleIOGatewayClient.SDC_GUID));
ScaleIOStoragePool pool1 = new ScaleIOStoragePool(uuid, "192.168.1.19", 443, "a519be2f00000000", type,
details, adapter);
assertEquals(systemId, pool1.getDetails().get(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID));
assertEquals(sdcGuid, pool1.getDetails().get(ScaleIOGatewayClient.SDC_GUID));
}
}
@Test
@ -146,35 +149,35 @@ public class ScaleIOStoragePoolTest {
final String volumePath = "6c3362b500000001:vol-139-3d2c-12f0";
final String systemId = "218ce1797566a00f";
File dir = PowerMockito.mock(File.class);
PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(dir);
// TODO: Mock file in dir
File[] files = new File[1];
String volumeId = ScaleIOUtil.getVolumePath(volumePath);
String diskFilePath = ScaleIOUtil.DISK_PATH + File.separator + ScaleIOUtil.DISK_NAME_PREFIX + systemId + "-" + volumeId;
files[0] = new File(diskFilePath);
PowerMockito.when(dir.listFiles(any(FileFilter.class))).thenReturn(files);
KVMPhysicalDisk disk = adapter.getPhysicalDisk(volumePath, pool);
assertNull(disk);
try (MockedConstruction<File> ignored = Mockito.mockConstruction(File.class, (mock, context) -> {
File[] files = new File[1];
String volumeId = ScaleIOUtil.getVolumePath(volumePath);
String diskFilePath =
ScaleIOUtil.DISK_PATH + File.separator + ScaleIOUtil.DISK_NAME_PREFIX + systemId + "-" + volumeId;
files[0] = new File(diskFilePath);
Mockito.when(mock.listFiles(any(FileFilter.class))).thenReturn(files);
})) {
KVMPhysicalDisk disk = adapter.getPhysicalDisk(volumePath, pool);
assertNull(disk);
}
}
@Test
public void testGetPhysicalDiskWithSystemId() throws Exception {
final String volumePath = "6c3362b500000001:vol-139-3d2c-12f0";
final String volumeId = ScaleIOUtil.getVolumePath(volumePath);
final String systemId = "218ce1797566a00f";
PowerMockito.mockStatic(ScaleIOUtil.class);
when(ScaleIOUtil.getSystemIdForVolume(volumeId)).thenReturn(systemId);
try (MockedStatic<ScaleIOUtil> ignored = Mockito.mockStatic(ScaleIOUtil.class, Mockito.CALLS_REAL_METHODS)) {
when(ScaleIOUtil.getSystemIdForVolume(volumeId)).thenReturn(systemId);
// TODO: Mock file exists
File file = PowerMockito.mock(File.class);
PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(file);
PowerMockito.when(file.exists()).thenReturn(true);
// TODO: Mock file exists
KVMPhysicalDisk disk = adapter.getPhysicalDisk(volumePath, pool);
assertNull(disk);
KVMPhysicalDisk disk = adapter.getPhysicalDisk(volumePath, pool);
assertNull(disk);
}
}
@Test

View File

@ -0,0 +1,202 @@
// 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 com.cloud.hypervisor.kvm.storage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileFilter;
import java.util.HashMap;
import java.util.Map;
import org.apache.cloudstack.storage.datastore.client.ScaleIOGatewayClient;
import org.apache.cloudstack.storage.datastore.util.ScaleIOUtil;
import org.apache.cloudstack.utils.qemu.QemuImg;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.StorageLayer;
import com.cloud.utils.script.Script;
@RunWith(MockitoJUnitRunner.class)
public class ScaleIOStoragePoolTest {
ScaleIOStoragePool pool;
StorageAdaptor adapter;
@Mock
StorageLayer storageLayer;
@Before
public void setUp() throws Exception {
final String uuid = "345fc603-2d7e-47d2-b719-a0110b3732e6";
final String systemId = "218ce1797566a00f";
final StoragePoolType type = StoragePoolType.PowerFlex;
Map<String,String> details = new HashMap<String, String>();
details.put(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID, systemId);
adapter = spy(new ScaleIOStorageAdaptor(storageLayer));
pool = new ScaleIOStoragePool(uuid, "192.168.1.19", 443, "a519be2f00000000", type, details, adapter);
}
@Test
public void testAttributes() {
assertEquals(0, pool.getCapacity());
assertEquals(0, pool.getUsed());
assertEquals(0, pool.getAvailable());
assertEquals("345fc603-2d7e-47d2-b719-a0110b3732e6", pool.getUuid());
assertEquals("192.168.1.19", pool.getSourceHost());
assertEquals(443, pool.getSourcePort());
assertEquals("a519be2f00000000", pool.getSourceDir());
assertEquals(StoragePoolType.PowerFlex, pool.getType());
assertEquals("218ce1797566a00f", pool.getDetails().get(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID));
pool.setCapacity(131072);
pool.setUsed(24576);
pool.setAvailable(106496);
assertEquals(131072, pool.getCapacity());
assertEquals(24576, pool.getUsed());
assertEquals(106496, pool.getAvailable());
}
@Test
public void testSdcIdAttribute() {
final String uuid = "345fc603-2d7e-47d2-b719-a0110b3732e6";
final String systemId = "218ce1797566a00f";
final String sdcId = "301b852c00000003";
final StoragePoolType type = StoragePoolType.PowerFlex;
Map<String,String> details = new HashMap<String, String>();
details.put(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID, systemId);
try(MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
when(Script.runSimpleBashScript(
"/opt/emc/scaleio/sdc/bin/drv_cfg --query_mdms|grep 218ce1797566a00f|awk '{print $5}'")).thenReturn(
sdcId);
ScaleIOStoragePool pool1 = new ScaleIOStoragePool(uuid, "192.168.1.19", 443, "a519be2f00000000", type,
details, adapter);
assertEquals(systemId, pool1.getDetails().get(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID));
assertEquals(sdcId, pool1.getDetails().get(ScaleIOGatewayClient.SDC_ID));
}
}
@Test
public void testSdcGuidAttribute() {
final String uuid = "345fc603-2d7e-47d2-b719-a0110b3732e6";
final String systemId = "218ce1797566a00f";
final String sdcGuid = "B0E3BFB8-C20B-43BF-93C8-13339E85AA50";
final StoragePoolType type = StoragePoolType.PowerFlex;
Map<String,String> details = new HashMap<String, String>();
details.put(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID, systemId);
try(MockedStatic<Script> ignored = Mockito.mockStatic(Script.class)) {
when(Script.runSimpleBashScript(
"/opt/emc/scaleio/sdc/bin/drv_cfg --query_mdms|grep 218ce1797566a00f|awk '{print $5}'")).thenReturn(
null);
when(Script.runSimpleBashScript("/opt/emc/scaleio/sdc/bin/drv_cfg --query_guid")).thenReturn(sdcGuid);
ScaleIOStoragePool pool1 = new ScaleIOStoragePool(uuid, "192.168.1.19", 443, "a519be2f00000000", type,
details, adapter);
assertEquals(systemId, pool1.getDetails().get(ScaleIOGatewayClient.STORAGE_POOL_SYSTEM_ID));
assertEquals(sdcGuid, pool1.getDetails().get(ScaleIOGatewayClient.SDC_GUID));
}
}
@Test
public void testDefaults() {
assertEquals(PhysicalDiskFormat.RAW, pool.getDefaultFormat());
assertEquals(StoragePoolType.PowerFlex, pool.getType());
assertNull(pool.getAuthUserName());
assertNull(pool.getAuthSecret());
Assert.assertFalse(pool.supportsConfigDriveIso());
assertTrue(pool.isExternalSnapshot());
}
public void testGetPhysicalDiskWithWildcardFileFilter() throws Exception {
final String volumePath = "6c3362b500000001:vol-139-3d2c-12f0";
final String systemId = "218ce1797566a00f";
// TODO: Mock file in dir
try(MockedConstruction<File> ignored = Mockito.mockConstruction(File.class, (mock, context) -> {
File[] files = new File[1];
String volumeId = ScaleIOUtil.getVolumePath(volumePath);
String diskFilePath =
ScaleIOUtil.DISK_PATH + File.separator + ScaleIOUtil.DISK_NAME_PREFIX + systemId + "-" + volumeId;
files[0] = new File(diskFilePath);
Mockito.when(mock.listFiles(any(FileFilter.class))).thenReturn(files);
})) {
KVMPhysicalDisk disk = adapter.getPhysicalDisk(volumePath, pool);
assertNull(disk);
}
}
@Test
public void testGetPhysicalDiskWithSystemId() throws Exception {
final String volumePath = "6c3362b500000001:vol-139-3d2c-12f0";
final String volumeId = ScaleIOUtil.getVolumePath(volumePath);
final String systemId = "218ce1797566a00f";
try (MockedConstruction<File> ignored = Mockito.mockConstruction(File.class, (mock, context) -> {
Mockito.when(mock.exists()).thenReturn(true);
}); MockedStatic<ScaleIOUtil> scaleIOUtilMockedStatic = Mockito.mockStatic(ScaleIOUtil.class)) {
scaleIOUtilMockedStatic.when(() -> ScaleIOUtil.getSystemIdForVolume(volumeId)).thenReturn(systemId);
KVMPhysicalDisk disk = adapter.getPhysicalDisk(volumePath, pool);
assertNull(disk);
}
}
@Test
public void testConnectPhysicalDisk() {
final String volumePath = "6c3362b500000001:vol-139-3d2c-12f0";
final String volumeId = ScaleIOUtil.getVolumePath(volumePath);
final String systemId = "218ce1797566a00f";
final String diskFilePath = ScaleIOUtil.DISK_PATH + File.separator + ScaleIOUtil.DISK_NAME_PREFIX + systemId + "-" + volumeId;
KVMPhysicalDisk disk = new KVMPhysicalDisk(diskFilePath, volumePath, pool);
disk.setFormat(QemuImg.PhysicalDiskFormat.RAW);
disk.setSize(8192);
disk.setVirtualSize(8192);
assertEquals("/dev/disk/by-id/emc-vol-218ce1797566a00f-6c3362b500000001", disk.getPath());
when(adapter.getPhysicalDisk(volumeId, pool)).thenReturn(disk);
final boolean result = adapter.connectPhysicalDisk(volumePath, pool, null);
assertTrue(result);
}
}

View File

@ -29,7 +29,6 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import com.cloud.exception.StorageUnavailableException;
@ -47,7 +46,6 @@ public class KVMHostHATest {
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
kvmHAProvider = new KVMHAProvider();
kvmHAProvider.hostActivityChecker = kvmHostActivityChecker;
}

View File

@ -23,6 +23,8 @@ import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.IOException;
import java.io.RandomAccessFile;
@ -32,6 +34,8 @@ import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
@RunWith(MockitoJUnitRunner.class)
public class CryptSetupTest {
CryptSetup cryptSetup = new CryptSetup();

View File

@ -20,11 +20,14 @@ package org.apache.cloudstack.utils.cryptsetup;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@RunWith(MockitoJUnitRunner.class)
public class KeyFileTest {
@Test

View File

@ -17,24 +17,19 @@
package org.apache.cloudstack.utils.linux;
import org.apache.commons.lang.SystemUtils;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.libvirt.Connect;
import org.libvirt.NodeInfo;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.hypervisor.kvm.resource.LibvirtConnection;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {LibvirtConnection.class})
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*", "org.xml.*"})
@RunWith(MockitoJUnitRunner.class)
public class KVMHostInfoTest {
@Test
public void getCpuSpeed() {
@ -44,7 +39,7 @@ public class KVMHostInfoTest {
Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
NodeInfo nodeInfo = Mockito.mock(NodeInfo.class);
nodeInfo.mhz = 1000;
Assert.assertThat(KVMHostInfo.getCpuSpeed(null, nodeInfo), Matchers.greaterThan(0l));
Assert.assertTrue(KVMHostInfo.getCpuSpeed(null, nodeInfo) > 0L);
}
@Test
@ -57,7 +52,7 @@ public class KVMHostInfoTest {
" <vendor>AMD</vendor>\n" +
" <counter name='tsc' frequency='2350000000' scaling='no'/>\n" +
" </cpu>\n" +
"</host>\n";;
"</host>\n";
Assert.assertEquals(2350L, KVMHostInfo.getCpuSpeedFromHostCapabilities(capabilities));
}
@ -66,19 +61,20 @@ public class KVMHostInfoTest {
if (!System.getProperty("os.name").equals("Linux")) {
return;
}
PowerMockito.mockStatic(LibvirtConnection.class);
Connect conn = Mockito.mock(Connect.class);
NodeInfo nodeInfo = Mockito.mock(NodeInfo.class);
nodeInfo.mhz = 1000;
String capabilitiesXml = "<capabilities></capabilities>";
try (MockedStatic<LibvirtConnection> ignored = Mockito.mockStatic(LibvirtConnection.class)) {
Connect conn = Mockito.mock(Connect.class);
NodeInfo nodeInfo = Mockito.mock(NodeInfo.class);
nodeInfo.mhz = 1000;
String capabilitiesXml = "<capabilities></capabilities>";
PowerMockito.doReturn(conn).when(LibvirtConnection.class, "getConnection");
PowerMockito.when(conn.nodeInfo()).thenReturn(nodeInfo);
PowerMockito.when(conn.getCapabilities()).thenReturn(capabilitiesXml);
PowerMockito.when(conn.close()).thenReturn(0);
int manualSpeed = 500;
Mockito.when(LibvirtConnection.getConnection()).thenReturn(conn);
Mockito.when(conn.nodeInfo()).thenReturn(nodeInfo);
Mockito.when(conn.getCapabilities()).thenReturn(capabilitiesXml);
Mockito.when(conn.close()).thenReturn(0);
int manualSpeed = 500;
KVMHostInfo kvmHostInfo = new KVMHostInfo(10, 10, manualSpeed);
Assert.assertEquals(kvmHostInfo.getCpuSpeed(), manualSpeed);
KVMHostInfo kvmHostInfo = new KVMHostInfo(10, 10, manualSpeed);
Assert.assertEquals(kvmHostInfo.getCpuSpeed(), manualSpeed);
}
}
}

View File

@ -16,18 +16,21 @@
// under the License.
package org.apache.cloudstack.utils.linux;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(MemStat.class)
@RunWith(MockitoJUnitRunner.class)
public class MemStatTest {
final String memInfo = "MemTotal: 5830236 kB\n" +
"MemFree: 156752 kB\n" +
@ -37,10 +40,26 @@ public class MemStatTest {
"Active: 4260808 kB\n" +
"Inactive: 949392 kB\n";
MockedConstruction<Scanner> scanner;
@Before
public void setup() throws Exception {
Scanner scanner = new Scanner(memInfo);
PowerMockito.whenNew(Scanner.class).withAnyArguments().thenReturn(scanner);
scanner = Mockito.mockConstruction(Scanner.class, (mock, context) -> {
String[] memInfoLines = memInfo.split("\\n");
List<Boolean> hasNextReturnList = Arrays.stream(memInfoLines).map(line -> true).collect(
Collectors.toList());
hasNextReturnList.add(false);
Mockito.when(mock.next()).thenReturn(memInfoLines[0], Arrays.copyOfRange(memInfoLines, 1,
memInfoLines.length));
Mockito.when(mock.hasNext()).thenReturn(true,
Arrays.copyOfRange(hasNextReturnList.toArray(new Boolean[0]), 1, hasNextReturnList.size()));
});
}
@After
public void tearDown() {
scanner.close();
}
@Test

View File

@ -18,12 +18,14 @@ package org.apache.cloudstack.utils.qemu;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@Ignore
@RunWith(MockitoJUnitRunner.class)
public class QemuImgFileTest {
@Test
public void testFileNameAtContructor() {