Initial checkin of unified hierarchy of WPILib 2015

This commit is contained in:
Brad Miller
2013-12-15 18:30:16 -05:00
commit 3178911eef
1560 changed files with 410007 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
package edu.wpi.first.wpilibj.networktables2.stream;
import java.io.*;
import java.net.*;
/**
* An object that will provide socket connections when a client connects to the server on the given port (for standard java VM)
*
* @author mwills
*
*/
public class SocketServerStreamProvider implements IOStreamProvider{
private ServerSocket server = null;
public SocketServerStreamProvider(int port) throws IOException{
server = new ServerSocket(port);
}
public IOStream accept() throws IOException {
Socket socket = server.accept();
return new SocketStream(socket);
}
public void close() throws IOException {
if(server!=null)
server.close();
}
}

View File

@@ -0,0 +1,30 @@
package edu.wpi.first.wpilibj.networktables2.stream;
import java.io.*;
import java.net.*;
/**
* A socket connection on a standard Java VM
*
* @author mwills
*
*/
public class SocketStream extends SimpleIOStream{
private final Socket socket;
public SocketStream(String host, int port) throws IOException {
this(new Socket(host, port));
}
public SocketStream(Socket socket) throws IOException {
super(socket.getInputStream(), socket.getOutputStream());
this.socket = socket;
}
public void close() {
super.close();
try{
socket.close();
} catch(IOException e){}
}
}

View File

@@ -0,0 +1,24 @@
package edu.wpi.first.wpilibj.networktables2.stream;
import java.io.*;
/**
*
* @author mwills
*
*/
public class SocketStreamFactory implements IOStreamFactory{
private final String host;
private final int port;
public SocketStreamFactory(String host, int port) throws IOException {
this.host = host;
this.port = port;
}
public IOStream createStream() throws IOException {
return new SocketStream(host, port);
}
}

View File

@@ -0,0 +1,15 @@
package edu.wpi.first.wpilibj.networktables2.stream;
import java.io.*;
public final class SocketStreams {
private SocketStreams(){}
public static IOStreamFactory newStreamFactory(String host, int port) throws IOException{
return new SocketStreamFactory(host, port);
}
public static IOStreamProvider newStreamProvider(int port) throws IOException {
return new SocketServerStreamProvider(port);
}
}

View File

@@ -0,0 +1,183 @@
package edu.wpi.first.wpilibj.networktables;
import edu.wpi.first.wpilibj.networktables2.client.NetworkTableClient;
import edu.wpi.first.wpilibj.networktables2.stream.IOStream;
import edu.wpi.first.wpilibj.networktables2.stream.IOStreamFactory;
import edu.wpi.first.wpilibj.tables.*;
import java.io.*;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.auto.Mock;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.*;
import org.junit.runner.RunWith;
@RunWith(JMock.class)
public class NetworkTableListenerTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
private NetworkTableClient client;
private NetworkTableProvider provider;
private NetworkTable testTable1;
private NetworkTable testTable2;
private NetworkTable testTable3;
private NetworkTable testSubTable1;
private NetworkTable testSubTable2;
private NetworkTable testSubTable3;
private NetworkTable testSubTable4;
@Before
public void init() throws IOException{
client = new NetworkTableClient(new IOStreamFactory(){
public IOStream createStream() throws IOException {
return null;
}
});
provider = new NetworkTableProvider(client);
testTable1 = (NetworkTable)provider.getTable("/test1");
testTable2 = (NetworkTable)provider.getTable("/test2");
testSubTable1 = (NetworkTable)provider.getTable("/test2/sub1");
testSubTable2 = (NetworkTable)provider.getTable("/test2/sub2");
testTable3 = (NetworkTable)provider.getTable("/test3");
testSubTable3 = (NetworkTable)provider.getTable("/test3/suba");
testSubTable4 = (NetworkTable)provider.getTable("/test3/suba/subb");
}
@After
public void cleanup(){
provider.close();
}
@Mock ITableListener listener1;
@Mock ITableListener listener2;
@Test
public void keyListenerImediateNotifyTest() throws IOException {
testTable1.putBoolean("MyKey1", true);
testTable1.putBoolean("MyKey1", false);
testTable1.putBoolean("MyKey2", true);
testTable1.putBoolean("MyKey4", false);
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable1, "MyKey1", false, true);
oneOf(listener1).valueChanged(testTable1, "MyKey2", true, true);
oneOf(listener1).valueChanged(testTable1, "MyKey4", false, true);
}});
testTable1.addTableListener(listener1, true);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable1, "MyKey", false, true);
}});
testTable1.putBoolean("MyKey", false);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable1, "MyKey1", true, false);
}});
testTable1.putBoolean("MyKey1", true);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable1, "MyKey1", false, false);
}});
testTable1.putBoolean("MyKey1", false);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable1, "MyKey4", true, false);
}});
testTable1.putBoolean("MyKey4", true);
context.assertIsSatisfied();
}
@Test
public void keyListenerNotImediateNotifyTest() throws IOException {
testTable1.putBoolean("MyKey1", true);
testTable1.putBoolean("MyKey1", false);
testTable1.putBoolean("MyKey2", true);
testTable1.putBoolean("MyKey4", false);
testTable1.addTableListener(listener1, false);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable1, "MyKey", false, true);
}});
testTable1.putBoolean("MyKey", false);
context.assertIsSatisfied();
/*context.checking(new Expectations() {{Should not fire because value was previously false
oneOf(listener1).valueChanged(testTable1, "MyKey1", false, false);
}});*/
testTable1.putBoolean("MyKey1", false);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable1, "MyKey1", true, false);
}});
testTable1.putBoolean("MyKey1", true);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable1, "MyKey4", true, false);
}});
testTable1.putBoolean("MyKey4", true);
context.assertIsSatisfied();
}
@Test
public void subTableListenerTest() throws IOException {
testTable2.putBoolean("MyKey1", true);
testTable2.putBoolean("MyKey2", true);
testTable2.addSubTableListener(listener1);
testTable2.putBoolean("MyKey1", false);
testTable2.putBoolean("MyKey4", false);
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable2, "sub1", testSubTable1, true);
}});
testSubTable1.putBoolean("MyKey1", false);
context.assertIsSatisfied();
testSubTable1.putBoolean("MyKey2", true);
testSubTable1.putBoolean("MyKey1", true);
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable2, "sub2", testSubTable2, true);
}});
testSubTable2.putBoolean("MyKey1", false);
context.assertIsSatisfied();
}
@Test
public void subSubTableListenerTest() throws IOException {
testTable3.addSubTableListener(listener1);
testSubTable3.addSubTableListener(listener1);
testSubTable4.addTableListener(listener1, true);
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testTable3, "suba", testSubTable3, true);
oneOf(listener1).valueChanged(testSubTable3, "subb", testSubTable4, true);
oneOf(listener1).valueChanged(testSubTable4, "MyKey1", false, true);
}});
testSubTable4.putBoolean("MyKey1", false);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listener1).valueChanged(testSubTable4, "MyKey1", true, false);
}});
testSubTable4.putBoolean("MyKey1", true);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listener2).valueChanged(testTable3, "suba", testSubTable3, true);
oneOf(listener2).valueChanged(testSubTable3, "subb", testSubTable4, true);
oneOf(listener2).valueChanged(testSubTable4, "MyKey1", true, true);
}});
testTable3.addSubTableListener(listener2);
testSubTable3.addSubTableListener(listener2);
testSubTable4.addTableListener(listener2, true);
context.assertIsSatisfied();
}
}

View File

@@ -0,0 +1,203 @@
package edu.wpi.first.wpilibj.networktables;
import edu.wpi.first.wpilibj.networktables2.client.NetworkTableClient;
import edu.wpi.first.wpilibj.networktables2.stream.IOStream;
import edu.wpi.first.wpilibj.networktables2.stream.IOStreamFactory;
import edu.wpi.first.wpilibj.tables.*;
import java.io.*;
import org.junit.*;
import static org.junit.Assert.*;
public class NetworkTableTest {
private NetworkTableClient client;
private NetworkTableProvider provider;
private NetworkTable testTable1;
private NetworkTable testTable2;
@Before
public void init() throws IOException{
client = new NetworkTableClient(new IOStreamFactory(){
public IOStream createStream() throws IOException {
return null;
}
});
provider = new NetworkTableProvider(client);
testTable1 = (NetworkTable)provider.getTable("/test1");
testTable2 = (NetworkTable)provider.getTable("/test2");
}
@After
public void cleanup(){
provider.close();
}
@Test
public void putDoubleTest() throws IOException {
double testDouble = 43.43;
testTable1.putNumber("double", 42.42);
try {
testDouble = testTable1.getNumber("double");
} catch (TableKeyNotDefinedException e) {
e.printStackTrace();
}
assertEquals(42.42, testDouble, 0.0);
try {
testDouble = testTable1.getNumber("Non-Existant");
fail();
} catch (TableKeyNotDefinedException e) {
}
testDouble = testTable1.getNumber("Non-Existant", 44.44);
assertEquals(44.44, testDouble, 0.0);
}
@Test
public void putBooleanTest() throws IOException {
boolean testBool = false;
testTable1.putBoolean("boolean", true);
try {
testBool = testTable1.getBoolean("boolean");
} catch (TableKeyNotDefinedException e) {
e.printStackTrace();
}
assertTrue(testBool);
try {
testBool = testTable1.getBoolean("Non-Existant");
fail();
} catch (TableKeyNotDefinedException e) {
}
testBool = testTable1.getBoolean("Non-Existant", false);
assertFalse(testBool);
}
@Test
public void putStringTest() throws IOException {
String testString = "Initialized Test";
testTable1.putString("String", "Test 1");
try {
testString = testTable1.getString("String");
} catch (TableKeyNotDefinedException e) {
e.printStackTrace();
}
assertEquals("Test 1", testString);
try {
testString = testTable1.getString("Non-Existant");
fail();
} catch (TableKeyNotDefinedException e) {
}
testString = testTable1.getString("Non-Existant", "Test 3");
assertEquals("Test 3", testString);
}
@Test
public void putMultiDataTypeTest() throws TableKeyNotDefinedException, IOException {
double double1 = 1;
double double2 = 2;
double double3 = 3;
boolean bool1 = false;
boolean bool2 = true;
String string1 = "String 1";
String string2 = "String 2";
String string3 = "String 3";
testTable1.putNumber("double1", double1);
testTable1.putNumber("double2", double2);
testTable1.putNumber("double3", double3);
testTable1.putBoolean("bool1", bool1);
testTable1.putBoolean("bool2", bool2);
testTable1.putString("string1", string1);
testTable1.putString("string2", string2);
testTable1.putString("string3", string3);
assertEquals(double1, testTable1.getNumber("double1"), 0.0);
assertEquals(double2, testTable1.getNumber("double2"), 0.0);
assertEquals(double3, testTable1.getNumber("double3"), 0.0);
assertEquals(bool1, testTable1.getBoolean("bool1"));
assertEquals(bool2, testTable1.getBoolean("bool2"));
assertEquals(string1, testTable1.getString("string1"));
assertEquals(string2, testTable1.getString("string2"));
assertEquals(string3, testTable1.getString("string3"));
double1 = 4;
double2 = 5;
double3 = 6;
bool1 = true;
bool2 = false;
string1 = "String 4";
string2 = "String 5";
string3 = "String 6";
testTable1.putNumber("double1", double1);
testTable1.putNumber("double2", double2);
testTable1.putNumber("double3", double3);
testTable1.putBoolean("bool1", bool1);
testTable1.putBoolean("bool2", bool2);
testTable1.putString("string1", string1);
testTable1.putString("string2", string2);
testTable1.putString("string3", string3);
assertEquals(double1, testTable1.getNumber("double1"), 0.0);
assertEquals(double2, testTable1.getNumber("double2"), 0.0);
assertEquals(double3, testTable1.getNumber("double3"), 0.0);
assertEquals(bool1, testTable1.getBoolean("bool1"));
assertEquals(bool2, testTable1.getBoolean("bool2"));
assertEquals(string1, testTable1.getString("string1"));
assertEquals(string2, testTable1.getString("string2"));
assertEquals(string3, testTable1.getString("string3"));
}
@Test
public void multiTableTest() throws IOException {
double table1double = 1;
double table2double = 2;
boolean table1boolean = true;
boolean table2boolean = false;
String table1String = "Table 1";
String table2String = "Table 2";
testTable1.putNumber("table1double", table1double);
testTable1.putBoolean("table1boolean", table1boolean);
testTable1.putString("table1String", table1String);
try {
testTable2.getNumber("table1double");
fail();
} catch(TableKeyNotDefinedException e){}
try {
testTable2.getBoolean("table1boolean");
fail();
} catch(TableKeyNotDefinedException e){}
try {
testTable2.getString("table1String");
fail();
} catch(TableKeyNotDefinedException e){}
testTable2.putNumber("table2double", table2double);
testTable2.putBoolean("table2boolean", table2boolean);
testTable2.putString("table2String", table2String);
try {
testTable1.getNumber("table2double");
fail();
} catch(TableKeyNotDefinedException e){}
try {
testTable1.getBoolean("table2boolean");
fail();
} catch(TableKeyNotDefinedException e){}
try {
testTable1.getString("table2String");
fail();
} catch(TableKeyNotDefinedException e){}
}
@Test
public void getTableTest() throws IOException{
assertSame(testTable1, provider.getTable("/test1"));
assertSame(testTable2, provider.getTable("/test2"));
assertNotSame(testTable1, provider.getTable("/test2"));
ITable testTable3 = provider.getTable("/test3");
assertNotSame(testTable1, testTable3);
assertNotSame(testTable2, testTable3);
}
}

View File

@@ -0,0 +1,201 @@
package edu.wpi.first.wpilibj.networktables2;
import static org.junit.Assert.*;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.AbstractNetworkTableEntryStore.TableListenerManager;
import edu.wpi.first.wpilibj.networktables2.connection.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
@RunWith(JMock.class)
public class NetworkTableEntryTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test public void testSendValue() throws IOException {
final NetworkTableEntryType type = context.mock(NetworkTableEntryType.class);
final Object value = "MyValue";
final NetworkTableEntry entry = new NetworkTableEntry((char)0, "MyKey", (char)0, type, value);
final DataOutputStream os = context.mock(DataOutputStream.class);
context.checking(new Expectations() {{
oneOf(type).sendValue(value, os);
}});
entry.sendValue(os);
}
@Test public void testToString() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newBooleanEntry("MyKey", false);
assertEquals( "Network Table Boolean entry: MyKey: 65535 - 0 - false", entry.toString());
}
@Test public void testSend() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newBooleanEntry((char)0, "MyBoolean", (char)0, true);
final NetworkTableConnection connection = context.mock(NetworkTableConnection.class);
context.checking(new Expectations() {{
oneOf(connection).sendEntryAssignment(entry);
}});
entry.send(connection);
}
@Test public void testConstructor() throws IOException {
final NetworkTableEntry entry = new NetworkTableEntry((char)10, "MyNotBoolean", (char)2, DefaultEntryTypes.STRING, "Test1");
assertEquals((char)10, entry.getId());
assertEquals("MyNotBoolean", entry.name);
assertEquals((char)2, entry.getSequenceNumber());
assertEquals(DefaultEntryTypes.STRING, entry.getType());
assertEquals("Test1", entry.getValue());
}
@Test public void testPut() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newStringEntry((char)10, "MyString", (char)2, "Test1");
assertTrue(entry.putValue((char)3, "Test5"));
assertEquals("Test5", entry.getValue());
assertEquals((char)3, entry.getSequenceNumber());
assertTrue(entry.putValue((char)4, "Test2"));
assertEquals("Test2", entry.getValue());
assertEquals((char)4, entry.getSequenceNumber());
assertFalse(entry.putValue((char)3, "Test3"));
assertEquals("Test2", entry.getValue());
assertEquals((char)4, entry.getSequenceNumber());
assertFalse(entry.putValue((char)40000, "Test22"));
assertEquals("Test2", entry.getValue());
assertEquals((char)4, entry.getSequenceNumber());
assertTrue(entry.putValue((char)30000, "Test10"));
assertEquals("Test10", entry.getValue());
assertEquals((char)30000, entry.getSequenceNumber());
assertTrue(entry.putValue((char)40000, "Test23"));
assertEquals("Test23", entry.getValue());
assertEquals((char)40000, entry.getSequenceNumber());
assertFalse(entry.putValue((char)30000, "Test100"));
assertEquals("Test23", entry.getValue());
assertEquals((char)40000, entry.getSequenceNumber());
assertTrue(entry.putValue((char)0, "Test0"));
assertEquals("Test0", entry.getValue());
assertEquals((char)0, entry.getSequenceNumber());
}
@Test public void testSetWhenValid() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newStringEntry("MyString", "Test1");
entry.setId((char)100);
}
@Test public void testSetWhenNotValid() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newStringEntry((char)10, "MyString", (char)2, "Test1");
try{
entry.setId((char)100);
fail();
} catch(RuntimeException e){
}
}
@Test public void testClearId() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newDoubleEntry("MyString", 203.2);
entry.setId((char)10);
assertEquals((char)10, entry.getId());
entry.clearId();
assertEquals(NetworkTableEntry.UNKNOWN_ID, entry.getId());
entry.setId((char)22);
assertEquals((char)22, entry.getId());
}
@Test public void testDirtyness() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newDoubleEntry("MyString", 203.2);
assertEquals(false, entry.isDirty());
entry.makeClean();
assertEquals(false, entry.isDirty());
entry.makeDirty();
assertEquals(true, entry.isDirty());
entry.makeClean();
assertEquals(false, entry.isDirty());
}
@Test public void testForcePut() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newStringEntry((char)10, "MyString", (char)2, "Test1");
entry.forcePut((char)3, "Test5");
assertEquals("Test5", entry.getValue());
assertEquals((char)3, entry.getSequenceNumber());
entry.forcePut((char)4, "Test2");
assertEquals("Test2", entry.getValue());
assertEquals((char)4, entry.getSequenceNumber());
entry.forcePut((char)3, "Test3");
assertEquals("Test3", entry.getValue());
assertEquals((char)3, entry.getSequenceNumber());
entry.forcePut((char)40000, "Test22");
assertEquals("Test22", entry.getValue());
assertEquals((char)40000, entry.getSequenceNumber());
entry.forcePut((char)30000, "Test10");
assertEquals("Test10", entry.getValue());
assertEquals((char)30000, entry.getSequenceNumber());
}
@Test public void testForcePutWithType() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newStringEntry((char)10, "MyString", (char)2, "Test1");
entry.forcePut((char)3, DefaultEntryTypes.BOOLEAN, true);
assertEquals(DefaultEntryTypes.BOOLEAN, entry.getType());
assertEquals(true, entry.getValue());
assertEquals((char)3, entry.getSequenceNumber());
entry.forcePut((char)4, DefaultEntryTypes.STRING, "HELLO");
assertEquals("HELLO", entry.getValue());
assertEquals(DefaultEntryTypes.STRING, entry.getType());
assertEquals((char)4, entry.getSequenceNumber());
entry.forcePut((char)3, DefaultEntryTypes.DOUBLE, 11.5);
assertEquals(DefaultEntryTypes.DOUBLE, entry.getType());
assertEquals(11.5, entry.getValue());
assertEquals((char)3, entry.getSequenceNumber());
entry.forcePut((char)3, DefaultEntryTypes.STRING, "HI");
assertEquals(DefaultEntryTypes.STRING, entry.getType());
assertEquals("HI", entry.getValue());
assertEquals((char)3, entry.getSequenceNumber());
}
@Test public void testFireListener() throws IOException {
final NetworkTableEntry entry = NetworkTableEntryUtil.newStringEntry((char)10, "MyString", (char)2, "Test1");
final TableListenerManager listenerManager = context.mock(TableListenerManager.class);
context.checking(new Expectations() {{
oneOf(listenerManager).fireTableListeners("MyString", "Test1", true);
}});
entry.fireListener(listenerManager);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(listenerManager).fireTableListeners("MyString", "Test1", false);
}});
entry.fireListener(listenerManager);
context.assertIsSatisfied();
entry.forcePut((char)0, "TEST3");
context.checking(new Expectations() {{
oneOf(listenerManager).fireTableListeners("MyString", "TEST3", false);
}});
entry.fireListener(listenerManager);
context.assertIsSatisfied();
}
}

View File

@@ -0,0 +1,67 @@
package edu.wpi.first.wpilibj.networktables2;
import java.io.*;
import org.jmock.*;
import org.jmock.auto.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
@RunWith(JMock.class)
public class TransactionDirtierTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Mock OutgoingEntryReceiver receiver;
TransactionDirtier dirtier;
@Before public void before(){
dirtier = new TransactionDirtier(receiver);
}
@Test public void testOutgoingCleanAssignment() throws IOException {
final NetworkTableEntry entry = context.mock(NetworkTableEntry.class);
context.checking(new Expectations() {{
oneOf(entry).isDirty();will(returnValue(false));
oneOf(entry).makeDirty();
oneOf(receiver).offerOutgoingAssignment(entry);
}});
dirtier.offerOutgoingAssignment(entry);
}
@Test public void testOutgoingCleanUpdate() throws IOException {
final NetworkTableEntry entry = context.mock(NetworkTableEntry.class);
context.checking(new Expectations() {{
oneOf(entry).isDirty();will(returnValue(false));
oneOf(entry).makeDirty();
oneOf(receiver).offerOutgoingUpdate(entry);
}});
dirtier.offerOutgoingUpdate(entry);
}
@Test public void testOutgoingDirtyAssignment() throws IOException {
final NetworkTableEntry entry = context.mock(NetworkTableEntry.class);
context.checking(new Expectations() {{
oneOf(entry).isDirty();will(returnValue(true));
}});
dirtier.offerOutgoingAssignment(entry);
}
@Test public void testOutgoingDirtyUpdate() throws IOException {
final NetworkTableEntry entry = context.mock(NetworkTableEntry.class);
context.checking(new Expectations() {{
oneOf(entry).isDirty();will(returnValue(true));
}});
dirtier.offerOutgoingUpdate(entry);
}
}

View File

@@ -0,0 +1,198 @@
package edu.wpi.first.wpilibj.networktables2.client;
import static org.junit.Assert.*;
import static org.hamcrest.core.IsInstanceOf.*;
import java.io.*;
import org.hamcrest.*;
import org.hamcrest.Description;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.connection.BadMessageException;
import edu.wpi.first.wpilibj.networktables2.stream.*;
import edu.wpi.first.wpilibj.networktables2.thread.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
@RunWith(JMock.class)
public class ClientConnectionAdapterTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test public void testKeepAlive() {
final ClientConnectionListenerManager connectionListenerManager = context.mock(ClientConnectionListenerManager.class);
final ClientNetworkTableEntryStore entryStore = context.mock(ClientNetworkTableEntryStore.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStreamFactory streamFactory = context.mock(IOStreamFactory.class);
ClientConnectionAdapter clientAdapter = new ClientConnectionAdapter(entryStore, threadManager, streamFactory, connectionListenerManager, new NetworkTableEntryTypeManager());
try{
clientAdapter.keepAlive();
} catch(BadMessageException e){
fail();
} catch(IOException e){
fail();
}
}
@Test public void testClientHello() {
final ClientConnectionListenerManager connectionListenerManager = context.mock(ClientConnectionListenerManager.class);
final ClientNetworkTableEntryStore entryStore = context.mock(ClientNetworkTableEntryStore.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStreamFactory streamFactory = context.mock(IOStreamFactory.class);
ClientConnectionAdapter clientAdapter = new ClientConnectionAdapter(entryStore, threadManager, streamFactory, connectionListenerManager, new NetworkTableEntryTypeManager());
try{
clientAdapter.clientHello((char)0);
fail();
} catch(BadMessageException e){
} catch(IOException e){
fail();
}
}
@Test public void testUnsupportedProtocol() {
final ClientConnectionListenerManager connectionListenerManager = context.mock(ClientConnectionListenerManager.class);
final ClientNetworkTableEntryStore entryStore = context.mock(ClientNetworkTableEntryStore.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStreamFactory streamFactory = context.mock(IOStreamFactory.class);
final IOStream stream = context.mock(IOStream.class);
final NTThread thread = context.mock(NTThread.class);
ClientConnectionAdapter clientAdapter = new ClientConnectionAdapter(entryStore, threadManager, streamFactory, connectionListenerManager, new NetworkTableEntryTypeManager());
try {
context.checking(new Expectations() {{
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
oneOf(streamFactory).createStream();will(returnValue(stream));
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Client Connection Reader Thread"));will(returnValue(thread));
oneOf(entryStore).clearIds();
}});
} catch (IOException e1) {}
clientAdapter.reconnect();
context.checking(new Expectations() {{
oneOf(stream).close();
oneOf(thread).stop();
oneOf(entryStore).clearIds();
}});
clientAdapter.protocolVersionUnsupported((char)10);
assertThat(clientAdapter.getConnectionState(), instanceOf(ClientConnectionState.ProtocolUnsuppotedByServer.class));
assertEquals((char)10, ((ClientConnectionState.ProtocolUnsuppotedByServer)clientAdapter.getConnectionState()).getServerVersion());
}
@Test public void testConnectionErrorBadMessage() {
final ClientConnectionListenerManager connectionListenerManager = context.mock(ClientConnectionListenerManager.class);
final ClientNetworkTableEntryStore entryStore = context.mock(ClientNetworkTableEntryStore.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStreamFactory streamFactory = context.mock(IOStreamFactory.class);
final IOStream stream = context.mock(IOStream.class);
final NTThread thread = context.mock(NTThread.class);
ClientConnectionAdapter clientAdapter = new ClientConnectionAdapter(entryStore, threadManager, streamFactory, connectionListenerManager, new NetworkTableEntryTypeManager());
try {
context.checking(new Expectations() {{
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
oneOf(streamFactory).createStream();will(returnValue(stream));
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Client Connection Reader Thread"));will(returnValue(thread));
oneOf(entryStore).clearIds();
}});
} catch (IOException e1) {}
clientAdapter.reconnect();
context.checking(new Expectations() {{
oneOf(stream).close();
oneOf(thread).stop();
oneOf(entryStore).clearIds();
}});
BadMessageException e = new BadMessageException("");
clientAdapter.badMessage(e);
assertThat(clientAdapter.getConnectionState(), isClientConnectionErrorState(e));
}
@Test public void testConnectionErrorIOException() {
final ClientConnectionListenerManager connectionListenerManager = context.mock(ClientConnectionListenerManager.class);
final ClientNetworkTableEntryStore entryStore = context.mock(ClientNetworkTableEntryStore.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStreamFactory streamFactory = context.mock(IOStreamFactory.class);
final IOStream stream1 = context.mock(IOStream.class, "stream1");
final IOStream stream2 = context.mock(IOStream.class, "stream2");
final NTThread thread1 = context.mock(NTThread.class, "thread1");
final NTThread thread2 = context.mock(NTThread.class, "thread2");
final ClientConnectionAdapter clientAdapter = new ClientConnectionAdapter(entryStore, threadManager, streamFactory, connectionListenerManager, new NetworkTableEntryTypeManager());
try {
context.checking(new Expectations() {{
allowing(stream1).getInputStream();
allowing(stream1).getOutputStream();
oneOf(streamFactory).createStream();will(returnValue(stream1));
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Client Connection Reader Thread"));will(returnValue(thread1));
oneOf(entryStore).clearIds();
}});
} catch (IOException e1) {}
clientAdapter.reconnect();
try {
context.checking(new Expectations() {{
oneOf(stream1).close();
oneOf(thread1).stop();
oneOf(entryStore).clearIds();
allowing(stream2).getInputStream();
allowing(stream2).getOutputStream();
oneOf(streamFactory).createStream();will(returnValue(stream2));
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Client Connection Reader Thread"));will(returnValue(thread2));
}});
} catch (IOException e1) {}
IOException e = new IOException("");
clientAdapter.ioException(e);
assertEquals(clientAdapter.getConnectionState(), ClientConnectionState.CONNECTED_TO_SERVER);
}
@Test public void testGetEntryType() {
final ClientConnectionListenerManager connectionListenerManager = context.mock(ClientConnectionListenerManager.class);
final ClientNetworkTableEntryStore entryStore = context.mock(ClientNetworkTableEntryStore.class);
final IOStreamFactory streamFactory = context.mock(IOStreamFactory.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final NetworkTableEntry entry1 = NetworkTableEntryUtil.newBooleanEntry("MyEntry", true);
final NetworkTableEntry entry2 = NetworkTableEntryUtil.newDoubleEntry("MyEntry", 12);
final NetworkTableEntry entry3 = NetworkTableEntryUtil.newStringEntry("MyEntry", "Value");
context.checking(new Expectations() {{
allowing(entryStore).getEntry((char)16);will(returnValue(entry1));
allowing(entryStore).getEntry((char)1);will(returnValue(entry2));
allowing(entryStore).getEntry((char)22);will(returnValue(entry3));
}});
ClientConnectionAdapter clientAdapter = new ClientConnectionAdapter(entryStore, threadManager, streamFactory, connectionListenerManager, new NetworkTableEntryTypeManager());
assertEquals(DefaultEntryTypes.BOOLEAN, clientAdapter.getEntry((char)16).getType());
assertEquals(DefaultEntryTypes.DOUBLE, clientAdapter.getEntry((char)1).getType());
assertEquals(DefaultEntryTypes.STRING, clientAdapter.getEntry((char)22).getType());
}
private Matcher<ClientConnectionState> isClientConnectionErrorState(final Exception e) {
return new TypeSafeMatcher<ClientConnectionState>() {
@Override
public void describeTo(Description description) {
description.appendText(" a connection error state with the exception ").appendValue(e);
}
@Override
public boolean matchesSafely(ClientConnectionState item) {
if(item instanceof ClientConnectionState.Error)
return ((ClientConnectionState.Error) item).getException()==e;
return false;
}
};
}
}

View File

@@ -0,0 +1,122 @@
package edu.wpi.first.wpilibj.networktables2.client;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import edu.wpi.first.wpilibj.networktables2.stream.*;
import edu.wpi.first.wpilibj.networktables2.thread.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
@RunWith(JMock.class)
public class ClientConnectionManagementTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test public void testReconnect() {
final ClientConnectionListenerManager connectionListenerManager = context.mock(ClientConnectionListenerManager.class);
final ClientNetworkTableEntryStore entryStore = context.mock(ClientNetworkTableEntryStore.class);
final IOStreamFactory streamFactory = context.mock(IOStreamFactory.class);
final IOStream stream1 = context.mock(IOStream.class, "stream1");
final IOStream stream2 = context.mock(IOStream.class, "stream2");
final NTThread thread1 = context.mock(NTThread.class, "thread1");
final NTThread thread2 = context.mock(NTThread.class, "thread2");
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
context.checking(new Expectations() {{
try{
allowing(stream1).getInputStream();
allowing(stream1).getOutputStream();
oneOf(entryStore).clearIds();
oneOf(streamFactory).createStream();will(returnValue(stream1));
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Client Connection Reader Thread"));will(returnValue(thread1));
} catch(IOException e){}
}});
ClientConnectionAdapter client = new ClientConnectionAdapter(entryStore, threadManager, streamFactory, connectionListenerManager, new NetworkTableEntryTypeManager());
client.reconnect();
context.checking(new Expectations() {{
try{
allowing(stream2).getInputStream();
allowing(stream2).getOutputStream();
oneOf(entryStore).clearIds();
oneOf(thread1).stop();
oneOf(stream1).close();
oneOf(streamFactory).createStream();will(returnValue(stream2));
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Client Connection Reader Thread"));will(returnValue(thread2));
} catch(IOException e){}
}});
client.reconnect();
}
@Test public void testClose() {
final ClientConnectionListenerManager connectionListenerManager = context.mock(ClientConnectionListenerManager.class);
final ClientNetworkTableEntryStore entryStore = context.mock(ClientNetworkTableEntryStore.class);
final IOStreamFactory streamFactory = context.mock(IOStreamFactory.class);
final IOStream stream1 = context.mock(IOStream.class);
final NTThread thread1 = context.mock(NTThread.class, "thread1");
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
context.checking(new Expectations() {{
try{
allowing(stream1).getInputStream();
allowing(stream1).getOutputStream();
oneOf(entryStore).clearIds();
oneOf(streamFactory).createStream();will(returnValue(stream1));
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Client Connection Reader Thread"));will(returnValue(thread1));
}catch(IOException e){}
}});
ClientConnectionAdapter client = new ClientConnectionAdapter(entryStore, threadManager, streamFactory, connectionListenerManager, new NetworkTableEntryTypeManager());
client.reconnect();
context.checking(new Expectations() {{
oneOf(entryStore).clearIds();
oneOf(thread1).stop();
oneOf(stream1).close();
}});
client.close();
}
@Test public void testFailCreateStream() {
final ClientNetworkTableEntryStore entryStore = context.mock(ClientNetworkTableEntryStore.class);
final IOStreamFactory streamFactory = context.mock(IOStreamFactory.class);
final IOStream stream1 = context.mock(IOStream.class, "stream1");
final NTThread thread1 = context.mock(NTThread.class, "thread1");
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final ClientConnectionListenerManager connectionListenerManager = context.mock(ClientConnectionListenerManager.class);
context.checking(new Expectations() {{
try{
allowing(stream1).getInputStream();
allowing(stream1).getOutputStream();
oneOf(entryStore).clearIds();
oneOf(streamFactory).createStream();will(returnValue(stream1));
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Client Connection Reader Thread"));will(returnValue(thread1));
} catch(IOException e){}
}});
ClientConnectionAdapter client = new ClientConnectionAdapter(entryStore, threadManager, streamFactory, connectionListenerManager, new NetworkTableEntryTypeManager());
client.reconnect();
context.checking(new Expectations() {{
try{
oneOf(entryStore).clearIds();
oneOf(thread1).stop();
oneOf(stream1).close();
oneOf(streamFactory).createStream();will(returnValue(null));
} catch(IOException e){}
}});
client.reconnect();
}
}

View File

@@ -0,0 +1,52 @@
package edu.wpi.first.wpilibj.networktables2.client;
import static org.junit.Assert.*;
import java.io.*;
import org.hamcrest.*;
import org.hamcrest.Description;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.AbstractNetworkTableEntryStore.TableListenerManager;
import edu.wpi.first.wpilibj.networktables2.connection.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
import edu.wpi.first.wpilibj.tables.*;
@RunWith(JMock.class)
public class ClientNetworkTableEntryStoreTest {
Mockery context = new JUnit4Mockery();
TableListenerManager tlm;
OutgoingEntryReceiver oer;
ClientNetworkTableEntryStore clientStore;
@Before
public void setup() {
tlm = context.mock(TableListenerManager.class);
oer = context.mock(OutgoingEntryReceiver.class);
clientStore = new ClientNetworkTableEntryStore(tlm);
clientStore.setOutgoingReceiver(oer);
}
@Test(expected=TableKeyExistsWithDifferentTypeException.class)
public void testPutOfExistingKeyWithDifferentTypeThrowsException() {
context.checking(new Expectations() {{
oneOf(tlm).fireTableListeners(with("TestKey"), with(any(Double.class)), with(any(boolean.class)));
oneOf(oer).offerOutgoingAssignment(with(any(NetworkTableEntry.class)));
}});
clientStore.putOutgoing("TestKey", DefaultEntryTypes.DOUBLE, new Double(3));
// This call should throw an exception, because the entry already exists
// with type double.
clientStore.putOutgoing("TestKey", DefaultEntryTypes.STRING, new String("abc"));
}
}

View File

@@ -0,0 +1,52 @@
package edu.wpi.first.wpilibj.networktables2.client;
import static org.junit.Assert.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.junit.*;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.stream.*;
import edu.wpi.first.wpilibj.networktables2.thread.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
import edu.wpi.first.wpilibj.tables.*;
public class ClientTest {
Mockery context = new JUnit4Mockery();
NetworkTableClient client;
@Before
public void setup() {
IOStreamFactory ioStreamFactory = context.mock(IOStreamFactory.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
context.checking(new Expectations() {{
oneOf(threadManager).newBlockingPeriodicThread(with(any(WriteManager.class)), with("Write Manager Thread"));
}});
client = new NetworkTableClient(ioStreamFactory, new NetworkTableEntryTypeManager(), threadManager);
}
@Test public void testOfflinePutGet() throws TableKeyNotDefinedException {
client.putBoolean("MyKey", false);
assertEquals(false, client.getBoolean("MyKey"));
client.putBoolean("MyKey", true);
assertEquals(true, client.getBoolean("MyKey"));
client.putBoolean("MyKey", false);
assertEquals(false, client.getBoolean("MyKey"));
}
@Test public void testUndefinedKey() {
try{
client.getBoolean("MyKey");
fail();
} catch(TableKeyNotDefinedException e){
assertEquals("Unkown Table Key: MyKey", e.getMessage());
}
}
@Test(expected=TableKeyExistsWithDifferentTypeException.class)
public void testPutToExistingKeyWithDifferentTypeThrowsExeption() {
client.putDouble("TestKey", 3.0);
client.putString("TestKey", "abc");
}
}

View File

@@ -0,0 +1,18 @@
package edu.wpi.first.wpilibj.networktables2.connection;
import static org.junit.Assert.*;
import org.junit.*;
public class BadMessageExceptionTest {
@Test
public void throwExceptionTest(){
try {
throw new BadMessageException("Got some bad message");
} catch (BadMessageException e) {
assertEquals("Got some bad message", e.getMessage());
}
}
}

View File

@@ -0,0 +1,50 @@
package edu.wpi.first.wpilibj.networktables2.connection;
import java.io.*;
import org.jmock.*;
import org.jmock.auto.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import edu.wpi.first.wpilibj.networktables2.*;
@RunWith(JMock.class)
public class ConnectionMonitorThreadTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Mock ConnectionAdapter adapter;
@Mock NetworkTableConnection connection;
ConnectionMonitorThread thread;
@Before public void before(){
thread = new ConnectionMonitorThread(adapter, connection);
}
@Test public void testSimpleRead() throws Exception {
context.checking(new Expectations() {{
oneOf(connection).read(adapter);
}});
thread.run();
}
@Test public void testReadIOException() throws Exception {
final IOException e = new IOException();
context.checking(new Expectations() {{
oneOf(connection).read(adapter);will(throwException(e));
oneOf(adapter).ioException(e);
}});
thread.run();
}
@Test public void testReadBadMessageException() throws Exception {
final BadMessageException e = new BadMessageException("");
context.checking(new Expectations() {{
oneOf(connection).read(adapter);will(throwException(e));
oneOf(adapter).badMessage(e);
}});
thread.run();
}
}

View File

@@ -0,0 +1,112 @@
package edu.wpi.first.wpilibj.networktables2.connection;
import static org.junit.Assert.*;
import static test.util.NetworkTableEntryUtil.*;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
@RunWith(JMock.class)
public class NetworkTableConnectionEntryAssignmentTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test public void testBooleanEntryAssignmentSend() throws IOException {
ByteArrayStream stream = new ByteArrayStream();
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.sendEntryAssignment(NetworkTableEntryUtil.newBooleanEntry("My Entry", true));
connection.flush();
assertArrayEquals(new byte[]{16, 0, 8, 77, 121, 32, 69, 110, 116, 114, 121, 0, -1, -1, 0, 0, 1}, stream.getOutput());
}
@Test public void testBooleanEntryAssignmentReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{16, 0, 8, 77, 121, 32, 69, 110, 116, 114, 121, 0, -1, -1, 0, 0, 1});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
context.checking(new Expectations() {{
oneOf(receiver).offerIncomingAssignment(with(aBooleanEntry(0xFFFF, "My Entry", 0, true)));
}});
connection.read(receiver);
}
@Test public void testDoubleEntryAssignmentSend() throws IOException {
ByteArrayStream stream = new ByteArrayStream();
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.sendEntryAssignment(newDoubleEntry("My Entry", 12.5));
connection.flush();
assertArrayEquals(new byte[]{16, 0, 8, 77, 121, 32, 69, 110, 116, 114, 121, 1, -1, -1, 0, 0, 64, 41, 0, 0, 0, 0, 0, 0}, stream.getOutput());
}
@Test public void testDoubleEntryAssignmentReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{16, 0, 8, 77, 121, 32, 69, 110, 116, 114, 121, 1, -1, -1, 0, 0, 64, 41, 0, 0, 0, 0, 0, 0});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
context.checking(new Expectations() {{
oneOf(receiver).offerIncomingAssignment(with(aDoubleEntry(0xFFFF, "My Entry", 0, 12.5)));
}});
connection.read(receiver);
}
@Test public void testStringEntryAssignmentSend() throws IOException {
ByteArrayStream stream = new ByteArrayStream();
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.sendEntryAssignment(NetworkTableEntryUtil.newStringEntry("My Entry", "VaLuE"));
connection.flush();
assertArrayEquals(new byte[]{16, 0, 8, 77, 121, 32, 69, 110, 116, 114, 121, 2, -1, -1, 0, 0, 0, 5, 86, 97, 76, 117, 69}, stream.getOutput());
}
@Test public void testStringEntryAssignmentReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{16, 0, 8, 77, 121, 32, 69, 110, 116, 114, 121, 2, -1, -1, 0, 0, 0, 5, 86, 97, 76, 117, 69});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
context.checking(new Expectations() {{
oneOf(receiver).offerIncomingAssignment(with(aStringEntry(0xFFFF, "My Entry", 0, "VaLuE")));
}});
connection.read(receiver);
}
@Test public void testBadTypeEntryAssignmentReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{16, 0, 8, 77, 121, 32, 69, 110, 116, 114, 121, 127});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
try{
connection.read(receiver);
fail();
} catch(BadMessageException e){
} catch(IOException e){
fail();
}
}
}

View File

@@ -0,0 +1,100 @@
package edu.wpi.first.wpilibj.networktables2.connection;
import static org.junit.Assert.*;
import static test.util.NetworkTableEntryUtil.*;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
@RunWith(JMock.class)
public class NetworkTableConnectionEntryUpdateTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test public void testBooleanEntryUpdateSend() throws IOException {
ByteArrayStream stream = new ByteArrayStream();
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.sendEntryUpdate(newBooleanEntry((char)16, "My Entry", (char)0, true));
connection.flush();
assertArrayEquals(new byte[]{17, 0, 16, 0, 0, 1}, stream.getOutput());
}
@Test public void testBooleanEntryUpdateReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{17, 0, 16, 0, 0, 1});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
final NetworkTableEntry entry = newBooleanEntry((char)16, "MyEntry", (char)10, false);
context.checking(new Expectations() {{
oneOf(receiver).offerIncomingUpdate(entry, (char)0, true);
allowing(receiver).getEntry((char)16);will(returnValue(entry));
}});
connection.read(receiver);
}
@Test public void testDoubleEntryUpdateSend() throws IOException {
ByteArrayStream stream = new ByteArrayStream();
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.sendEntryUpdate(newDoubleEntry((char)16, "My Entry", (char)0, 12.5));
connection.flush();
assertArrayEquals(new byte[]{17, 0, 16, 0, 0, 64, 41, 0, 0, 0, 0, 0, 0}, stream.getOutput());
}
@Test public void testDoubleEntryUpdateReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{17, 0, 16, 0, 0, 64, 41, 0, 0, 0, 0, 0, 0});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
final NetworkTableEntry entry = newDoubleEntry((char)16, "MyEntry", (char)10, 3);
context.checking(new Expectations() {{
allowing(receiver).getEntry((char)16);will(returnValue(entry));
oneOf(receiver).offerIncomingUpdate(entry, (char)0, 12.5);
}});
connection.read(receiver);
}
@Test public void testStringEntryUpdateSend() throws IOException {
ByteArrayStream stream = new ByteArrayStream();
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.sendEntryUpdate(NetworkTableEntryUtil.newStringEntry((char)16, "My Entry", (char)0, "VaLuE"));
connection.flush();
assertArrayEquals(new byte[]{17, 0, 16, 0, 0, 0, 5, 86, 97, 76, 117, 69}, stream.getOutput());
}
@Test public void testStringEntryUpdateReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{17, 0, 16, 0, 0, 0, 5, 86, 97, 76, 117, 69});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
final NetworkTableEntry entry = newStringEntry((char)16, "MyEntry", (char)10, "HI");
context.checking(new Expectations() {{
allowing(receiver).getEntry((char)16);will(returnValue(entry));
oneOf(receiver).offerIncomingUpdate(entry, (char)0, "VaLuE");
}});
connection.read(receiver);
}
}

View File

@@ -0,0 +1,148 @@
package edu.wpi.first.wpilibj.networktables2.connection;
import static org.junit.Assert.*;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.stream.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
@RunWith(JMock.class)
public class NetworkTableConnectionTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test public void testProperties() {
final IOStream stream = context.mock(IOStream.class);
context.checking(new Expectations() {{
ignoring(stream);
}});
@SuppressWarnings("unused")
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
}
@Test public void testClose() {
final IOStream stream = context.mock(IOStream.class);
context.checking(new Expectations() {{
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
oneOf(stream).close();
}});
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.close();
}
@Test public void testCloseTwice() {
final IOStream stream = context.mock(IOStream.class);
context.checking(new Expectations() {{
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
oneOf(stream).close();
}});
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.close();
connection.close();
}
@Test public void testKeepAliveSend() throws IOException {
ByteArrayStream stream = new ByteArrayStream();
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.sendKeepAlive();
assertArrayEquals(new byte[]{0}, stream.getOutput());
}
@Test public void testKeepAliveReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{0});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
context.checking(new Expectations() {{
oneOf(receiver).keepAlive();
}});
connection.read(receiver);
}
@Test public void testClientHelloSend() throws IOException {
ByteArrayStream stream = new ByteArrayStream();
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.sendClientHello();
assertArrayEquals(new byte[]{1, 2, 00}, stream.getOutput());
}
@Test public void testClientHelloReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{1, 0, 4});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
context.checking(new Expectations() {{
oneOf(receiver).clientHello((char)4);
}});
connection.read(receiver);
}
@Test public void testProtocolVersionUnsupportedSend() throws IOException {
ByteArrayStream stream = new ByteArrayStream();
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
connection.sendProtocolVersionUnsupported();
assertArrayEquals(new byte[]{2, 2, 00}, stream.getOutput());
}
@Test public void testProtocolVersionUnsupportedReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{2, 0, 4});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
context.checking(new Expectations() {{
oneOf(receiver).protocolVersionUnsupported((char)4);
}});
connection.read(receiver);
}
@Test public void testBadMessageTypeReceive() throws IOException {
ByteArrayStream stream = new ByteArrayStream(new byte[]{127});
final ConnectionAdapter receiver = context.mock(ConnectionAdapter.class);
NetworkTableConnection connection = new NetworkTableConnection(stream, new NetworkTableEntryTypeManager());
try{
connection.read(receiver);
fail();
} catch(BadMessageException e){
} catch(IOException e){
fail();
}
}
}

View File

@@ -0,0 +1,71 @@
package edu.wpi.first.wpilibj.networktables2.server;
import edu.wpi.first.wpilibj.networktables2.*;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
@RunWith(JMock.class)
public class ConnectionListTest {
Mockery context = new JUnit4Mockery(){{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test public void testSendTransaction() throws IOException {
final ServerConnectionAdapter adapter1 = context.mock(ServerConnectionAdapter.class, "adapter 1");
final ServerConnectionAdapter adapter2 = context.mock(ServerConnectionAdapter.class, "adapter 2");
final NetworkTableEntry entry1 = context.mock(NetworkTableEntry.class, "entry1");
final NetworkTableEntry entry2 = context.mock(NetworkTableEntry.class, "entry2");
ServerConnectionList connectionList = new ServerConnectionList();
connectionList.add(adapter1);
connectionList.add(adapter2);
context.checking(new Expectations() {{
oneOf(adapter1).offerOutgoingAssignment(entry1);
oneOf(adapter2).offerOutgoingAssignment(entry1);
}});
connectionList.offerOutgoingAssignment(entry1);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(adapter1).offerOutgoingAssignment(entry2);
oneOf(adapter2).offerOutgoingAssignment(entry2);
}});
connectionList.offerOutgoingAssignment(entry2);
}
@Test public void testClose() throws IOException {
final ServerConnectionAdapter adapter1 = context.mock(ServerConnectionAdapter.class, "adapter 1");
final ServerConnectionAdapter adapter2 = context.mock(ServerConnectionAdapter.class, "adapter 2");
final NetworkTableEntry entry1 = context.mock(NetworkTableEntry.class, "entry1");
final NetworkTableEntry entry2 = context.mock(NetworkTableEntry.class, "entry2");
ServerConnectionList connectionList = new ServerConnectionList();
connectionList.add(adapter1);
connectionList.add(adapter2);
context.checking(new Expectations() {{
oneOf(adapter1).offerOutgoingAssignment(entry1);
oneOf(adapter2).offerOutgoingAssignment(entry1);
}});
connectionList.offerOutgoingAssignment(entry1);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(adapter1).shutdown(true);
}});
connectionList.close(adapter1, true);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(adapter2).offerOutgoingAssignment(entry2);
}});
connectionList.offerOutgoingAssignment(entry2);
}
}

View File

@@ -0,0 +1,223 @@
package edu.wpi.first.wpilibj.networktables2.server;
import static org.junit.Assert.*;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.connection.BadMessageException;
import edu.wpi.first.wpilibj.networktables2.stream.*;
import edu.wpi.first.wpilibj.networktables2.thread.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
@RunWith(JMock.class)
public class ServerConnectionAdapterTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test public void testServerConnectionState() throws IOException {
assertEquals("GOT_CONNECTION_FROM_CLIENT", ServerConnectionState.GOT_CONNECTION_FROM_CLIENT.toString());
assertEquals("CONNECTED_TO_CLIENT", ServerConnectionState.CONNECTED_TO_CLIENT.toString());
assertEquals("CLIENT_DISCONNECTED", ServerConnectionState.CLIENT_DISCONNECTED.toString());
assertEquals("SERVER_ERROR: class java.io.IOException: Something happended", new ServerConnectionState.Error(new IOException("Something happended")).toString());
}
@Test public void testKeepAlive() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final IncomingEntryReceiver transactionReceiver = context.mock(IncomingEntryReceiver.class);
final ServerAdapterManager connectionListener = context.mock(ServerAdapterManager.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStream stream = context.mock(IOStream.class);
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
}});
ServerConnectionAdapter serverAdapter = new ServerConnectionAdapter(stream, entryStore, transactionReceiver, connectionListener, new NetworkTableEntryTypeManager(), threadManager);
serverAdapter.keepAlive();
}
@Test public void testClientHello() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final IncomingEntryReceiver transactionReceiver = context.mock(IncomingEntryReceiver.class);
final ServerAdapterManager connectionListener = context.mock(ServerAdapterManager.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStream stream = context.mock(IOStream.class);
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
}});
final ServerConnectionAdapter serverAdapter = new ServerConnectionAdapter(stream, entryStore, transactionReceiver, connectionListener, new NetworkTableEntryTypeManager(), threadManager);
context.assertIsSatisfied();
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
oneOf(entryStore).sendServerHello(serverAdapter.connection);
}});
assertEquals(ServerConnectionState.GOT_CONNECTION_FROM_CLIENT, serverAdapter.getConnectionState());
serverAdapter.clientHello((char)0x0200);
assertEquals(ServerConnectionState.CONNECTED_TO_CLIENT, serverAdapter.getConnectionState());
}
@Test public void testUnsupportedProtocol() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final IncomingEntryReceiver transactionReceiver = context.mock(IncomingEntryReceiver.class);
final ServerAdapterManager connectionListener = context.mock(ServerAdapterManager.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStream stream = context.mock(IOStream.class);
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
}});
final ServerConnectionAdapter serverAdapter = new ServerConnectionAdapter(stream, entryStore, transactionReceiver, connectionListener, new NetworkTableEntryTypeManager(), threadManager);
try{
serverAdapter.protocolVersionUnsupported((char)0);
fail();
} catch(BadMessageException e){
}
}
@Test public void testUnsupportedClientProtocol() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final IncomingEntryReceiver transactionReceiver = context.mock(IncomingEntryReceiver.class);
final ServerAdapterManager connectionListener = context.mock(ServerAdapterManager.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final ByteArrayStream stream = new ByteArrayStream();
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
}});
final ServerConnectionAdapter serverAdapter = new ServerConnectionAdapter(stream, entryStore, transactionReceiver, connectionListener, new NetworkTableEntryTypeManager(), threadManager);
try{
serverAdapter.clientHello((char)0);
fail();
} catch(BadMessageException e){
}
assertArrayEquals(new byte[]{0x02, 0x02, (byte)0x00}, stream.getOutput());
}
@Test public void testConnectionErrorBadMessage() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final IncomingEntryReceiver transactionReceiver = context.mock(IncomingEntryReceiver.class);
final ServerAdapterManager connectionListener = context.mock(ServerAdapterManager.class);
final IOStream stream = context.mock(IOStream.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
}});
final ServerConnectionAdapter serverAdapter = new ServerConnectionAdapter(stream, entryStore, transactionReceiver, connectionListener, new NetworkTableEntryTypeManager(), threadManager);
context.assertIsSatisfied();
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
oneOf(connectionListener).close(serverAdapter, true);
}});
serverAdapter.badMessage(new BadMessageException(""));
}
@Test public void testConnectionErrorIOException() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final IncomingEntryReceiver transactionReceiver = context.mock(IncomingEntryReceiver.class);
final ServerAdapterManager connectionListener = context.mock(ServerAdapterManager.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStream stream = context.mock(IOStream.class);
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
}});
final ServerConnectionAdapter serverAdapter = new ServerConnectionAdapter(stream, entryStore, transactionReceiver, connectionListener, new NetworkTableEntryTypeManager(), threadManager);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(connectionListener).close(serverAdapter, false);
}});
serverAdapter.ioException(new IOException(""));
}
@Test public void testClientDisconnect() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final IncomingEntryReceiver transactionReceiver = context.mock(IncomingEntryReceiver.class);
final ServerAdapterManager connectionListener = context.mock(ServerAdapterManager.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStream stream = context.mock(IOStream.class);
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
}});
final ServerConnectionAdapter serverAdapter = new ServerConnectionAdapter(stream, entryStore, transactionReceiver, connectionListener, new NetworkTableEntryTypeManager(), threadManager);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(connectionListener).close(serverAdapter, false);
}});
serverAdapter.ioException(new EOFException());
assertEquals(ServerConnectionState.CLIENT_DISCONNECTED, serverAdapter.getConnectionState());
}
@Test public void testGetEntryType() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final IncomingEntryReceiver transactionReceiver = context.mock(IncomingEntryReceiver.class);
final ServerAdapterManager connectionListener = context.mock(ServerAdapterManager.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final IOStream stream = context.mock(IOStream.class);
context.checking(new Expectations() {{
ignoring(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Connection Reader Thread"));
allowing(stream).getInputStream();
allowing(stream).getOutputStream();
}});
final NetworkTableEntry entry1 = NetworkTableEntryUtil.newBooleanEntry("MyEntry", true);
final NetworkTableEntry entry2 = NetworkTableEntryUtil.newDoubleEntry("MyEntry", 12);
final NetworkTableEntry entry3 = NetworkTableEntryUtil.newStringEntry("MyEntry", "Value");
context.checking(new Expectations() {{
allowing(entryStore).getEntry((char)16);will(returnValue(entry1));
allowing(entryStore).getEntry((char)1);will(returnValue(entry2));
allowing(entryStore).getEntry((char)22);will(returnValue(entry3));
}});
final ServerConnectionAdapter serverAdapter = new ServerConnectionAdapter(stream, entryStore, transactionReceiver, connectionListener, new NetworkTableEntryTypeManager(), threadManager);
assertEquals(DefaultEntryTypes.BOOLEAN, serverAdapter.getEntry((char)16).getType());
assertEquals(DefaultEntryTypes.DOUBLE, serverAdapter.getEntry((char)1).getType());
assertEquals(DefaultEntryTypes.STRING, serverAdapter.getEntry((char)22).getType());
}
}

View File

@@ -0,0 +1,182 @@
package edu.wpi.first.wpilibj.networktables2.server;
import static org.junit.Assert.*;
import java.io.*;
import org.hamcrest.*;
import org.hamcrest.Description;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.stream.*;
import edu.wpi.first.wpilibj.networktables2.thread.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
@RunWith(JMock.class)
public class ServerIncomingMonitorTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};;
@Test public void testReceiveConnections() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final ServerAdapterManager adapterListener = context.mock(ServerAdapterManager.class);
final IOStreamProvider streamProvider = context.mock(IOStreamProvider.class);
final TestThreadManager threadManager = new TestThreadManager();
final IOStream stream1 = new ByteArrayStream();
final IOStream stream2 = new ByteArrayStream();
final ServerIncomingConnectionListener incomingListener = context.mock(ServerIncomingConnectionListener.class);
final States progress = context.states("progress").startsAs("sendFirst");
context.checking(new Expectations() {{
oneOf(streamProvider).accept();will(returnValue(stream1));when(progress.is("sendFirst"));then(progress.is("sentFirst"));
oneOf(incomingListener).onNewConnection(with(aConnectionAdapterFor(stream1)));
when(progress.is("sentFirst"));then(progress.is("receivedFirst"));
oneOf(streamProvider).accept();will(returnValue(stream2));when(progress.is("sendSecond"));then(progress.is("sentSecond"));
oneOf(incomingListener).onNewConnection(with(aConnectionAdapterFor(stream2)));
when(progress.is("sentSecond"));then(progress.is("receivedSecond"));
}});
ServerIncomingStreamMonitor incomingMonitor = new ServerIncomingStreamMonitor(streamProvider, entryStore,
incomingListener, adapterListener, new NetworkTableEntryTypeManager(), threadManager);
incomingMonitor.start();
threadManager.getPeriodicThread(ServerIncomingStreamMonitor.class).run();
assertThat(progress, hasState("receivedFirst"));
progress.become("sendSecond");
threadManager.getPeriodicThread(ServerIncomingStreamMonitor.class).run();
assertThat(progress, hasState("receivedSecond"));
}
@Test public void testClose() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final ServerAdapterManager adapterListener = context.mock(ServerAdapterManager.class);
final IOStreamProvider streamProvider = context.mock(IOStreamProvider.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final NTThread thread = context.mock(NTThread.class);
final ServerIncomingConnectionListener incomingListener = context.mock(ServerIncomingConnectionListener.class);
final States progress = context.states("progress").startsAs("creating monitor");
context.checking(new Expectations() {{
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Incoming Stream Monitor Thread"));will(returnValue(thread));
when(progress.is("starting monitor"));then(progress.is("started monitor"));
oneOf(thread).stop();when(progress.is("stopping monitor"));then(progress.is("stopped monitor"));
}});
ServerIncomingStreamMonitor incomingMonitor = new ServerIncomingStreamMonitor(streamProvider, entryStore,
incomingListener, adapterListener, new NetworkTableEntryTypeManager(), threadManager);
progress.become("starting monitor");
incomingMonitor.start();
assertThat(progress, hasState("started monitor"));
progress.become("stopping monitor");
incomingMonitor.stop();
assertThat(progress, hasState("stopped monitor"));
}
@Test public void testStopWithoutStart() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final ServerAdapterManager adapterListener = context.mock(ServerAdapterManager.class);
final IOStreamProvider streamProvider = context.mock(IOStreamProvider.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final ServerIncomingConnectionListener incomingListener = context.mock(ServerIncomingConnectionListener.class);
ServerIncomingStreamMonitor incomingMonitor = new ServerIncomingStreamMonitor(streamProvider, entryStore,
incomingListener, adapterListener, new NetworkTableEntryTypeManager(), threadManager);
incomingMonitor.stop();
}
@Test public void testNullStream() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final ServerAdapterManager adapterListener = context.mock(ServerAdapterManager.class);
final IOStreamProvider streamProvider = context.mock(IOStreamProvider.class);
final TestThreadManager threadManager = new TestThreadManager();
final ServerIncomingConnectionListener incomingListener = context.mock(ServerIncomingConnectionListener.class);
context.checking(new Expectations() {{
oneOf(streamProvider).accept();will(returnValue(null));
}});
ServerIncomingStreamMonitor incomingMonitor = new ServerIncomingStreamMonitor(streamProvider, entryStore,
incomingListener, adapterListener, new NetworkTableEntryTypeManager(), threadManager);
incomingMonitor.start();
threadManager.getPeriodicThread(ServerIncomingStreamMonitor.class).run();
}
@Test public void testStreamAcceptException() throws IOException {
final ServerNetworkTableEntryStore entryStore = context.mock(ServerNetworkTableEntryStore.class);
final ServerAdapterManager adapterListener = context.mock(ServerAdapterManager.class);
final IOStreamProvider streamProvider = context.mock(IOStreamProvider.class);
final TestThreadManager threadManager = new TestThreadManager();
final ServerIncomingConnectionListener incomingListener = context.mock(ServerIncomingConnectionListener.class);
context.checking(new Expectations() {{
oneOf(streamProvider).accept();will(throwException(new IOException("Something bad happened")));
}});
ServerIncomingStreamMonitor incomingMonitor = new ServerIncomingStreamMonitor(streamProvider, entryStore,
incomingListener, adapterListener, new NetworkTableEntryTypeManager(), threadManager);
incomingMonitor.start();
threadManager.getPeriodicThread(ServerIncomingStreamMonitor.class).run();
}
private Matcher<ServerConnectionAdapter> aConnectionAdapterFor(final IOStream stream) {
return new TypeSafeMatcher<ServerConnectionAdapter>(){
@Override
public void describeTo(Description description) {
description.appendText(" a server connection adapter for ").appendValue(stream);
}
@Override
public boolean matchesSafely(ServerConnectionAdapter adapter) {
return adapter.connection.stream==stream;
}
};
}
private Matcher<States> hasState(final String state) {
return new TypeSafeMatcher<States>(){
@Override
public void describeTo(Description description) {
description.appendText(" has the state: ").appendValue(state);
}
@Override
public boolean matchesSafely(States stateMachine) {
return stateMachine.is(state).isActive();
}
};
}
}

View File

@@ -0,0 +1,39 @@
package edu.wpi.first.wpilibj.networktables2.server;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.junit.*;
import org.junit.runner.*;
import edu.wpi.first.wpilibj.networktables2.stream.*;
import edu.wpi.first.wpilibj.networktables2.thread.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
@RunWith(JMock.class)
public class ServerTest {
Mockery context = new JUnit4Mockery();
@Test public void testClose() throws IOException {
final IOStreamProvider streamProvider = context.mock(IOStreamProvider.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final NTThread thread1 = context.mock(NTThread.class, "thread 1");
final NTThread thread2 = context.mock(NTThread.class, "thread 2");
context.checking(new Expectations() {{
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Write Manager Thread"));will(returnValue(thread1));
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Server Incoming Stream Monitor Thread"));will(returnValue(thread2));
}});
NetworkTableServer server = new NetworkTableServer(streamProvider, new NetworkTableEntryTypeManager(), threadManager);
context.checking(new Expectations() {{
oneOf(thread1).stop();
oneOf(thread2).stop();
oneOf(streamProvider).close();
}});
server.close();
}
}

View File

@@ -0,0 +1,80 @@
package edu.wpi.first.wpilibj.networktables2.server;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.thread.*;
@RunWith(JMock.class)
public class ServerWriteManagerTest {
Mockery context = new JUnit4Mockery(){{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test public void testSendTransaction() throws Exception {
final TestThreadManager threadManager = new TestThreadManager();
final ServerConnectionList connectionList = context.mock(ServerConnectionList.class);
final NetworkTableEntry entry1 = context.mock(NetworkTableEntry.class, "entry1");
final NetworkTableEntry entry2 = context.mock(NetworkTableEntry.class, "entry2");
final NetworkTableEntry entry3 = context.mock(NetworkTableEntry.class, "entry3");
final AbstractNetworkTableEntryStore entryStore = context.mock(AbstractNetworkTableEntryStore.class);
WriteManager writeManager = new WriteManager(connectionList, threadManager, entryStore, Long.MAX_VALUE);
writeManager.start();
writeManager.offerOutgoingAssignment(entry1);
final Sequence writeSequence1 = context.sequence("writeSequence1");
context.checking(new Expectations() {{
oneOf(connectionList).offerOutgoingAssignment(entry1);inSequence(writeSequence1);
oneOf(connectionList).flush();inSequence(writeSequence1);
oneOf(entry1).makeClean();
}});
threadManager.getPeriodicThread(WriteManager.class).run();
context.assertIsSatisfied();
writeManager.offerOutgoingAssignment(entry2);
writeManager.offerOutgoingAssignment(entry3);
final Sequence writeSequence2 = context.sequence("writeSequence2");
context.checking(new Expectations() {{
oneOf(connectionList).offerOutgoingAssignment(entry2);inSequence(writeSequence2);
oneOf(connectionList).offerOutgoingAssignment(entry3);inSequence(writeSequence2);
oneOf(connectionList).flush();inSequence(writeSequence2);
oneOf(entry2).makeClean();
oneOf(entry3).makeClean();
}});
threadManager.getPeriodicThread(WriteManager.class).run();
}
@Test public void testClose() throws IOException {
final ServerConnectionList connectionList = context.mock(ServerConnectionList.class);
final NTThreadManager threadManager = context.mock(NTThreadManager.class);
final NTThread thread = context.mock(NTThread.class);
final AbstractNetworkTableEntryStore entryStore = context.mock(AbstractNetworkTableEntryStore.class);
context.checking(new Expectations() {{
oneOf(threadManager).newBlockingPeriodicThread(with(any(PeriodicRunnable.class)), with("Write Manager Thread"));will(returnValue(thread));
}});
WriteManager writeManager = new WriteManager(connectionList, threadManager, entryStore, Long.MAX_VALUE);
writeManager.start();
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(thread).stop();
}});
writeManager.stop();
}
}

View File

@@ -0,0 +1,59 @@
package edu.wpi.first.wpilibj.networktables2.stream;
import static org.junit.Assert.*;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
@RunWith(JMock.class)
public class SimpleIOStreamTest {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test
public void testSingleSocketConnection() throws IOException {
final InputStream is = context.mock(InputStream.class);
final OutputStream os = context.mock(OutputStream.class);
SimpleIOStream stream = new SimpleIOStream(is, os);
assertSame(is, stream.getInputStream());
assertSame(os, stream.getOutputStream());
context.checking(new Expectations() {{
oneOf(is).close();
oneOf(os).close();
}});
stream.close();
}
@Test
public void testExceptionsOnISClose() throws IOException {
final InputStream is = context.mock(InputStream.class);
final OutputStream os = context.mock(OutputStream.class);
SimpleIOStream stream = new SimpleIOStream(is, os);
context.checking(new Expectations() {{
oneOf(is).close();will(throwException(new IOException()));
oneOf(os).close();
}});
stream.close();
}
@Test
public void testExceptionsOnOSClose() throws IOException {
final InputStream is = context.mock(InputStream.class);
final OutputStream os = context.mock(OutputStream.class);
SimpleIOStream stream = new SimpleIOStream(is, os);
context.checking(new Expectations() {{
oneOf(is).close();
oneOf(os).close();will(throwException(new IOException()));
}});
stream.close();
}
}

View File

@@ -0,0 +1,88 @@
package edu.wpi.first.wpilibj.networktables2.stream;
import static org.junit.Assert.*;
import java.io.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.concurrent.*;
import org.junit.*;
import test.util.*;
public class SocketTest {
Mockery context = new JUnit4Mockery() {{
setThreadingPolicy(new Synchroniser());
}};
@Test(timeout=1000)
public void testSingleSocketConnection() throws Throwable {
doSocketTest(1, 500, 1000, SocketStreams.newStreamProvider(10111), SocketStreams.newStreamFactory("localhost", 10111));
}
@Test(timeout=2500)
public void testManySocketConnection() throws Throwable {
doSocketTest(10, 500, 2000, SocketStreams.newStreamProvider(10112), SocketStreams.newStreamFactory("localhost", 10112));
}
private void doSocketTest(final int count, long threadTimeout, long testTimeout, final IOStreamProvider streamProvider, final IOStreamFactory factory) throws Throwable {
TestExecutor executor = new TestExecutor(count+1, threadTimeout);
final AtomicInteger clientCount = new AtomicInteger(0);
final AtomicInteger serverCount = new AtomicInteger(0);
for(int i = 0; i<count; ++i){
executor.execute(new Runnable() {
@Override
public void run() {
try{
IOStream clientStream = factory.createStream();
PrintWriter output = new PrintWriter(clientStream.getOutputStream());
output.println("FromClient");
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(clientStream.getInputStream()));
assertEquals("FromServer", input.readLine());
clientStream.close();
clientCount.incrementAndGet();
} catch(IOException e){
e.printStackTrace();
}
}
});
}
executor.execute(new Runnable() {
@Override
public void run() {
try{
while(serverCount.get()!=count){
IOStream serverStream = streamProvider.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(serverStream.getInputStream()));
assertEquals("FromClient", input.readLine());
PrintWriter output = new PrintWriter(serverStream.getOutputStream());
output.println("FromServer");
output.flush();
serverStream.close();
serverCount.incrementAndGet();
}
streamProvider.close();
} catch(IOException e){
e.printStackTrace();
}
}
});
executor.await(testTimeout, TimeUnit.MILLISECONDS);
assertEquals("server count", count, serverCount.get());
assertEquals("client count", count, clientCount.get());
}
}

View File

@@ -0,0 +1,206 @@
package edu.wpi.first.wpilibj.networktables2.system;
import edu.wpi.first.testing.*;
import edu.wpi.first.wpilibj.networktables2.client.*;
import edu.wpi.first.wpilibj.networktables2.stream.*;
import edu.wpi.first.wpilibj.tables.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import org.junit.*;
import static org.junit.Assert.*;
import org.junit.runner.*;
@RunWith(sUnitTestRunner.class)
public class SystemTest {
@Test
public void testSimpleBidirectionalPut() throws Exception{
sUnitTestRunner.server.waitMessage();//Server Up
IOStreamFactory streamFactory = SocketStreams.newStreamFactory("10.1.90.2", 1735);
NetworkTableClient client = new NetworkTableClient(streamFactory);
client.reconnect();
Thread.sleep(500);
sUnitTestRunner.server.sendMessage("client connected");
client.putString("ClientString1", "CValue1-1");
client.putString("ClientString2", "CValue2-1");
sUnitTestRunner.server.waitMessage();//Server sent
Thread.sleep(100);
assertEquals("SValue1-1", client.getString("ServerString1"));
assertEquals("SValue2-1", client.getString("ServerString2"));
client.putString("ClientString1", "CValue1-2");
client.putString("ClientString2", "CValue2-2");
sUnitTestRunner.server.sendMessage("client sent");
sUnitTestRunner.server.waitMessage();//Server sent
Thread.sleep(100);
assertEquals("SValue1-2", client.getString("ServerString1"));
assertEquals("SValue2-2", client.getString("ServerString2"));
client.stop();
sUnitTestRunner.server.sendMessage("test complete");
}
@Test
public void testRapidServerPutSingleKey() throws Exception{
sUnitTestRunner.server.waitMessage();//Server Up
IOStreamFactory streamFactory = SocketStreams.newStreamFactory("10.1.90.2", 1735);
NetworkTableClient client = new NetworkTableClient(streamFactory);
client.reconnect();
Thread.sleep(100);
sUnitTestRunner.server.sendMessage("client connected");
sUnitTestRunner.server.waitMessage();//Server done
assertEquals("SValue9999", client.getString("ServerKey"));
client.stop();
sUnitTestRunner.server.sendMessage("test complete");
}
@Test
public void testRapidServerPutMultiKey() throws Exception{
sUnitTestRunner.server.waitMessage();//Server Up
IOStreamFactory streamFactory = SocketStreams.newStreamFactory("10.1.90.2", 1735);
NetworkTableClient client = new NetworkTableClient(streamFactory);
client.reconnect();
Thread.sleep(100);
sUnitTestRunner.server.sendMessage("client connected");
sUnitTestRunner.server.waitMessage();//Server done
client.stop();
for(int i = 0; i<100; ++i)
assertEquals("SValue999", client.getString("ServerKey"+i));
sUnitTestRunner.server.sendMessage("test complete");
}
@Test
public void testPeriodicServerPutMultiKey() throws Exception{
sUnitTestRunner.server.waitMessage();//Server Up
IOStreamFactory streamFactory = SocketStreams.newStreamFactory("10.1.90.2", 1735);
NetworkTableClient client = new NetworkTableClient(streamFactory);
client.reconnect();
Thread.sleep(100);
sUnitTestRunner.server.sendMessage("client connected");
sUnitTestRunner.server.waitMessage();//Server done
client.stop();
for(int i = 0; i<100; ++i)
assertEquals("SValue99", client.getString("ServerKey"+i));
sUnitTestRunner.server.sendMessage("test complete");
}
@Test
public void testBiDirectionalStress() throws Exception {
sUnitTestRunner.server.waitMessage(); // Server up
IOStreamFactory streamFactory = SocketStreams.newStreamFactory("10.1.90.2", 1735);
NetworkTableClient client = new NetworkTableClient(streamFactory);
client.reconnect();
Thread.sleep(100);
sUnitTestRunner.server.sendMessage("Client connected");
Map<String, Double> valueRecord = new HashMap<String, Double>();
// Add and send 1 million values
try {
// Seed the RNG from a build property; otherwise, generate a random seed
final String seedPropertyName = "edu.wpi.first.wpilibj.test.randomSeed";
String seedStr = System.getProperty(seedPropertyName);
boolean seedLoaded = false;
Random rand;
long seed;
if(seedStr != null) {
seed = Long.parseLong(seedStr);
System.out.println("Seed loaded from property '" + seedPropertyName + "'");
seedLoaded = true;
} else {
System.out.println("Property '" + seedPropertyName + "' not set; generating random seed");
Random seedRand = new Random();
seed = seedRand.nextLong();
}
System.out.println("Using seed: "+ seed);
rand = new Random(seed);
// Write values to the robot; try 10000 runs
System.out.println("Writing values to the robot...");
for(int i = 0; i < 10000; i++) {
// Pick a random name out of ascii characters
int nameLen = rand.nextInt(99) + 1;
StringBuilder sb = new StringBuilder(nameLen);
for(int j = 0; j < nameLen; j++) {
// Pick a random human-readable ascii character
int c = rand.nextInt(94) + 32;
sb.append((char) c);
}
// Pick a value to send from the range of +/- Double.MAX_VALUE
double value = rand.nextDouble() * Double.MAX_VALUE;
if(!rand.nextBoolean())
value *= -1;
// If a seed was specified (i.e. we are probably debugging),
// print out the value sequence
if(seedLoaded) {
System.out.println(String.format("Setting %s to value %f", sb.toString(), value));
}
valueRecord.put(sb.toString(), value);
client.putDouble("/client/" + sb.toString(), value);
Thread.sleep(rand.nextInt(19) + 1);
}
System.out.println("Waiting for 10 seconds...");
Thread.sleep(10000);
List<String> incorrectEntries = new LinkedList<String>();
// Compare the current value of every entry with the expected value
for(Entry<String, Double> e : valueRecord.entrySet()) {
try {
Double d = client.getDouble("/server/" + e.getKey());
if(!e.getValue().equals(d))
incorrectEntries.add(e.getKey());
} catch (TableKeyNotDefinedException tknde) {
incorrectEntries.add(e.getKey());
}
}
// Note any/all failures
if(incorrectEntries.size() > 0) {
for(String s : incorrectEntries) {
try {
Double d = client.getDouble("/server/" + s);
System.err.println(String.format("For key '%s' expected %f, got %f", s, valueRecord.get(s), d));
} catch (TableKeyNotDefinedException tknde) {
System.err.println(String.format("No key %s; expected %f", s, valueRecord.get(s)));
}
}
fail("Server namespace in network tables never became consistent with expected values");
}
sUnitTestRunner.server.sendMessage("Test complete");
} catch(Exception e) {
sUnitTestRunner.server.sendMessage("Test complete (exception occurred)");
throw e;
}
}
}

View File

@@ -0,0 +1,96 @@
package edu.wpi.first.wpilibj.networktables2.thread;
import static org.junit.Assert.*;
import java.io.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.junit.*;
public class DefaultThreadManagerTest {
volatile Throwable exception = null;
@Test(timeout=300)
public void testConcurrentThreads() throws Throwable {
final int numCounts = 10;
final int numThreads = 10;
final CyclicBarrier barrier = new CyclicBarrier(numThreads);
final CountDownLatch ranNotification = new CountDownLatch(numThreads*numCounts);
DefaultThreadManager threadManager = new DefaultThreadManager();
NTThread[] threads = new NTThread[numThreads];
for(int i = 0; i<numThreads; ++i)
threads[i] = threadManager.newBlockingPeriodicThread(new PeriodicRunnable(){
@Override
public void run() throws InterruptedException {
try {
barrier.await();
} catch (BrokenBarrierException e) {
throw new InterruptedException();
}
ranNotification.countDown();
}
}, "Test thread "+i);
try {
ranNotification.await();
for(int i = 0; i<numThreads; ++i)
threads[i].stop();
Thread.sleep(100);//Wait for threads to terminate
for(int i = 0; i<numThreads; ++i)
assertFalse(threads[i].isRunning());
} catch (InterruptedException e) {
fail("interrupted while waiting");
}
if(exception!=null)
throw exception;
}
volatile boolean threadInterrupted = false;
@Test(timeout=300)
public void testStopThread() throws IOException {
DefaultThreadManager threadManager = new DefaultThreadManager();
NTThread thread = threadManager.newBlockingPeriodicThread(new PeriodicRunnable(){
@Override
public void run() throws InterruptedException {
Thread.sleep(1000);
}
}, "A Test Thread");
try {
Thread.sleep(100);
thread.stop();
Thread.sleep(100);//wait for thread to stop
assertFalse(thread.isRunning());
} catch (InterruptedException e) {
fail("interrupted while waiting");
}
}
@Test(timeout=2000)
public void testPeriodicThread() throws IOException {
final CountDownLatch countDown = new CountDownLatch(10);
final AtomicInteger afterFinishCount = new AtomicInteger(0);
DefaultThreadManager threadManager = new DefaultThreadManager();
NTThread thread = threadManager.newBlockingPeriodicThread(new PeriodicRunnable(){
@Override
public void run() throws InterruptedException {
Thread.sleep(50);
if(countDown.getCount()==0)
afterFinishCount.incrementAndGet();
else
countDown.countDown();
}
}, "A test thread");
try {
countDown.await();
thread.stop();
Thread.sleep(100);//wait for thread to stop
assertFalse(thread.isRunning());
assertTrue(afterFinishCount.get()<=1);//make sure the periodic calls stopped
} catch (InterruptedException e) {
fail("interrupted while waiting");
}
}
}

View File

@@ -0,0 +1,426 @@
package edu.wpi.first.wpilibj.networktables2.type;
import edu.wpi.first.wpilibj.networktables2.TableKeyExistsWithDifferentTypeException;
import static org.junit.Assert.*;
import java.io.*;
import org.jmock.*;
import org.jmock.integration.junit4.*;
import org.jmock.lib.legacy.*;
import org.junit.*;
import org.junit.runner.*;
import test.util.*;
import edu.wpi.first.wpilibj.networktables2.client.*;
import edu.wpi.first.wpilibj.networktables2.server.*;
import edu.wpi.first.wpilibj.tables.*;
/**
*
* @author Mitchell
*/
@RunWith(JMock.class)
public class ArrayTypeTest {
Mockery context = new JUnit4Mockery(){{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test
public void testPutArrayValue() throws Exception{
NetworkTableTestNode node = new NetworkTableTestNode();
final NetworkTableEntryType type = context.mock(NetworkTableEntryType.class);
final ArrayEntryType arrayType = new ArrayEntryType((byte)10, type, ArrayData.class);
final ArrayData data = new ArrayData(arrayType);
data.setSize(9);
final Object value1 = new Object();
final Object value2 = new Object();
data._set(0, value1);
data._set(1, value2);
node.putValue("MyKey", data);
Object[] internalValue = (Object[])node.getValue("MyKey");
assertEquals(9, internalValue.length);
assertSame(internalValue[0], value1);
assertSame(internalValue[1], value2);
for(int i = 2; i<9; ++i)
assertNull(internalValue[i]);
data._set(0, value2);
data._set(1, value1);
Object[] internalValue2 = (Object[])node.getValue("MyKey");
assertSame(internalValue, internalValue2);
assertEquals(9, internalValue2.length);
assertSame(internalValue2[0], value1);
assertSame(internalValue2[1], value2);
for(int i = 2; i<9; ++i)
assertNull(internalValue2[i]);
node.putValue("MyKey", data);
Object[] internalValue3 = (Object[])node.getValue("MyKey");
assertSame(internalValue2, internalValue3);
assertEquals(9, internalValue3.length);
assertSame(internalValue3[0], value2);
assertSame(internalValue3[1], value1);
for(int i = 2; i<9; ++i)
assertNull(internalValue3[i]);
data.setSize(4);
data._set(0, value1);
data._set(1, value2);
data._set(2, value2);
data._set(3, value1);
Object[] internalValue4 = (Object[])node.getValue("MyKey");
assertSame(internalValue3, internalValue4);
assertEquals(9, internalValue4.length);
assertSame(internalValue4[0], value2);
assertSame(internalValue4[1], value1);
for(int i = 2; i<9; ++i)
assertNull(internalValue4[i]);
node.putValue("MyKey", data);
Object[] internalValue5 = (Object[])node.getValue("MyKey");
assertNotSame(internalValue4, internalValue5);
assertEquals(4, internalValue5.length);
assertSame(internalValue5[0], value1);
assertSame(internalValue5[1], value2);
assertSame(internalValue5[2], value2);
assertSame(internalValue5[3], value1);
}
@Test
public void testRetrieveArrayValue() throws Exception{
NetworkTableTestNode node = new NetworkTableTestNode();
final NetworkTableEntryType type = context.mock(NetworkTableEntryType.class);
final ArrayEntryType arrayType = new ArrayEntryType((byte)10, type, ArrayData.class);
final ArrayData data = new ArrayData(arrayType);
data.setSize(4);
final Object value1 = new Object();
final Object value2 = new Object();
final Object value3 = new Object();
final Object value4 = new Object();
data._set(0, value1);
data._set(1, value2);
data._set(2, value3);
data._set(3, value4);
node.putValue("MyKey", data);
final ArrayData targetData = new ArrayData(arrayType);
node.retrieveValue("MyKey", targetData);
assertEquals(4, targetData.size());
assertSame(targetData.getAsObject(0), value1);
assertSame(targetData.getAsObject(1), value2);
assertSame(targetData.getAsObject(2), value3);
assertSame(targetData.getAsObject(3), value4);
Object[] internalValue = (Object[])node.getValue("MyKey");
assertNotSame(internalValue, targetData.getDataArray());
targetData._set(0, value2);
targetData._set(1, value1);
Object[] internalValue2 = (Object[])node.getValue("MyKey");
assertSame(internalValue, internalValue2);
assertEquals(4, internalValue2.length);
assertSame(internalValue[0], value1);
assertSame(internalValue[1], value2);
assertSame(internalValue[2], value3);
assertSame(internalValue[3], value4);
}
@Test
public void testCreateWithNonArrayExternal(){
final NetworkTableEntryType elementType = context.mock(NetworkTableEntryType.class);
try{
new ArrayEntryType((byte)2, elementType, String.class);
fail();
} catch(Exception e){}
}
@Test
public void testInternalizeDifferentExternalType(){
final NetworkTableEntryType type = context.mock(NetworkTableEntryType.class);
final ArrayEntryType arrayType = new ArrayEntryType((byte)10, type, BooleanArray.class);
try{
arrayType.internalizeValue("MyKey", new ArrayData(arrayType), new Object[0]);
fail();
}
catch(TableKeyExistsWithDifferentTypeException e){
}
}
@Test
public void testExportDifferentExternalType(){
final NetworkTableEntryType type = context.mock(NetworkTableEntryType.class);
final ArrayEntryType arrayType = new ArrayEntryType((byte)10, type, BooleanArray.class);
try{
arrayType.exportValue("MyKey", new Object[0], new ArrayData(arrayType));
fail();
}
catch(TableKeyExistsWithDifferentTypeException e){
}
}
@Test
public void testExportDifferentInternalType(){
final NetworkTableEntryType type = context.mock(NetworkTableEntryType.class);
final ArrayEntryType arrayType = new ArrayEntryType((byte)10, type, BooleanArray.class);
try{
arrayType.exportValue("MyKey", new boolean[0], new BooleanArray());
fail();
}
catch(TableKeyExistsWithDifferentTypeException e){
}
}
/*
* Boolean
*/
@Test
public void testSendBooleanArray(){
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
BooleanArray.TYPE.sendValue(new Object[]{true, false, true, true}, new DataOutputStream(output));
assertArrayEquals(new byte[]{4, 1, 0, 1, 1}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
BooleanArray.TYPE.sendValue(new Object[]{false, true, true, true, false, false, false, true}, new DataOutputStream(output));
assertArrayEquals(new byte[]{8, 0, 1, 1, 1, 0, 0, 0, 1}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
BooleanArray.TYPE.sendValue(new Object[1000], new DataOutputStream(output));
fail();
} catch (IOException e) {}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
BooleanArray.TYPE.sendValue(new Object(), new DataOutputStream(output));
fail();
} catch (IOException e) {}
}
@Test
public void testReadBooleanArray() {
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{4, 0, 1, 1, 0});
assertArrayEquals(new Object[]{false, true, true, false}, (Object[])BooleanArray.TYPE.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{9, 0, 1, 1, 1, 0, 0, 1, 1, 1});
assertArrayEquals(new Object[]{false, true, true, true, false, false, true, true, true}, (Object[])BooleanArray.TYPE.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
}
@Test
public void testReadWriteBooleanArray() throws Exception{
StreamPipeProvider streamProvider = new StreamPipeProvider();
NetworkTableServer server = new NetworkTableServer(streamProvider);
NetworkTableClient client = new NetworkTableClient(streamProvider.getFactory());
final BooleanArray data = new BooleanArray();
data.setSize(4);
data.set(0, true);
data.set(1, false);
data.set(2, false);
data.set(3, true);
server.putValue("MyKey", data);
Thread.sleep(1500);
final BooleanArray targetData = new BooleanArray();
client.retrieveValue("MyKey", targetData);
assertEquals(4, targetData.size());
assertEquals(targetData.get(0), true);
assertEquals(targetData.get(1), false);
assertEquals(targetData.get(2), false);
assertEquals(targetData.get(3), true);
client.stop();
server.close();
}
/*
* Double
*/
@Test
public void testSendNumberArray(){
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
NumberArray.TYPE.sendValue(new Object[]{new Double(10), new Double(20), new Double(200.3), new Double(-1.3)}, new DataOutputStream(output));
assertArrayEquals(new byte[]{4, 64, 36, 0, 0, 0, 0, 0, 0, 64, 52, 0, 0, 0, 0, 0, 0, 64, 105, 9, -103, -103, -103, -103, -102, -65, -12, -52, -52, -52, -52, -52, -51}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
NumberArray.TYPE.sendValue(new Object[]{new Double(10), new Double(20), new Double(200.3), new Double(-1.3), new Double(11), new Double(-3.3), new Double(11), new Double(66.2)}, new DataOutputStream(output));
assertArrayEquals(new byte[]{8, 64, 36, 0, 0, 0, 0, 0, 0, 64, 52, 0, 0, 0, 0, 0, 0, 64, 105, 9, -103, -103, -103, -103, -102, -65, -12, -52, -52, -52, -52, -52, -51, 64, 38, 0, 0, 0, 0, 0, 0, -64, 10, 102, 102, 102, 102, 102, 102, 64, 38, 0, 0, 0, 0, 0, 0, 64, 80, -116, -52, -52, -52, -52, -51}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
NumberArray.TYPE.sendValue(new Object[1000], new DataOutputStream(output));
fail();
} catch (IOException e) {}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
NumberArray.TYPE.sendValue(new Object(), new DataOutputStream(output));
fail();
} catch (IOException e) {}
}
@Test
public void testReadNumberArray() {
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{4, 64, 36, 0, 0, 0, 0, 0, 0, 64, 52, 0, 0, 0, 0, 0, 0, 64, 105, 9, -103, -103, -103, -103, -102, -65, -12, -52, -52, -52, -52, -52, -51});
assertArrayEquals(new Object[]{new Double(10), new Double(20), new Double(200.3), new Double(-1.3)}, (Object[])NumberArray.TYPE.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{8, 64, 36, 0, 0, 0, 0, 0, 0, 64, 52, 0, 0, 0, 0, 0, 0, 64, 105, 9, -103, -103, -103, -103, -102, -65, -12, -52, -52, -52, -52, -52, -51, 64, 38, 0, 0, 0, 0, 0, 0, -64, 10, 102, 102, 102, 102, 102, 102, 64, 38, 0, 0, 0, 0, 0, 0, 64, 80, -116, -52, -52, -52, -52, -51});
assertArrayEquals(new Object[]{new Double(10), new Double(20), new Double(200.3), new Double(-1.3), new Double(11), new Double(-3.3), new Double(11), new Double(66.2)}, (Object[])NumberArray.TYPE.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
}
@Test
public void testReadWriteNumberArray() throws Exception{
StreamPipeProvider streamProvider = new StreamPipeProvider();
NetworkTableServer server = new NetworkTableServer(streamProvider);
NetworkTableClient client = new NetworkTableClient(streamProvider.getFactory());
final NumberArray data = new NumberArray();
data.setSize(4);
data.set(0, 10.4);
data.set(1, 44.3);
data.set(2, 33.4);
data.set(3, 233);
server.putValue("MyKey", data);
Thread.sleep(1500);
final NumberArray targetData = new NumberArray();
client.retrieveValue("MyKey", targetData);
assertEquals(4, targetData.size());
assertEquals(targetData.get(0), 10.4, 0);
assertEquals(targetData.get(1), 44.3, 0);
assertEquals(targetData.get(2), 33.4, 0);
assertEquals(targetData.get(3), 233, 0);
client.stop();
server.close();
}
/*
* String
*/
@Test
public void testSendStringArray(){
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
StringArray.TYPE.sendValue(new Object[]{"HI", "", "HELlO", "--asdf"}, new DataOutputStream(output));
assertArrayEquals(new byte[]{4, 0, 2, 72, 73, 0, 0, 0, 5, 72, 69, 76, 108, 79, 0, 6, 45, 45, 97, 115, 100, 102}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
StringArray.TYPE.sendValue(new Object[]{"", "TEw4390", "00*&(&(*&*", "adsf", "asdfasdf", "asdfai888"}, new DataOutputStream(output));
assertArrayEquals(new byte[]{6, 0, 0, 0, 7, 84, 69, 119, 52, 51, 57, 48, 0, 10, 48, 48, 42, 38, 40, 38, 40, 42, 38, 42, 0, 4, 97, 100, 115, 102, 0, 8, 97, 115, 100, 102, 97, 115, 100, 102, 0, 9, 97, 115, 100, 102, 97, 105, 56, 56, 56}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
StringArray.TYPE.sendValue(new Object[1000], new DataOutputStream(output));
fail();
} catch (IOException e) {}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
StringArray.TYPE.sendValue(new Object(), new DataOutputStream(output));
fail();
} catch (IOException e) {}
}
@Test
public void testReadStringArray() {
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{4, 0, 2, 72, 73, 0, 0, 0, 5, 72, 69, 76, 108, 79, 0, 6, 45, 45, 97, 115, 100, 102});
assertArrayEquals(new Object[]{"HI", "", "HELlO", "--asdf"}, (Object[])StringArray.TYPE.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{6, 0, 0, 0, 7, 84, 69, 119, 52, 51, 57, 48, 0, 10, 48, 48, 42, 38, 40, 38, 40, 42, 38, 42, 0, 4, 97, 100, 115, 102, 0, 8, 97, 115, 100, 102, 97, 115, 100, 102, 0, 9, 97, 115, 100, 102, 97, 105, 56, 56, 56});
assertArrayEquals(new Object[]{"", "TEw4390", "00*&(&(*&*", "adsf", "asdfasdf", "asdfai888"}, (Object[])StringArray.TYPE.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
}
@Test
public void testReadWriteStringArray() throws Exception{
StreamPipeProvider streamProvider = new StreamPipeProvider();
NetworkTableServer server = new NetworkTableServer(streamProvider);
NetworkTableClient client = new NetworkTableClient(streamProvider.getFactory());
final StringArray data = new StringArray();
data.setSize(5);
data.set(0, "HI");
data.set(1, "ehllos");
data.set(2, "sdf-9889");
data.set(3, "hi-----");
data.set(4, "sfdasdfasdfasdfasf");
server.putValue("MyKey", data);
Thread.sleep(1500);
final StringArray targetData = new StringArray();
client.retrieveValue("MyKey", targetData);
assertEquals(5, targetData.size());
assertEquals(targetData.get(0), "HI");
assertEquals(targetData.get(1), "ehllos");
assertEquals(targetData.get(2), "sdf-9889");
assertEquals(targetData.get(3), "hi-----");
assertEquals(targetData.get(4), "sfdasdfasdfasdfasf");
client.stop();
server.close();
}
}

View File

@@ -0,0 +1,95 @@
package edu.wpi.first.wpilibj.networktables2.type;
import edu.wpi.first.wpilibj.networktables2.TableKeyExistsWithDifferentTypeException;
import edu.wpi.first.wpilibj.tables.TableKeyNotDefinedException;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import test.util.NetworkTableTestNode;
/**
*
* @author Mitchell
*/
@RunWith(JMock.class)
public class ComplexTypeTest {
Mockery context = new JUnit4Mockery(){{
setImposteriser(ClassImposteriser.INSTANCE);
}};
@Test
public void testPutComplexValue() throws Exception{
NetworkTableTestNode node = new NetworkTableTestNode();
final ComplexEntryType dataType = context.mock(ComplexEntryType.class);
final ComplexData data1 = context.mock(ComplexData.class, "data1");
final Object value1 = new Object();
final ComplexData data2 = context.mock(ComplexData.class, "data2");
final Object value2 = new Object();
context.checking(new Expectations() {{
allowing(data1).getType();will(returnValue(dataType));
oneOf(dataType).internalizeValue("MyKey", data1, null);will(returnValue(value1));
}});
node.putValue("MyKey", data1);
assertSame(value1, node.getValue("MyKey"));
context.assertIsSatisfied();
context.checking(new Expectations() {{
allowing(data2).getType();will(returnValue(dataType));
oneOf(dataType).internalizeValue("MyKey", data2, value1);will(returnValue(value2));
}});
node.putValue("MyKey", data2);
assertSame(value2, node.getValue("MyKey"));
context.assertIsSatisfied();
}
@Test
public void testRetrieveComplexValue() throws Exception{
NetworkTableTestNode node = new NetworkTableTestNode();
final ComplexEntryType dataType = context.mock(ComplexEntryType.class);
final ComplexData data = context.mock(ComplexData.class, "data");
final Object value = new Object();
context.checking(new Expectations() {{
oneOf(dataType).internalizeValue("MyKey", value, null);will(returnValue(value));
}});
node.putValue("MyKey", dataType, value);
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(dataType).exportValue("MyKey", value, data);
}});
node.retrieveValue("MyKey", data);
}
@Test
public void testRetrieveNonExistantValue(){
NetworkTableTestNode node = new NetworkTableTestNode();
final ComplexData data = context.mock(ComplexData.class, "data");
try{
node.retrieveValue("MyKey", data);
fail();
} catch(TableKeyNotDefinedException e){}
}
@Test
public void testRetrieveNonComplexValue() throws Exception{
NetworkTableTestNode node = new NetworkTableTestNode();
final ComplexData data = context.mock(ComplexData.class, "data");
node.putString("MyKey", "SomeValue");
try{
node.retrieveValue("MyKey", data);
fail();
} catch(TableKeyExistsWithDifferentTypeException e){}
}
}

View File

@@ -0,0 +1,191 @@
package edu.wpi.first.wpilibj.networktables2.type;
import static org.junit.Assert.*;
import java.io.*;
import org.junit.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
public class EntryTypeTest {
@Test
public void testIdToType() {
assertSame(DefaultEntryTypes.BOOLEAN, new NetworkTableEntryTypeManager().getType((byte)0));
assertSame(DefaultEntryTypes.DOUBLE, new NetworkTableEntryTypeManager().getType((byte)1));
assertSame(DefaultEntryTypes.STRING, new NetworkTableEntryTypeManager().getType((byte)2));
assertNull(new NetworkTableEntryTypeManager().getType((byte)3));
assertNull(new NetworkTableEntryTypeManager().getType((byte)4));
assertNull(new NetworkTableEntryTypeManager().getType((byte)5));
assertNull(new NetworkTableEntryTypeManager().getType((byte)127));
assertNull(new NetworkTableEntryTypeManager().getType((byte)-1));
}
@Test
public void testTypeIds() {
assertEquals(0, DefaultEntryTypes.BOOLEAN.id);
assertEquals(1, DefaultEntryTypes.DOUBLE.id);
assertEquals(2, DefaultEntryTypes.STRING.id);
}
@Test
public void testTypeNames() {
assertEquals("Boolean", DefaultEntryTypes.BOOLEAN.name);
assertEquals("Double", DefaultEntryTypes.DOUBLE.name);
assertEquals("String", DefaultEntryTypes.STRING.name);
}
@Test
public void testTypeToString() {
assertEquals("NetworkTable type: Boolean", DefaultEntryTypes.BOOLEAN.toString());
assertEquals("NetworkTable type: Double", DefaultEntryTypes.DOUBLE.toString());
assertEquals("NetworkTable type: String", DefaultEntryTypes.STRING.toString());
}
@Test
public void testBooleanRead() {
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{0});
assertEquals(false, DefaultEntryTypes.BOOLEAN.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{1});
assertEquals(true, DefaultEntryTypes.BOOLEAN.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[0]);
assertEquals(false, DefaultEntryTypes.BOOLEAN.readValue(new DataInputStream(input)));
fail();
} catch (IOException e) {}
}
@Test
public void testBooleanWrite() {
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DefaultEntryTypes.BOOLEAN.sendValue(false, new DataOutputStream(output));
assertArrayEquals(new byte[]{0}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DefaultEntryTypes.BOOLEAN.sendValue(true, new DataOutputStream(output));
assertArrayEquals(new byte[]{1}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DefaultEntryTypes.BOOLEAN.sendValue(new Object(), new DataOutputStream(output));
fail();
} catch (IOException e) {}
}
@Test
public void testDoubleRead() {
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{64, 41, 0, 0, 0, 0, 0, 0});
assertEquals(12.5, DefaultEntryTypes.DOUBLE.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{64, 100, 0, 0, 0, 0, 0, 0});
assertEquals(160.0, DefaultEntryTypes.DOUBLE.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[0]);
assertEquals(false, DefaultEntryTypes.DOUBLE.readValue(new DataInputStream(input)));
fail();
} catch (IOException e) {}
}
@Test
public void testDoubleWrite() {
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DefaultEntryTypes.DOUBLE.sendValue(12.5, new DataOutputStream(output));
assertArrayEquals(new byte[]{64, 41, 0, 0, 0, 0, 0, 0}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DefaultEntryTypes.DOUBLE.sendValue(160.0, new DataOutputStream(output));
assertArrayEquals(new byte[]{64, 100, 0, 0, 0, 0, 0, 0}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DefaultEntryTypes.DOUBLE.sendValue(new Object(), new DataOutputStream(output));
fail();
} catch (IOException e) {}
}
@Test
public void testStringRead() {
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{0, 8, 77, 121, 32, 69, 110, 116, 114, 121});
assertEquals("My Entry", DefaultEntryTypes.STRING.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[]{0, 5, 86, 97, 76, 117, 69});
assertEquals("VaLuE", DefaultEntryTypes.STRING.readValue(new DataInputStream(input)));
} catch (IOException e) {
fail();
}
try {
ByteArrayInputStream input = new ByteArrayInputStream(new byte[0]);
assertEquals(false, DefaultEntryTypes.STRING.readValue(new DataInputStream(input)));
fail();
} catch (IOException e) {}
}
@Test
public void testStringWrite() {
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DefaultEntryTypes.STRING.sendValue("My Entry", new DataOutputStream(output));
assertArrayEquals(new byte[]{0, 8, 77, 121, 32, 69, 110, 116, 114, 121}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DefaultEntryTypes.STRING.sendValue("VaLuE", new DataOutputStream(output));
assertArrayEquals(new byte[]{0, 5, 86, 97, 76, 117, 69}, output.toByteArray());
} catch (IOException e) {
fail();
}
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DefaultEntryTypes.STRING.sendValue(new Object(), new DataOutputStream(output));
fail();
} catch (IOException e) {}
}
}

View File

@@ -0,0 +1,226 @@
package edu.wpi.first.wpilibj.networktables2.util;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.hamcrest.*;
import org.junit.*;
/**
* @author mwills
* @author Fred
*/
public class ListTest {
@Test
public void testIsEmpty() {
List list = new List();
assertThat(list, isEmpty());
list.add(new Integer(42));
assertThat(list, not(isEmpty()));
}
@Test
public void testSize() {
List list = new List();
assertThat(list, isEmpty());
for (int i = 0; i < 42; i++) {
list.add(new Integer(i));
assertThat(list, hasSize(i+1));
}
}
@Test
public void testSizeGrowth() {
List list = new List(10);
assertThat(list, isEmpty());
for (int i = 0; i < 100; i++) {
list.add(new Integer(i));
}
for (int i = 0; i < 100; i++) {
assertThat(list, hasItem(i, equalTo(new Integer(i))));
}
}
@Test
public void testContains() {
List list = new List();
Integer testInt1 = new Integer(42);
Integer testInt2 = new Integer(43);
assertThat(list, not(contains(testInt1)));
list.add(testInt1);
assertThat(list, contains(testInt1));
assertThat(list, not(contains(testInt2)));
list.add(testInt2);
assertThat(list, contains(testInt2));
}
@Test
public void testAddRemoveObject() {
List list = new List();
Integer testInt1 = new Integer(42);
Integer testInt2 = new Integer(43);
Integer testInt3 = new Integer(44);
list.add(testInt1);
list.add(testInt2);
list.add(testInt3);
assertThat(list, contains(testInt1));
assertThat(list, contains(testInt2));
assertThat(list, contains(testInt3));
assertThat(list, hasSize(3));
list.remove(testInt1);
list.remove(testInt2);
list.remove(testInt3);
assertThat(list, not(contains(testInt1)));
assertThat(list, not(contains(testInt2)));
assertThat(list, not(contains(testInt3)));
}
@Test
public void testAddRemoveIndex() {
List list = new List();
Integer testInt1 = new Integer(42);
Integer testInt2 = new Integer(43);
Integer testInt3 = new Integer(44);
list.add(testInt1);
list.add(testInt2);
list.add(testInt3);
assertThat(list, hasItem(0, equalTo(testInt1)));
assertThat(list, hasItem(1, equalTo(testInt2)));
assertThat(list, hasItem(2, equalTo(testInt3)));
assertThat(list, hasSize(3));
list.remove(2);
list.remove(1);
list.remove(0);
assertThat(list, isEmpty());
}
@Test
public void testClear() {
List list = new List();
Integer testInt1 = new Integer(42);
Integer testInt2 = new Integer(43);
Integer testInt3 = new Integer(44);
list.add(testInt1);
list.add(testInt2);
list.add(testInt3);
assertThat(list, not(isEmpty()));
list.clear();
assertTrue(list.isEmpty());
}
@Test
public void testOrdering(){
Integer obj1 = new Integer(42);
Boolean obj2 = new Boolean(false);
Double obj3 = new Double(42.42);
List list = new List();
list.add(obj1);
list.add(obj2);
list.add(obj3);
assertThat(list, hasItem(0, equalTo(obj1)));
assertThat(list, hasItem(1, equalTo(obj2)));
assertThat(list, hasItem(2, equalTo(obj3)));
list.remove(obj2);
assertThat(list, hasItem(0, equalTo(obj1)));
assertThat(list, hasItem(1, equalTo(obj3)));
}
@Test
public void testSet(){
Integer obj1 = new Integer(42);
Boolean obj2 = new Boolean(false);
Double obj3 = new Double(42.42);
String obj4 = "MyString";
String obj5 = "MyString2";
String obj6 = "MyString3";
List list = new List();
list.add(obj1);
list.add(obj2);
list.add(obj3);
assertThat(list, hasItem(0, equalTo(obj1)));
assertThat(list, hasItem(1, equalTo(obj2)));
assertThat(list, hasItem(2, equalTo(obj3)));
list.set(1, obj4);
assertThat(list, hasItem(0, equalTo(obj1)));
assertThat(list, hasItem(1, equalTo(obj4)));
assertThat(list, hasItem(2, equalTo(obj3)));
assertThat(list, hasSize(3));
list.set(2, obj5);
assertThat(list, hasItem(0, equalTo(obj1)));
assertThat(list, hasItem(1, equalTo(obj4)));
assertThat(list, hasItem(2, equalTo(obj5)));
assertThat(list, hasSize(3));
list.set(0, obj6);
assertThat(list, hasItem(0, equalTo(obj6)));
assertThat(list, hasItem(1, equalTo(obj4)));
assertThat(list, hasItem(2, equalTo(obj5)));
assertThat(list, hasSize(3));
}
public Matcher<List> contains(final Object object){
return new TypeSafeMatcher<List>(){
@Override
public void describeTo(Description description) {
description.appendText("contains ").appendValue(object);
}
@Override
public boolean matchesSafely(List item) {
return item.contains(object);
}
};
}
public Matcher<List> isEmpty(){
return new TypeSafeMatcher<List>(){
@Override
public void describeTo(Description description) {
description.appendText("is empty");
}
@Override
public boolean matchesSafely(List item) {
return item.isEmpty();
}
};
}
public Matcher<List> hasSize(final int size){
return new TypeSafeMatcher<List>(){
@Override
public void describeTo(Description description) {
description.appendText("has size ").appendValue(size);
}
@Override
public boolean matchesSafely(List item) {
return item.size()==size;
}
};
}
public Matcher<List> hasItem(final int index, final Matcher<?> matcher){
return new TypeSafeMatcher<List>(){
@Override
public void describeTo(Description description) {
description.appendText("has ").appendDescriptionOf(matcher).appendText(" at index ").appendValue(index);
}
@Override
public boolean matchesSafely(List item) {
return matcher.matches(item.get(index));
}
};
}
}

View File

@@ -0,0 +1,102 @@
package edu.wpi.first.wpilibj.networktables2.util;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.hamcrest.*;
import org.junit.*;
/**
* @author mwills
* @author Fred
*/
public class StackTest {
@Test
public void pushTest(){
Integer obj1 = new Integer(0);
Stack stack = new Stack();
assertThat(stack, isEmpty());
stack.push(obj1);
assertThat(stack, not(isEmpty()));
}
@Test
public void popTest(){
Integer obj1 = new Integer(0);
Object obj2;
Stack stack = new Stack();
assertThat(stack, isEmpty());
obj2 = stack.pop();
assertNull(obj2);
stack.push(obj1);
obj2 = stack.pop();
assertSame(obj1, obj2);
assertThat(stack, isEmpty());
}
@Test
public void orderingTest(){
Integer obj1 = new Integer(42);
Integer obj2 = new Integer(43);
Integer obj3 = new Integer(44);
Object obj4;
Object obj5;
Object obj6;
Object obj7;
Stack stack = new Stack();
assertThat(stack, isEmpty());
stack.push(obj1);
assertThat(stack, hasSize(1));
stack.push(obj2);
stack.push(obj3);
assertThat(stack, hasSize(3));
obj4 = stack.pop();
assertThat(stack, hasSize(2));
obj5 = stack.pop();
obj6 = stack.pop();
assertSame(obj1, obj6);
assertSame(obj2, obj5);
assertSame(obj3, obj4);
stack.push(obj1);
stack.push(obj2);
stack.push(obj3);
stack.pop();
stack.push(obj1);
obj7 = stack.pop();
assertSame(obj1, obj7);
}
public Matcher<Stack> isEmpty(){
return new TypeSafeMatcher<Stack>(){
@Override
public void describeTo(Description description) {
description.appendText("is empty");
}
@Override
public boolean matchesSafely(Stack item) {
return item.isEmpty();
}
};
}
public Matcher<Stack> hasSize(final int size){
return new TypeSafeMatcher<Stack>(){
@Override
public void describeTo(Description description) {
description.appendText("has size ").appendValue(size);
}
@Override
public boolean matchesSafely(Stack item) {
return item.size()==size;
}
};
}
}

View File

@@ -0,0 +1,18 @@
package edu.wpi.first.wpilibj.tables;
import static org.junit.Assert.*;
import org.junit.*;
public class TableKeyNotDefinedExceptionTest {
@Test
public void throwExceptionTest(){
try {
throw new TableKeyNotDefinedException("Key 1");
} catch (TableKeyNotDefinedException e) {
assertEquals("Unkown Table Key: Key 1", e.getMessage());
}
}
}

View File

@@ -0,0 +1,46 @@
package test.util;
import java.io.*;
import edu.wpi.first.wpilibj.networktables2.stream.*;
public class ByteArrayStream implements IOStream {
private final ByteArrayOutputStream os;
private final ByteArrayInputStream is;
public ByteArrayStream() {
this(new byte[0]);
}
public ByteArrayStream(final byte[] inputData) {
this(new ByteArrayOutputStream(), new ByteArrayInputStream(inputData));
}
public ByteArrayStream(final ByteArrayOutputStream os, final byte[] inputData) {
this(os, new ByteArrayInputStream(inputData));
}
public ByteArrayStream(final ByteArrayOutputStream os, final ByteArrayInputStream is) {
this.is = is;
this.os = os;
}
public byte[] getOutput(){
return os.toByteArray();
}
public InputStream getInputStream() {
return is;
}
public OutputStream getOutputStream() {
return os;
}
public void close() {
try{
is.close();
} catch(IOException e){}
try {
os.close();
} catch (IOException e){}
}
}

View File

@@ -0,0 +1,43 @@
package test.util;
import java.io.*;
import java.util.*;
public class LoggingOutputStream extends OutputStream {
private final OutputStream backingStream;
private final ByteArrayOutputStream buffer;
public LoggingOutputStream(OutputStream backingStream){
this.backingStream = backingStream;
buffer = new ByteArrayOutputStream();
}
public void close() throws IOException {
backingStream.close();
System.out.println("Closed "+backingStream+" with "+Arrays.toString(buffer.toByteArray()));
buffer.reset();
}
public void flush() throws IOException {
backingStream.flush();
System.out.println("Wrote "+Arrays.toString(buffer.toByteArray())+" to "+backingStream);
buffer.reset();
}
public void write(byte[] b) throws IOException {
backingStream.write(b);
buffer.write(b);
}
public void write(byte[] b, int off, int len) throws IOException {
backingStream.write(b, off, len);
buffer.write(b, off, len);
}
public void write(int b) throws IOException {
backingStream.write(b);
buffer.write(b);
}
}

View File

@@ -0,0 +1,67 @@
package test.util;
import org.hamcrest.*;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.type.*;
public class NetworkTableEntryUtil {
public static NetworkTableEntry newBooleanEntry(final String name, final boolean value){
return new NetworkTableEntry(name, DefaultEntryTypes.BOOLEAN, new Boolean(value));
}
public static NetworkTableEntry newBooleanEntry(char id, String name, char sequenceNumber, boolean value){
return new NetworkTableEntry(id, name, sequenceNumber, DefaultEntryTypes.BOOLEAN, new Boolean(value));
}
public static NetworkTableEntry newDoubleEntry(String name, double value){
return new NetworkTableEntry(name, DefaultEntryTypes.DOUBLE, new Double(value));
}
public static NetworkTableEntry newDoubleEntry(char id, String name, char sequenceNumber, double value){
return new NetworkTableEntry(id, name, sequenceNumber, DefaultEntryTypes.DOUBLE, new Double(value));
}
public static NetworkTableEntry newStringEntry(String name, String value){
return new NetworkTableEntry(name, DefaultEntryTypes.STRING, value);
}
public static NetworkTableEntry newStringEntry(char id, String name, char sequenceNumber, String value){
return new NetworkTableEntry(id, name, sequenceNumber, DefaultEntryTypes.STRING, value);
}
public static Matcher<NetworkTableEntry> aBooleanEntry(final int id, final String name, final int sequenceNumber, final boolean value){
return aTableEntry((char)id, name, (char)sequenceNumber, DefaultEntryTypes.BOOLEAN, value);
}
public static Matcher<NetworkTableEntry> aDoubleEntry(final int id, final String name, final int sequenceNumber, final double value){
return aTableEntry((char)id, name, (char)sequenceNumber, DefaultEntryTypes.DOUBLE, value);
}
public static Matcher<NetworkTableEntry> aStringEntry(final int id, final String name, final int sequenceNumber, final String value){
return aTableEntry((char)id, name, (char)sequenceNumber, DefaultEntryTypes.STRING, value);
}
public static Matcher<NetworkTableEntry> aTableEntry(final char id, final String name, final char sequenceNumber, final NetworkTableEntryType type, final Object value){
return new TypeSafeMatcher<NetworkTableEntry>() {
@Override
public void describeTo(Description description) {
description.appendText(" a NetworkTableEntry with an id ").appendValue((int)id)
.appendText(" and name ").appendValue(name)
.appendText(" and sequence number ").appendValue((int)sequenceNumber)
.appendText(" and type ").appendValue(type)
.appendText(" and value ").appendValue(value);
}
@Override
protected boolean matchesSafely(NetworkTableEntry item) {
if(item.getId()!=id)
return false;
if(!item.name.equals(name))
return false;
if(item.getSequenceNumber()!=sequenceNumber)
return false;
if(!item.getType().equals(type))
return false;
if(!item.getValue().equals(value))
return false;
return true;
}
};
}
}

View File

@@ -0,0 +1,34 @@
package test.util;
import edu.wpi.first.wpilibj.networktables2.*;
import edu.wpi.first.wpilibj.networktables2.client.*;
/**
* @author Mitchell
*
*/
public class NetworkTableTestNode extends NetworkTableNode{
public NetworkTableTestNode(){
this(OutgoingEntryReceiver.NULL, OutgoingEntryReceiver.NULL);
}
public NetworkTableTestNode(OutgoingEntryReceiver incomingReceiver, OutgoingEntryReceiver outgoingReceiver){
init(new ClientNetworkTableEntryStore(this));
getEntryStore().setOutgoingReceiver(outgoingReceiver);
getEntryStore().setIncomingReceiver(incomingReceiver);
}
@Override
public void close() {
}
public boolean isConnected() {
return false;
}
public boolean isServer() {
return false;
}
}

View File

@@ -0,0 +1,74 @@
package test.util;
import java.io.*;
import java.util.concurrent.*;
import edu.wpi.first.wpilibj.networktables2.stream.*;
public class StreamPipeProvider implements IOStreamProvider{
private final StreamPipeFactory factory;
private boolean hasAccepted = false;
private final CountDownLatch closedLatch = new CountDownLatch(1);
public StreamPipeProvider(){
try {
factory = new StreamPipeFactory();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public IOStream accept() throws IOException {
if(!hasAccepted){
hasAccepted = true;
return factory.getServerStream();
}
try {
closedLatch.await();
} catch (InterruptedException e) {}
return null;
}
@Override
public void close() throws IOException {
closedLatch.countDown();
}
public StreamPipeFactory getFactory(){
return factory;
}
public class StreamPipeFactory implements IOStreamFactory{
private final PipedOutputStream serverOut;
private final PipedInputStream serverIn;
private final PipedOutputStream clientOut;
private final PipedInputStream clientIn;
private final IOStream serverStream;
private final IOStream clientStream;
public StreamPipeFactory() throws IOException {
clientIn = new PipedInputStream(serverOut = new PipedOutputStream());
serverIn = new PipedInputStream(clientOut = new PipedOutputStream());
serverStream = new SimpleIOStream(serverIn, serverOut);
clientStream = new SimpleIOStream(clientIn, clientOut);
}
public IOStream getServerStream(){
return serverStream;
}
public IOStream getClientStream(){
return clientStream;
}
@Override
public IOStream createStream() throws IOException {
return getClientStream();
}
}
}

View File

@@ -0,0 +1,40 @@
package test.util;
import java.util.concurrent.*;
public class TestExecutor implements Executor, ThreadFactory{
private ScheduledExecutorService executor;
private long threadTimeout;
private LinkedBlockingQueue<Throwable> exceptions = new LinkedBlockingQueue<Throwable>();
public TestExecutor(int numThreads, long threadTimeout) {
this.threadTimeout = threadTimeout;
executor = Executors.newScheduledThreadPool(numThreads, this);
}
@Override
public void execute(Runnable command) {
executor.schedule(command, threadTimeout, TimeUnit.MILLISECONDS);
}
@Override
public Thread newThread(final Runnable r) {
return new Thread(new Runnable(){
@Override
public void run() {
try{
r.run();
} catch(Throwable t){
exceptions.offer(t);
}
}
});
}
public void await(long timeout, TimeUnit unit) throws Throwable{
executor.shutdown();
executor.awaitTermination(timeout, unit);
Throwable firstError = exceptions.poll();
if(firstError!=null)
throw firstError;
}
}

View File

@@ -0,0 +1,26 @@
package test.util;
import java.io.*;
import java.util.concurrent.*;
import edu.wpi.first.wpilibj.networktables2.stream.*;
public class TestServerConnectionProvider implements IOStreamProvider{
private final BlockingQueue<IOStream> connections = new LinkedBlockingQueue<IOStream>();
public void supply(IOStream stream){
connections.offer(stream);
}
public IOStream accept() {
try {
return connections.take();
} catch (InterruptedException e) {
return null;
}
}
@Override
public void close() throws IOException {
}
}

View File

@@ -0,0 +1,76 @@
package test.util;
import java.util.*;
import java.util.concurrent.*;
import edu.wpi.first.wpilibj.networktables2.thread.*;
public class TestThreadManager implements NTThreadManager {
private final List<TestPeriodicThread> periodicThreads = new CopyOnWriteArrayList<TestPeriodicThread>();
public class TestPeriodicThread implements NTThread{
private final PeriodicRunnable r;
private final String name;
public TestPeriodicThread(PeriodicRunnable r, String name){
this.r = r;
this.name = name;
}
public String toString(){
return "Test Thread: "+name;
}
public String getName(){
return r.getClass().getName();
}
public void run(){
try {
r.run();
} catch (InterruptedException e) {}
}
@Override
public void stop() {
periodicThreads.remove(this);
}
@Override
public boolean isRunning() {
return periodicThreads.contains(this);
}
}
@Override
public NTThread newBlockingPeriodicThread(PeriodicRunnable r, String name) {
TestPeriodicThread thread = new TestPeriodicThread(r, name);
periodicThreads.add(thread);
return thread;
}
public TestPeriodicThread getPeriodicThread(Class<?> type){
TestPeriodicThread foundThread = null;
for(TestPeriodicThread thread:periodicThreads){
if(thread.getName().equals(type.getName())){
if(foundThread!=null)
throw new RuntimeException("There are more than one periodic threads of type: "+type);
foundThread = thread;
}
}
if(foundThread==null)
throw new RuntimeException("There are no periodic threads of type: "+type);
return foundThread;
}
public List<TestPeriodicThread> getAllPeriodicThread(Class<?> type){
List<TestPeriodicThread> threads = new ArrayList<TestPeriodicThread>();
for(TestPeriodicThread thread:periodicThreads){
if(thread.getName().equals(type.getName()))
threads.add(thread);
}
return threads;
}
public void runAllPeriodicThread(Class<?> type){
for(TestPeriodicThread thread:periodicThreads){
if(thread.getName().equals(type.getName()))
thread.run();
}
}
}