Skip to content

Commit

Permalink
Refactored unit tests: TestAll is now split into different parts to p…
Browse files Browse the repository at this point in the history
…revent it from getting to large and clumsy
  • Loading branch information
hypfvieh committed Nov 24, 2023
1 parent a2887c7 commit 200ecfb
Show file tree
Hide file tree
Showing 25 changed files with 981 additions and 901 deletions.
Original file line number Diff line number Diff line change
@@ -1,75 +1,60 @@
package org.freedesktop.dbus.test;

import org.freedesktop.dbus.bin.EmbeddedDBusDaemon;
import org.freedesktop.dbus.config.DBusSysProps;
import org.freedesktop.dbus.connections.BusAddress;
import org.freedesktop.dbus.connections.transports.TransportBuilder;
import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder;
import org.freedesktop.dbus.exceptions.DBusException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import org.freedesktop.dbus.exceptions.DBusExecutionException;
import org.freedesktop.dbus.test.helper.SampleClass;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;

/**
* Base test which will start a embedded DBus daemon if no UNIX transport is found.
*
* @author hypfvieh
* @since v4.0.0 - 2021-09-14
* Base test providing server and client connection and some default exports.
*/
public abstract class AbstractDBusBaseTest extends AbstractBaseTest {

//CHECKSTYLE:OFF
protected static EmbeddedDBusDaemon edbus;
//CHECKSTYLE:ON

/**
* Wait 500 ms if the current test uses TCP transport.
*
* @throws InterruptedException on interruption
*/
protected static void waitIfTcp() throws InterruptedException {
if (!TransportBuilder.getRegisteredBusTypes().contains("UNIX")) {
Thread.sleep(500L);
}
public abstract class AbstractDBusBaseTest extends AbstractDBusDaemonBaseTest {
// CHECKSTYLE:OFF
protected DBusConnection serverconn = null;
protected DBusConnection clientconn = null;
protected SampleClass tclass;
// CHECKSTYLE:ON

@BeforeEach
public void setUp() throws DBusException {
serverconn = DBusConnectionBuilder.forSessionBus().withShared(false).withWeakReferences(true).build();
clientconn = DBusConnectionBuilder.forSessionBus().withShared(false).withWeakReferences(true).build();
serverconn.requestBusName(getTestBusName());

tclass = new SampleClass(serverconn);

/** This exports an instance of the test class as the object /Test. */
serverconn.exportObject(getTestObjectPath(), tclass);
serverconn.addFallback(getTestObjectPath() + "FallbackTest", tclass);
}

/**
* Start an embedded Dbus daemon (in background) if the test uses TCP transport.
*
* @throws DBusException if start of daemon failed
* @throws InterruptedException on interruption
*/
@BeforeAll
public static void beforeAll() throws DBusException, InterruptedException {
Logger logger = LoggerFactory.getLogger(AbstractDBusBaseTest.class);
if (!TransportBuilder.getRegisteredBusTypes().contains("UNIX")) {
String busType = TransportBuilder.getRegisteredBusTypes().get(0);
String addr = TransportBuilder.createDynamicSession(busType, true);
BusAddress address = BusAddress.of(addr);

logger.info("Creating {} based DBus daemon on address {}", busType, addr);
edbus = new EmbeddedDBusDaemon(addr);
edbus.startInBackgroundAndWait(MAX_WAIT);
@AfterEach
public void tearDown() throws Exception {
logger.debug("Checking for outstanding errors");
DBusExecutionException dbee = serverconn.getError();
if (null != dbee) {
throw dbee;
}
dbee = clientconn.getError();
if (null != dbee) {
throw dbee;
}

if (address.isBusType("TCP")) {
String addrStr = address.removeParameter("listen").toString();
System.setProperty(DBusSysProps.DBUS_SESSION_BUS_ADDRESS, addrStr);
}
logger.debug("Disconnecting");
/** Disconnect from the bus. */
clientconn.disconnect();
serverconn.releaseBusName(getTestBusName());
serverconn.disconnect();
}

}
protected String getTestObjectPath() {
return "/" + getClass().getSimpleName();
}

/**
* Shutdown embedded Dbus daemon after test (if any).
*
* @throws IOException shutdown failed
*/
@AfterAll
public static void afterAll() throws IOException {
if (edbus != null) {
edbus.close();
}
protected String getTestBusName() {
return getClass().getName();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package org.freedesktop.dbus.test;

import org.freedesktop.dbus.bin.EmbeddedDBusDaemon;
import org.freedesktop.dbus.config.DBusSysProps;
import org.freedesktop.dbus.connections.BusAddress;
import org.freedesktop.dbus.connections.transports.TransportBuilder;
import org.freedesktop.dbus.exceptions.DBusException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
* Base test which will start a embedded DBus daemon if no UNIX transport is found.
*
* @author hypfvieh
* @since v4.0.0 - 2021-09-14
*/
public abstract class AbstractDBusDaemonBaseTest extends AbstractBaseTest {

//CHECKSTYLE:OFF
protected static EmbeddedDBusDaemon edbus;
//CHECKSTYLE:ON

/**
* Wait 500 ms if the current test uses TCP transport.
*
* @throws InterruptedException on interruption
*/
protected static void waitIfTcp() throws InterruptedException {
if (!TransportBuilder.getRegisteredBusTypes().contains("UNIX")) {
Thread.sleep(500L);
}
}

/**
* Start an embedded Dbus daemon (in background) if the test uses TCP transport.
*
* @throws DBusException if start of daemon failed
* @throws InterruptedException on interruption
*/
@BeforeAll
public static void beforeAll() throws DBusException, InterruptedException {
Logger logger = LoggerFactory.getLogger(AbstractDBusDaemonBaseTest.class);
if (!TransportBuilder.getRegisteredBusTypes().contains("UNIX")) {
String busType = TransportBuilder.getRegisteredBusTypes().get(0);
String addr = TransportBuilder.createDynamicSession(busType, true);
BusAddress address = BusAddress.of(addr);

logger.info("Creating {} based DBus daemon on address {}", busType, addr);
edbus = new EmbeddedDBusDaemon(addr);
edbus.startInBackgroundAndWait(MAX_WAIT);

if (address.isBusType("TCP")) {
String addrStr = address.removeParameter("listen").toString();
System.setProperty(DBusSysProps.DBUS_SESSION_BUS_ADDRESS, addrStr);
}

}
}

/**
* Shutdown embedded Dbus daemon after test (if any).
*
* @throws IOException shutdown failed
*/
@AfterAll
public static void afterAll() throws IOException {
if (edbus != null) {
edbus.close();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package org.freedesktop.dbus.test;

import org.freedesktop.dbus.DBusPath;
import org.freedesktop.dbus.errors.ServiceUnknown;
import org.freedesktop.dbus.errors.UnknownObject;
import org.freedesktop.dbus.exceptions.DBusException;
import org.freedesktop.dbus.interfaces.DBus;
import org.freedesktop.dbus.interfaces.Introspectable;
import org.freedesktop.dbus.interfaces.Peer;
import org.freedesktop.dbus.interfaces.Properties;
import org.freedesktop.dbus.test.helper.SampleException;
import org.freedesktop.dbus.test.helper.SampleSerializable;
import org.freedesktop.dbus.test.helper.interfaces.SampleRemoteInterface;
import org.freedesktop.dbus.test.helper.interfaces.SampleRemoteInterface2;
import org.freedesktop.dbus.utils.TimeMeasure;
import org.junit.jupiter.api.Test;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BaseFunctionsTest extends AbstractDBusBaseTest {

@Test
public void testPing() throws DBusException {
logger.debug("Pinging ourselves");
Peer peer = clientconn.getRemoteObject(getTestBusName(), getTestObjectPath(), Peer.class);

TimeMeasure timeMeasure = new TimeMeasure();
assertDoesNotThrow(() -> {
for (int i = 0; i < 10; i++) {
timeMeasure.reset();
peer.Ping();
logger.debug("Ping returned in " + timeMeasure.getElapsed() + "ms.");
}
});

}

@Test
public void testDbusNames() throws DBusException, InterruptedException {
DBus dbus = clientconn.getRemoteObject("org.freedesktop.DBus", "/org/freedesktop/DBus", DBus.class);

String[] names = dbus.ListNames();
logger.debug("Names on bus: {}", Arrays.toString(names));
assertTrue(Arrays.asList(names).contains(getTestBusName()));
}

@Test
public void testSerialization() throws DBusException {
SampleRemoteInterface2 tri2 = clientconn.getRemoteObject(getTestBusName(), getTestObjectPath(), SampleRemoteInterface2.class);
List<Integer> v = new ArrayList<>();
v.add(1);
v.add(2);
v.add(3);
SampleSerializable<String> s = new SampleSerializable<>(1, "woo", v);
s = tri2.testSerializable((byte) 12, s, 13);
logger.debug("returned: " + s);
if (s.getInt() != 1 || !s.getString().equals("woo") || s.getList().size() != 3 || s.getList().get(0) != 1
|| s.getList().get(1) != 2 || s.getList().get(2) != 3) {
fail("Didn't get back the same TestSerializable");
}
}

@Test
public void testIntrospection() throws DBusException {
logger.debug("Getting our introspection data");
/** This gets a remote object matching our bus name and exported object path. */
Introspectable intro = clientconn.getRemoteObject(getTestBusName(), "/", Introspectable.class);
intro = clientconn.getRemoteObject(getTestBusName(), getTestObjectPath(), Introspectable.class);
/** Get introspection data */
String data = intro.Introspect();
assertNotNull(data);
assertTrue(data.startsWith("<!DOCTYPE"));
}

@Test
public void testExportPath() throws DBusException {
/** This gets a remote object matching our bus name and exported object path. */
SampleRemoteInterface2 tri2 = clientconn.getRemoteObject(getTestBusName(), getTestObjectPath(), SampleRemoteInterface2.class);
logger.debug("Calling the other introspect method: ");
String intro2 = tri2.Introspect();

Collator col = Collator.getInstance();
col.setDecomposition(Collator.FULL_DECOMPOSITION);
col.setStrength(Collator.PRIMARY);

if (0 != col.compare("Not XML", intro2)) {
fail("Introspect return value incorrect");
}

}

@Test
public void testGetProperties() throws DBusException {
Properties prop = clientconn.getRemoteObject(getTestBusName(), getTestObjectPath(), Properties.class);
DBusPath prv = (DBusPath) prop.Get("foo.bar", "foo");
logger.debug("Got path " + prv);

assertEquals("/nonexistant/path", prv.getPath());

}

@Test
public void testException() throws DBusException {
SampleRemoteInterface tri = (SampleRemoteInterface) clientconn.getPeerRemoteObject(getTestBusName(), getTestObjectPath());

/** call something that throws */
try {
logger.debug("Throwing stuff");
tri.throwme();
fail("Method Execution should have failed");
} catch (SampleException _ex) {
logger.debug("Remote Method Failed with: " + _ex.getClass().getName() + " " + _ex.getMessage());
if (!_ex.getMessage().equals("test")) {
fail("Error message was not correct");
}
}

}

@Test
public void testFails() throws DBusException {
SampleRemoteInterface tri = (SampleRemoteInterface) clientconn.getPeerRemoteObject(getTestBusName(), getTestObjectPath());

/** Try and call an invalid remote object */
try {
logger.debug("Calling Method2");
tri = clientconn.getRemoteObject("foo.bar.NotATest", "/Moofle", SampleRemoteInterface.class);
logger.debug("Got Remote Name: " + tri.getName());
fail("Method Execution should have failed");
} catch (ServiceUnknown _ex) {
logger.debug("Remote Method Failed with: " + _ex.getClass().getName() + " " + _ex.getMessage());
}

/** Try and call an invalid remote object */
try {
logger.debug("Calling Method3");
tri = clientconn.getRemoteObject(getTestBusName(), "/Moofle", SampleRemoteInterface.class);
logger.debug("Got Remote Name: " + tri.getName());
fail("Method Execution should have failed");
} catch (UnknownObject _ex) {
logger.debug("Remote Method Failed with: " + _ex.getClass().getName() + " " + _ex.getMessage());
}

/** Try and call an explicitly unexported object */
try {
logger.debug("Calling Method4");
tri = clientconn.getRemoteObject(getTestBusName(), "/BadTest", SampleRemoteInterface.class);
logger.debug("Got Remote Name: " + tri.getName());
fail("Method Execution should have failed");
} catch (UnknownObject _ex) {
logger.debug("Remote Method Failed with: " + _ex.getClass().getName() + " " + _ex.getMessage());
}

}

@Test
public void testOverload() throws DBusException {
logger.debug("testing method overloading...");
SampleRemoteInterface2 tri2 = clientconn.getRemoteObject(getTestBusName(), getTestObjectPath(), SampleRemoteInterface2.class);
SampleRemoteInterface tri = clientconn.getRemoteObject(getTestBusName(), getTestObjectPath(), SampleRemoteInterface.class);

assertEquals(1, tri2.overload("foo"));
assertEquals(2, tri2.overload((byte) 0));
assertEquals(3, tri2.overload());
assertEquals(4, tri.overload());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import java.util.List;
import java.util.Map;

public class BoundPropertiesTest extends AbstractDBusBaseTest {
public class BoundPropertiesTest extends AbstractDBusDaemonBaseTest {

@Test
public void testProperties() throws IOException, DBusException, InterruptedException {
Expand Down

0 comments on commit 200ecfb

Please sign in to comment.