Applies Google Styleguide to Java parts of the library (#23)

This was partially applied to simulation but
simulation is a bit of a mess and has a lot of duplicated code.
This commit is contained in:
Jonathan Leitschuh
2016-05-20 12:07:40 -04:00
committed by Peter Johnson
parent 64ab6e51fe
commit a834fff7b2
266 changed files with 15574 additions and 14718 deletions

View File

@@ -7,6 +7,15 @@
package edu.wpi.first.wpilibj;
import org.junit.After;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
@@ -14,51 +23,39 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.After;
import org.junit.Test;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
/**
* This class should not be run as a test explicitly. Instead it should be
* extended by tests that use the InterruptableSensorBase
* This class should not be run as a test explicitly. Instead it should be extended by tests that
* use the InterruptableSensorBase.
*
* @author jonathanleitschuh
*
*/
public abstract class AbstractInterruptTest extends AbstractComsSetup {
private InterruptableSensorBase interruptable = null;
private InterruptableSensorBase m_interruptable = null;
private InterruptableSensorBase getInterruptable() {
if (interruptable == null) {
interruptable = giveInterruptableSensorBase();
if (m_interruptable == null) {
m_interruptable = giveInterruptableSensorBase();
}
return interruptable;
return m_interruptable;
}
@After
public void interruptTeardown() {
if (interruptable != null) {
if (m_interruptable != null) {
freeInterruptableSensorBase();
interruptable = null;
m_interruptable = null;
}
}
/**
* Give the interruptible sensor base that interrupts can be attached to.
*$
* @return
* Give the interruptable sensor base that interrupts can be attached to.
*/
abstract InterruptableSensorBase giveInterruptableSensorBase();
/**
* Cleans up the interruptible sensor base. This is only called if
* {@link #giveInterruptableSensorBase()} is called.
* Cleans up the interruptable sensor base. This is only called if {@link
* #giveInterruptableSensorBase()} is called.
*/
abstract void freeInterruptableSensorBase();
@@ -74,50 +71,54 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
private class InterruptCounter {
private final AtomicInteger count = new AtomicInteger();
private final AtomicInteger m_count = new AtomicInteger();
void increment() {
count.addAndGet(1);
m_count.addAndGet(1);
}
int getCount() {
return count.get();
return m_count.get();
}
};
}
private class TestInterruptHandlerFunction extends InterruptHandlerFunction<InterruptCounter> {
protected final AtomicBoolean exceptionThrown = new AtomicBoolean(false);
/** Stores the time that the interrupt fires */
final AtomicLong interruptFireTime = new AtomicLong();
/** Stores if the interrupt has completed at least once */
final AtomicBoolean interruptComplete = new AtomicBoolean(false);
protected Exception ex;
final InterruptCounter counter;
protected final AtomicBoolean m_exceptionThrown = new AtomicBoolean(false);
/**
* Stores the time that the interrupt fires.
*/
final AtomicLong m_interruptFireTime = new AtomicLong();
/**
* Stores if the interrupt has completed at least once.
*/
final AtomicBoolean m_interruptComplete = new AtomicBoolean(false);
protected Exception m_ex;
final InterruptCounter m_counter;
TestInterruptHandlerFunction(InterruptCounter counter) {
this.counter = counter;
m_counter = counter;
}
@Override
public void interruptFired(int interruptAssertedMask, InterruptCounter param) {
interruptFireTime.set(Utility.getFPGATime());
counter.increment();
m_interruptFireTime.set(Utility.getFPGATime());
m_counter.increment();
try {
// This won't cause the test to fail
assertSame(counter, param);
assertSame(m_counter, param);
} catch (Exception ex) {
// So we must throw the exception within the test
exceptionThrown.set(true);
this.ex = ex;
m_exceptionThrown.set(true);
m_ex = ex;
}
interruptComplete.set(true);
};
m_interruptComplete.set(true);
}
@Override
public InterruptCounter overridableParameter() {
return counter;
return m_counter;
}
};
}
@Test(timeout = 1000)
public void testSingleInterruptsTriggering() throws Exception {
@@ -137,7 +138,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
setInterruptHigh();
// Delay until the interrupt is complete
while (!function.interruptComplete.get()) {
while (!function.m_interruptComplete.get()) {
Timer.delay(.005);
}
@@ -145,14 +146,15 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
// Then
assertEquals("The interrupt did not fire the expected number of times", 1, counter.getCount());
// If the test within the interrupt failed
if (function.exceptionThrown.get()) {
throw function.ex;
if (function.m_exceptionThrown.get()) {
throw function.m_ex;
}
final long range = 10000; // in microseconds
assertThat(
"The interrupt did not fire within the expected time period (values in milliseconds)",
function.interruptFireTime.get(),
both(greaterThan(interruptTriggerTime - range)).and(lessThan(interruptTriggerTime + range)));
function.m_interruptFireTime.get(),
both(greaterThan(interruptTriggerTime - range)).and(lessThan(interruptTriggerTime
+ range)));
assertThat(
"The readRisingTimestamp() did not return the correct value (values in seconds)",
getInterruptable().readRisingTimestamp(),
@@ -175,7 +177,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
setInterruptLow();
setInterruptHigh();
// Wait for the interrupt to complete before moving on
while (!function.interruptComplete.getAndSet(false)) {
while (!function.m_interruptComplete.getAndSet(false)) {
Timer.delay(.005);
}
}
@@ -184,7 +186,9 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
counter.getCount());
}
/** The timeout length for this test in seconds */
/**
* The timeout length for this test in seconds.
*/
private static final int synchronousTimeout = 5;
@Test(timeout = (long) (synchronousTimeout * 1e3))
@@ -193,13 +197,10 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
getInterruptable().requestInterrupts();
final double synchronousDelay = synchronousTimeout / 2.;
Runnable r = new Runnable() {
@Override
public void run() {
Timer.delay(synchronousDelay);
setInterruptLow();
setInterruptHigh();
}
final Runnable runnable = () -> {
Timer.delay(synchronousDelay);
setInterruptLow();
setInterruptHigh();
};
// When
@@ -207,7 +208,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
// Note: the long time value is used because doubles can flip if the robot
// is left running for long enough
final long startTimeStamp = Utility.getFPGATime();
new Thread(r).start();
new Thread(runnable).start();
// Delay for twice as long as the timeout so the test should fail first
getInterruptable().waitForInterrupt(synchronousTimeout * 2);
final long stopTimeStamp = Utility.getFPGATime();
@@ -225,9 +226,11 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
getInterruptable().requestInterrupts();
//Don't fire interrupt. Expect it to timeout.
InterruptableSensorBase.WaitResult result = getInterruptable().waitForInterrupt(synchronousTimeout / 2);
InterruptableSensorBase.WaitResult result = getInterruptable()
.waitForInterrupt(synchronousTimeout / 2);
assertEquals("The interrupt did not time out correctly.", result, InterruptableSensorBase.WaitResult.kTimeout);
assertEquals("The interrupt did not time out correctly.", result, InterruptableSensorBase
.WaitResult.kTimeout);
}
@Test(timeout = (long) (synchronousTimeout * 1e3))
@@ -236,20 +239,19 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
getInterruptable().requestInterrupts();
final double synchronousDelay = synchronousTimeout / 2.;
Runnable r = new Runnable() {
@Override
public void run() {
Timer.delay(synchronousDelay);
setInterruptLow();
setInterruptHigh();
}
final Runnable runnable = () -> {
Timer.delay(synchronousDelay);
setInterruptLow();
setInterruptHigh();
};
new Thread(r).start();
new Thread(runnable).start();
// Delay for twice as long as the timeout so the test should fail first
InterruptableSensorBase.WaitResult result = getInterruptable().waitForInterrupt(synchronousTimeout * 2);
InterruptableSensorBase.WaitResult result = getInterruptable()
.waitForInterrupt(synchronousTimeout * 2);
assertEquals("The interrupt did not fire on the rising edge.", result, InterruptableSensorBase.WaitResult.kRisingEdge);
assertEquals("The interrupt did not fire on the rising edge.", result,
InterruptableSensorBase.WaitResult.kRisingEdge);
}
@Test(timeout = (long) (synchronousTimeout * 1e3))
@@ -259,20 +261,19 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
getInterruptable().setUpSourceEdge(false, true);
final double synchronousDelay = synchronousTimeout / 2.;
Runnable r = new Runnable() {
@Override
public void run() {
Timer.delay(synchronousDelay);
setInterruptHigh();
setInterruptLow();
}
final Runnable runnable = () -> {
Timer.delay(synchronousDelay);
setInterruptHigh();
setInterruptLow();
};
new Thread(r).start();
new Thread(runnable).start();
// Delay for twice as long as the timeout so the test should fail first
InterruptableSensorBase.WaitResult result = getInterruptable().waitForInterrupt(synchronousTimeout * 2);
InterruptableSensorBase.WaitResult result = getInterruptable()
.waitForInterrupt(synchronousTimeout * 2);
assertEquals("The interrupt did not fire on the falling edge.", result, InterruptableSensorBase.WaitResult.kFallingEdge);
assertEquals("The interrupt did not fire on the falling edge.", result,
InterruptableSensorBase.WaitResult.kFallingEdge);
}
@@ -290,7 +291,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
setInterruptLow();
setInterruptHigh();
// Wait for the interrupt to complete before moving on
while (!function.interruptComplete.getAndSet(false)) {
while (!function.m_interruptComplete.getAndSet(false)) {
Timer.delay(.005);
}
}

View File

@@ -7,25 +7,25 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.AnalogTriggerOutput.AnalogTriggerType;
import edu.wpi.first.wpilibj.fixtures.AnalogCrossConnectFixture;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author jonathanleitschuh
* Test that covers the {@link AnalogCrossConnectFixture}.
*
* @author jonathanleitschuh
*/
public class AnalogCrossConnectTest extends AbstractInterruptTest {
private static final Logger logger = Logger.getLogger(AnalogCrossConnectTest.class.getName());
@@ -40,36 +40,22 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest {
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
analogIO = TestBench.getAnalogCrossConnectFixture();
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
analogIO.teardown();
analogIO = null;
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
analogIO.setup();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
@Test
public void testAnalogOuput() {
@@ -155,43 +141,44 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest {
analogIO.getInput().getAccumulatorCount();
}
private AnalogTrigger interruptTrigger;
private AnalogTriggerOutput interruptTriggerOutput;
private AnalogTrigger m_interruptTrigger;
private AnalogTriggerOutput m_interruptTriggerOutput;
/*
* (non-Javadoc)
*$
*
* @see
* edu.wpi.first.wpilibj.AbstractInterruptTest#giveInterruptableSensorBase()
*/
@Override
InterruptableSensorBase giveInterruptableSensorBase() {
interruptTrigger = new AnalogTrigger(analogIO.getInput());
interruptTrigger.setLimitsVoltage(2.0f, 3.0f);
interruptTriggerOutput = new AnalogTriggerOutput(interruptTrigger, AnalogTriggerType.kState);
return interruptTriggerOutput;
m_interruptTrigger = new AnalogTrigger(analogIO.getInput());
m_interruptTrigger.setLimitsVoltage(2.0f, 3.0f);
m_interruptTriggerOutput = new AnalogTriggerOutput(m_interruptTrigger,
AnalogTriggerType.kState);
return m_interruptTriggerOutput;
}
/*
* (non-Javadoc)
*$
*
* @see
* edu.wpi.first.wpilibj.AbstractInterruptTest#freeInterruptableSensorBase()
*/
@Override
void freeInterruptableSensorBase() {
interruptTriggerOutput.cancelInterrupts();
interruptTriggerOutput.free();
interruptTriggerOutput = null;
interruptTrigger.free();
interruptTrigger = null;
m_interruptTriggerOutput.cancelInterrupts();
m_interruptTriggerOutput.free();
m_interruptTriggerOutput = null;
m_interruptTrigger.free();
m_interruptTrigger = null;
}
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptHigh()
*/
@Override
@@ -202,7 +189,7 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptLow()
*/
@Override

View File

@@ -7,50 +7,45 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.AnalogCrossConnectFixture;
import edu.wpi.first.wpilibj.mockhardware.FakePotentiometerSource;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertEquals;
/**
* @author jonathanleitschuh
* Tests the {@link AnalogPotentiometer}.
*
* @author jonathanleitschuh
*/
public class AnalogPotentiometerTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(AnalogPotentiometerTest.class.getName());
private AnalogCrossConnectFixture analogIO;
private FakePotentiometerSource potSource;
private AnalogPotentiometer pot;
private AnalogCrossConnectFixture m_analogIO;
private FakePotentiometerSource m_potSource;
private AnalogPotentiometer m_pot;
private static final double DOUBLE_COMPARISON_DELTA = 2.0;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
analogIO = TestBench.getAnalogCrossConnectFixture();
potSource = new FakePotentiometerSource(analogIO.getOutput(), 360);
pot = new AnalogPotentiometer(analogIO.getInput(), 360.0, 0);
m_analogIO = TestBench.getAnalogCrossConnectFixture();
m_potSource = new FakePotentiometerSource(m_analogIO.getOutput(), 360);
m_pot = new AnalogPotentiometer(m_analogIO.getInput(), 360.0, 0);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
potSource.reset();
pot.free();
analogIO.teardown();
m_potSource.reset();
m_pot.free();
m_analogIO.teardown();
}
@Override
@@ -60,16 +55,16 @@ public class AnalogPotentiometerTest extends AbstractComsSetup {
@Test
public void testInitialSettings() {
assertEquals(0, pot.get(), DOUBLE_COMPARISON_DELTA);
assertEquals(0, m_pot.get(), DOUBLE_COMPARISON_DELTA);
}
@Test
public void testRangeValues() {
for (double i = 0.0; i < 360.0; i = i + 1.0) {
potSource.setAngle(i);
potSource.setMaxVoltage(ControllerPower.getVoltage5V());
m_potSource.setAngle(i);
m_potSource.setMaxVoltage(ControllerPower.getVoltage5V());
Timer.delay(.02);
assertEquals(i, pot.get(), DOUBLE_COMPARISON_DELTA);
assertEquals(i, m_pot.get(), DOUBLE_COMPARISON_DELTA);
}
}

View File

@@ -7,21 +7,21 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.interfaces.Accelerometer;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class BuiltInAccelerometerTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(BuiltInAccelerometerTest.class.getName());
@@ -46,7 +46,7 @@ public class BuiltInAccelerometerTest extends AbstractComsSetup {
*/
@Parameters
public static Collection<Accelerometer.Range[]> generateData() {
return Arrays.asList(new Accelerometer.Range[][] { {Accelerometer.Range.k2G},
return Arrays.asList(new Accelerometer.Range[][]{{Accelerometer.Range.k2G},
{Accelerometer.Range.k4G}, {Accelerometer.Range.k8G},});
}
@@ -56,8 +56,8 @@ public class BuiltInAccelerometerTest extends AbstractComsSetup {
}
/**
* There's not much we can automatically test with the on-board accelerometer,
* but checking for gravity is probably good enough to tell that it's working.
* There's not much we can automatically test with the on-board accelerometer, but checking for
* gravity is probably good enough to tell that it's working.
*/
@Test
public void testAccelerometer() {

View File

@@ -7,19 +7,17 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertTrue;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.SampleFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.hal.CanTalonJNI;
import static org.junit.Assert.assertTrue;
/**
* Basic test (borrowed straight from SampleTest) for running the CAN TalonSRX.
@@ -27,7 +25,7 @@ import edu.wpi.first.wpilibj.hal.CanTalonJNI;
public class CANTalonTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(SampleTest.class.getName());
static SampleFixture fixture = new SampleFixture();
static SampleFixture m_fixture = new SampleFixture();
protected Logger getClassLogger() {
return logger;
@@ -36,19 +34,19 @@ public class CANTalonTest extends AbstractComsSetup {
@BeforeClass
public static void classSetup() {
// Set up the fixture before the test is created
fixture.setup();
m_fixture.setup();
}
@Before
public void setUp() {
// Reset the fixture elements before every test
fixture.reset();
m_fixture.reset();
}
@AfterClass
public static void tearDown() {
// Clean up the fixture after the test
fixture.teardown();
m_fixture.teardown();
}
private String errorMessage(double actual, double expected) {
@@ -84,9 +82,10 @@ public class CANTalonTest extends AbstractComsSetup {
}
@Test
public void SetGetPID() {
public void setGetPID() {
CANTalon talon = new CANTalon(0);
talon.changeControlMode(CANTalon.TalonControlMode.Position);
@SuppressWarnings({"LocalVariableName", "MultipleVariableDeclarations"})
double p = 0.05, i = 0.098, d = 1.23;
talon.setPID(p, i, d);
assertTrue(errorMessage(talon.getP(), p), Math.abs(p - talon.getP()) < 1e-5);
@@ -109,6 +108,7 @@ public class CANTalonTest extends AbstractComsSetup {
talon.changeControlMode(CANTalon.TalonControlMode.Position);
talon.setFeedbackDevice(CANTalon.FeedbackDevice.AnalogPot);
Timer.delay(0.2);
@SuppressWarnings({"LocalVariableName", "MultipleVariableDeclarations"})
double p = 1.0, i = 0.0, d = 0.00;
talon.setPID(p, i, d);
talon.set(100);
@@ -137,20 +137,20 @@ public class CANTalonTest extends AbstractComsSetup {
CANTalon talon = new CANTalon(0);
talon.clearStickyFaults();
assertTrue(talon.getFaultOverTemp()==0);
assertTrue(talon.getFaultUnderVoltage()==0);
assertTrue(talon.getFaultForLim()==0);
assertTrue(talon.getFaultRevLim()==0);
assertTrue(talon.getFaultHardwareFailure()==0);
assertTrue(talon.getFaultForSoftLim()==0);
assertTrue(talon.getFaultRevSoftLim()==0);
assertTrue(talon.getFaultOverTemp() == 0);
assertTrue(talon.getFaultUnderVoltage() == 0);
assertTrue(talon.getFaultForLim() == 0);
assertTrue(talon.getFaultRevLim() == 0);
assertTrue(talon.getFaultHardwareFailure() == 0);
assertTrue(talon.getFaultForSoftLim() == 0);
assertTrue(talon.getFaultRevSoftLim() == 0);
assertTrue(talon.getStickyFaultOverTemp()==0);
// assertTrue(talon.getStickyFaultUnderVoltage()==0);
assertTrue(talon.getStickyFaultForLim()==0);
assertTrue(talon.getStickyFaultRevLim()==0);
assertTrue(talon.getStickyFaultForSoftLim()==0);
assertTrue(talon.getStickyFaultRevSoftLim()==0);
assertTrue(talon.getStickyFaultOverTemp() == 0);
// assertTrue(talon.getStickyFaultUnderVoltage()==0);
assertTrue(talon.getStickyFaultForLim() == 0);
assertTrue(talon.getStickyFaultRevLim() == 0);
assertTrue(talon.getStickyFaultForSoftLim() == 0);
assertTrue(talon.getStickyFaultRevSoftLim() == 0);
}
}

View File

@@ -7,34 +7,33 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.logging.Logger;
import org.junit.Test;
import edu.wpi.first.wpilibj.CircularBuffer;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
public class CircularBufferTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(CircularBufferTest.class.getName());
private double[] values = {751.848, 766.366, 342.657, 234.252, 716.126,
132.344, 445.697, 22.727, 421.125, 799.913};
private double[] pushFrontOut = {799.913, 421.125, 22.727, 445.697, 132.344,
716.126, 234.252, 342.657};
private double[] pushBackOut = {342.657, 234.252, 716.126, 132.344, 445.697,
22.727, 421.125, 799.913};
private double[] m_values = {751.848, 766.366, 342.657, 234.252, 716.126,
132.344, 445.697, 22.727, 421.125, 799.913};
private double[] m_pushFrontOut = {799.913, 421.125, 22.727, 445.697, 132.344,
716.126, 234.252, 342.657};
private double[] m_pushBackOut = {342.657, 234.252, 716.126, 132.344, 445.697,
22.727, 421.125, 799.913};
@Test
public void pushFrontTest() {
CircularBuffer queue = new CircularBuffer(8);
for (double value : values) {
for (double value : m_values) {
queue.pushFront(value);
}
for (int i = 0; i < pushFrontOut.length; i++) {
assertEquals(pushFrontOut[i], queue.get(i), 0.00005);
for (int i = 0; i < m_pushFrontOut.length; i++) {
assertEquals(m_pushFrontOut[i], queue.get(i), 0.00005);
}
}
@@ -42,12 +41,12 @@ public class CircularBufferTest extends AbstractComsSetup {
public void pushBackTest() {
CircularBuffer queue = new CircularBuffer(8);
for (double value : values) {
for (double value : m_values) {
queue.pushBack(value);
}
for (int i = 0; i < pushBackOut.length; i++) {
assertEquals(pushBackOut[i], queue.get(i), 0.00005);
for (int i = 0; i < m_pushBackOut.length; i++) {
assertEquals(m_pushBackOut[i], queue.get(i), 0.00005);
}
}

View File

@@ -7,11 +7,6 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -20,23 +15,28 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.FakeCounterFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests to see if the Counter is working properly
*$
* @author Jonathan Leitschuh
* Tests to see if the Counter is working properly.
*
* @author Jonathan Leitschuh
*/
@RunWith(Parameterized.class)
public class CounterTest extends AbstractComsSetup {
private static FakeCounterFixture counter = null;
private static final Logger logger = Logger.getLogger(CounterTest.class.getName());
Integer input;
Integer output;
Integer m_input;
Integer m_output;
@Override
protected Logger getClassLogger() {
@@ -44,29 +44,29 @@ public class CounterTest extends AbstractComsSetup {
}
/**
* Constructs a Counter Test with the given inputs
*$
* @param input The input Port
* Constructs a Counter Test with the given inputs.
*
* @param input The input Port
* @param output The output Port
*/
public CounterTest(Integer input, Integer output) {
assert input != null;
assert output != null;
this.input = input;
this.output = output;
m_input = input;
m_output = output;
// System.out.println("Counter Test: Input: " + input + " Output: " +
// output);
if (counter != null)
if (counter != null) {
counter.teardown();
}
counter = new FakeCounterFixture(input, output);
}
/**
* Test data generator. This method is called the the JUnit parameterized test
* runner and returns a Collection of Arrays. For each Array in the
* Collection, each array element corresponds to a parameter in the
* constructor.
* Test data generator. This method is called the the JUnit parameterized test runner and returns
* a Collection of Arrays. For each Array in the Collection, each array element corresponds to a
* parameter in the constructor.
*/
@Parameters
public static Collection<Integer[]> generateData() {
@@ -79,48 +79,39 @@ public class CounterTest extends AbstractComsSetup {
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
public static void setUpBeforeClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
counter.teardown();
counter = null;
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
counter.setup();
}
/**
* Tests the default state of the counter immediately after reset
* Tests the default state of the counter immediately after reset.
*/
@Test
public void testDefault() {
assertTrue("Counter did not reset to 0", counter.getCounter().get() == 0);
assertEquals("Counter did not reset to 0", 0, counter.getCounter().get());
}
@Test(timeout = 5000)
public void testCount() {
int goal = 100;
final int goal = 100;
counter.getFakeCounterSource().setCount(goal);
counter.getFakeCounterSource().execute();
int count = counter.getCounter().get();
final int count = counter.getCounter().get();
assertTrue("Fake Counter, Input: " + input + ", Output: " + output + ", did not return " + goal
+ " instead got: " + count, count == goal);
assertTrue("Fake Counter, Input: " + m_input + ", Output: " + m_output + ", did not return "
+ goal + " instead got: " + count, count == goal);
}
}

View File

@@ -7,12 +7,6 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Test;
@@ -20,12 +14,18 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.DIOCrossConnectFixture;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Tests to see if the Digital ports are working properly
*$
* Tests to see if the Digital ports are working properly.
*
* @author jonathanleitschuh
*/
@RunWith(Parameterized.class)
@@ -40,14 +40,12 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
}
/**
* Default constructor for the DIOCrossConnectTest This test is parameterized
* in order to allow it to be tested using a variety of different input/output
* pairs without duplicate code.<br>
* This class takes Integer port values instead of DigitalClasses because it
* would force them to be instantiated at the same time which could (untested)
* cause port binding errors.
*$
* @param input The port for the input wire
* Default constructor for the DIOCrossConnectTest This test is parameterized in order to allow it
* to be tested using a variety of different input/output pairs without duplicate code.<br> This
* class takes Integer port values instead of DigitalClasses because it would force them to be
* instantiated at the same time which could (untested) cause port binding errors.
*
* @param input The port for the input wire
* @param output The port for the output wire
*/
public DIOCrossConnectTest(Integer input, Integer output) {
@@ -58,12 +56,10 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
}
/**
* Test data generator. This method is called the the JUnit parameterized test
* runner and returns a Collection of Arrays. For each Array in the
* Collection, each array element corresponds to a parameter in the
* constructor.
* Test data generator. This method is called the the JUnit parameterized test runner and returns
* a Collection of Arrays. For each Array in the Collection, each array element corresponds to a
* parameter in the constructor.
*/
@Parameters(name = "{index}: Input Port: {0} Output Port: {1}")
public static Collection<Integer[]> generateData() {
@@ -87,7 +83,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
}
/**
* Tests to see if the DIO can create and recognize a high value
* Tests to see if the DIO can create and recognize a high value.
*/
@Test
public void testSetHigh() {
@@ -98,7 +94,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
}
/**
* Tests to see if the DIO can create and recognize a low value
* Tests to see if the DIO can create and recognize a low value.
*/
@Test
public void testSetLow() {
@@ -112,7 +108,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
* Tests to see if the DIO PWM functionality works.
*/
@Test
public void testDIOPWM() {
public void testDIOpulseWidthModulation() {
dio.getOutput().set(false);
assertFalse("DIO Not Low after no delay", dio.getInput().get());
//Set frequency to 2.0 Hz
@@ -126,24 +122,24 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
//TODO: Add return value from WaitForInterrupt
dio.getInput().waitForInterrupt(3.0, true);
Timer.delay(0.5);
boolean firstCycle = dio.getInput().get();
final boolean firstCycle = dio.getInput().get();
Timer.delay(0.5);
boolean secondCycle = dio.getInput().get();
final boolean secondCycle = dio.getInput().get();
Timer.delay(0.5);
boolean thirdCycle = dio.getInput().get();
final boolean thirdCycle = dio.getInput().get();
Timer.delay(0.5);
boolean forthCycle = dio.getInput().get();
final boolean forthCycle = dio.getInput().get();
Timer.delay(0.5);
boolean fifthCycle = dio.getInput().get();
final boolean fifthCycle = dio.getInput().get();
Timer.delay(0.5);
boolean sixthCycle = dio.getInput().get();
final boolean sixthCycle = dio.getInput().get();
Timer.delay(0.5);
boolean seventhCycle = dio.getInput().get();
final boolean seventhCycle = dio.getInput().get();
dio.getOutput().disablePWM();
Timer.delay(0.5);
boolean firstAfterStop = dio.getInput().get();
final boolean firstAfterStop = dio.getInput().get();
Timer.delay(0.5);
boolean secondAfterStop = dio.getInput().get();
final boolean secondAfterStop = dio.getInput().get();
assertFalse("DIO Not Low after first delay", firstCycle);
assertTrue("DIO Not High after second delay", secondCycle);
@@ -158,7 +154,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
/*
* (non-Javadoc)
*$
*
* @see
* edu.wpi.first.wpilibj.AbstractInterruptTest#giveInterruptableSensorBase()
*/
@@ -169,7 +165,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
/*
* (non-Javadoc)
*$
*
* @see
* edu.wpi.first.wpilibj.AbstractInterruptTest#freeInterruptableSensorBase()
*/
@@ -180,7 +176,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptHigh()
*/
@Override
@@ -190,7 +186,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptLow()
*/
@Override

View File

@@ -7,18 +7,13 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.logging.Logger;
import org.junit.Test;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Counter;
import edu.wpi.first.wpilibj.DigitalGlitchFilter;
import static org.junit.Assert.assertEquals;
/**
* Test for the DigitalGlitchFilter class.
@@ -27,38 +22,37 @@ import edu.wpi.first.wpilibj.DigitalGlitchFilter;
*/
public class DigitalGlitchFilterTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(
DigitalGlitchFilterTest.class.getName());
DigitalGlitchFilterTest.class.getName());
protected Logger getClassLogger() {
return logger;
}
/**
* This is a test to make sure that filters can be created and are consistent.
* This assumes that the FPGA implementation to actually implement the filter
* has been tested. It does validate that we are successfully able to set and
* get the active filters for ports and makes sure that the FPGA filter is
* changed correctly, and does the same for the period.
* This is a test to make sure that filters can be created and are consistent. This assumes that
* the FPGA implementation to actually implement the filter has been tested. It does validate
* that we are successfully able to set and get the active filters for ports and makes sure that
* the FPGA filter is changed correctly, and does the same for the period.
*/
@Test
public void testDigitalGlitchFilterBasic() {
DigitalInput input1 = new DigitalInput(1);
DigitalInput input2 = new DigitalInput(2);
DigitalInput input3 = new DigitalInput(3);
DigitalInput input4 = new DigitalInput(4);
Encoder encoder5 = new Encoder(5, 6);
Counter counter7 = new Counter(7);
final DigitalInput input1 = new DigitalInput(1);
final DigitalInput input2 = new DigitalInput(2);
final DigitalInput input3 = new DigitalInput(3);
final DigitalInput input4 = new DigitalInput(4);
final Encoder encoder5 = new Encoder(5, 6);
final Counter counter7 = new Counter(7);
DigitalGlitchFilter filter1 = new DigitalGlitchFilter();
final DigitalGlitchFilter filter1 = new DigitalGlitchFilter();
filter1.add(input1);
filter1.setPeriodNanoSeconds(4200);
DigitalGlitchFilter filter2 = new DigitalGlitchFilter();
final DigitalGlitchFilter filter2 = new DigitalGlitchFilter();
filter2.add(input2);
filter2.add(input3);
filter2.setPeriodNanoSeconds(97100);
DigitalGlitchFilter filter3 = new DigitalGlitchFilter();
final DigitalGlitchFilter filter3 = new DigitalGlitchFilter();
filter3.add(input4);
filter3.add(encoder5);
filter3.add(counter7);

View File

@@ -7,11 +7,6 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -20,27 +15,31 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.FakeEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertTrue;
/**
* Test to see if the FPGA properly recognizes a mock Encoder input
*$
* @author Jonathan Leitschuh
* Test to see if the FPGA properly recognizes a mock Encoder input.
*
* @author Jonathan Leitschuh
*/
@RunWith(Parameterized.class)
public class EncoderTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(EncoderTest.class.getName());
private static FakeEncoderFixture encoder = null;
private final boolean flip; // Does this test need to flip the inputs
private final int inputA;
private final int inputB;
private final int outputA;
private final int outputB;
private final boolean m_flip; // Does this test need to flip the inputs
private final int m_inputA;
private final int m_inputB;
private final int m_outputA;
private final int m_outputB;
@Override
protected Logger getClassLogger() {
@@ -48,10 +47,9 @@ public class EncoderTest extends AbstractComsSetup {
}
/**
* Test data generator. This method is called the the JUnit parameterized test
* runner and returns a Collection of Arrays. For each Array in the
* Collection, each array element corresponds to a parameter in the
* constructor.
* Test data generator. This method is called the the JUnit parametrized test runner and returns
* a Collection of Arrays. For each Array in the Collection, each array element corresponds to a
* parameter in the constructor.
*/
@Parameters
public static Collection<Integer[]> generateData() {
@@ -59,32 +57,29 @@ public class EncoderTest extends AbstractComsSetup {
}
/**
* Constructs a parameterized Encoder Test
*$
* @param inputA The port number for inputA
* Constructs a parametrized Encoder Test.
*
* @param inputA The port number for inputA
* @param outputA The port number for outputA
* @param inputB The port number for inputB
* @param inputB The port number for inputB
* @param outputB The port number for outputB
* @param flip whether or not these set of values require the encoder to be
* reversed (0 or 1)
* @param flip whether or not these set of values require the encoder to be reversed (0 or 1)
*/
public EncoderTest(int inputA, int outputA, int inputB, int outputB, int flip) {
this.inputA = inputA;
this.inputB = inputB;
this.outputA = outputA;
this.outputB = outputB;
m_inputA = inputA;
m_inputB = inputB;
m_outputA = outputA;
m_outputB = outputB;
// If the encoder from a previous test is allocated then we must free its
// members
if (encoder != null)
if (encoder != null) {
encoder.teardown();
this.flip = flip == 0;
}
m_flip = flip == 0;
encoder = new FakeEncoderFixture(inputA, outputA, inputB, outputB);
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
encoder.teardown();
@@ -92,9 +87,7 @@ public class EncoderTest extends AbstractComsSetup {
}
/**
* Sets up the test and verifies that the test was reset to the default state
*$
* @throws java.lang.Exception
* Sets up the test and verifies that the test was reset to the default state.
*/
@Before
public void setUp() throws Exception {
@@ -102,16 +95,13 @@ public class EncoderTest extends AbstractComsSetup {
testDefaultState();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
encoder.reset();
}
/**
* Tests to see if Encoders initialize to zero
* Tests to see if Encoders initialize to zero.
*/
@Test
public void testDefaultState() {
@@ -120,13 +110,13 @@ public class EncoderTest extends AbstractComsSetup {
}
/**
* Tests to see if Encoders can count up sucsessfully
* Tests to see if Encoders can count up successfully.
*/
@Test
public void testCountUp() {
int goal = 100;
encoder.getFakeEncoderSource().setCount(goal);
encoder.getFakeEncoderSource().setForward(flip);
encoder.getFakeEncoderSource().setForward(m_flip);
encoder.getFakeEncoderSource().execute();
int value = encoder.getEncoder().get();
assertTrue(errorMessage(goal, value), value == goal);
@@ -134,13 +124,13 @@ public class EncoderTest extends AbstractComsSetup {
}
/**
* Tests to see if Encoders can count down sucsessfully
* Tests to see if Encoders can count down successfully.
*/
@Test
public void testCountDown() {
int goal = -100;
encoder.getFakeEncoderSource().setCount(goal); // Goal has to be positive
encoder.getFakeEncoderSource().setForward(!flip);
encoder.getFakeEncoderSource().setForward(!m_flip);
encoder.getFakeEncoderSource().execute();
int value = encoder.getEncoder().get();
assertTrue(errorMessage(goal, value), value == goal);
@@ -148,16 +138,14 @@ public class EncoderTest extends AbstractComsSetup {
}
/**
* Creates a simple message with the error that was encounterd for the
* Encoders
*$
* @param goal The goal that was trying to be reached
* Creates a simple message with the error that was encountered for the Encoders.
*
* @param goal The goal that was trying to be reached
* @param trueValue The actual value that was reached by the test
* @return A fully constructed message with data about where and why the the
* test failed
* @return A fully constructed message with data about where and why the the test failed.
*/
private String errorMessage(int goal, int trueValue) {
return "Encoder ({In,Out}): {" + inputA + ", " + outputA + "},{" + inputB + ", " + outputB
+ "} Returned: " + trueValue + ", Wanted: " + goal;
return "Encoder ({In,Out}): {" + m_inputA + ", " + m_outputA + "},{" + m_inputB + ", "
+ m_outputB + "} Returned: " + trueValue + ", Wanted: " + goal;
}
}

View File

@@ -7,12 +7,6 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -21,10 +15,16 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.FilterNoiseFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertTrue;
@RunWith(Parameterized.class)
public class FilterNoiseTest extends AbstractComsSetup {
@@ -37,18 +37,24 @@ public class FilterNoiseTest extends AbstractComsSetup {
return logger;
}
/**
* Constructs the FilterNoiseTest.
*
* @param mef The fixture under test.
*/
public FilterNoiseTest(FilterNoiseFixture<?> mef) {
logger.fine("Constructor with: " + mef.getType());
if (me != null && !me.equals(mef))
if (me != null && !me.equals(mef)) {
me.teardown();
}
me = mef;
}
@Parameters(name = "{index}: {0}")
public static Collection<FilterNoiseFixture<?>[]> generateData() {
return Arrays.asList(new FilterNoiseFixture<?>[][] {
{TestBench.getInstance().getSinglePoleIIRNoiseFixture()},
{TestBench.getInstance().getMovAvgNoiseFixture()}});
return Arrays.asList(new FilterNoiseFixture<?>[][]{
{TestBench.getInstance().getSinglePoleIIRNoiseFixture()},
{TestBench.getInstance().getMovAvgNoiseFixture()}});
}
@Before
@@ -69,11 +75,10 @@ public class FilterNoiseTest extends AbstractComsSetup {
}
/**
* Test if the filter reduces the noise produced by a signal generator
* Test if the filter reduces the noise produced by a signal generator.
*/
@Test
public void testNoiseReduce() {
double theoryData = 0.0;
double noiseGenError = 0.0;
double filterError = 0.0;
@@ -81,11 +86,12 @@ public class FilterNoiseTest extends AbstractComsSetup {
noise.reset();
for (double t = 0; t < TestBench.kFilterTime; t += TestBench.kFilterStep) {
theoryData = noise.getData(t);
final double theoryData = noise.getData(t);
filterError += Math.abs(me.getFilter().pidGet() - theoryData);
noiseGenError += Math.abs(noise.get() - theoryData);
}
assertTrue(me.getType() + " should have reduced noise accumulation from " + noiseGenError + " but failed. The filter error was " + filterError, noiseGenError > filterError);
assertTrue(me.getType() + " should have reduced noise accumulation from " + noiseGenError
+ " but failed. The filter error was " + filterError, noiseGenError > filterError);
}
}

View File

@@ -7,12 +7,6 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -21,16 +15,22 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.FilterOutputFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class FilterOutputTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(FilterOutputTest.class.getName());
private double expectedOutput;
private double m_expectedOutput;
private static FilterOutputFixture<?> me = null;
@@ -39,20 +39,26 @@ public class FilterOutputTest extends AbstractComsSetup {
return logger;
}
/**
* Constructs a filter output test.
*
* @param mef The fixture under test.
*/
public FilterOutputTest(FilterOutputFixture<?> mef) {
logger.fine("Constructor with: " + mef.getType());
if (me != null && !me.equals(mef))
if (me != null && !me.equals(mef)) {
me.teardown();
}
me = mef;
expectedOutput = me.getExpectedOutput();
m_expectedOutput = me.getExpectedOutput();
}
@Parameters(name = "{index}: {0}")
public static Collection<FilterOutputFixture<?>[]> generateData() {
return Arrays.asList(new FilterOutputFixture<?>[][] {
{TestBench.getInstance().getSinglePoleIIROutputFixture()},
{TestBench.getInstance().getHighPassOutputFixture()},
{TestBench.getInstance().getMovAvgOutputFixture()}});
return Arrays.asList(new FilterOutputFixture<?>[][]{
{TestBench.getInstance().getSinglePoleIIROutputFixture()},
{TestBench.getInstance().getHighPassOutputFixture()},
{TestBench.getInstance().getMovAvgOutputFixture()}});
}
@Before
@@ -73,7 +79,7 @@ public class FilterOutputTest extends AbstractComsSetup {
}
/**
* Test if the filter produces consistent output for a given data set
* Test if the filter produces consistent output for a given data set.
*/
@Test
public void testOutput() {
@@ -84,6 +90,6 @@ public class FilterOutputTest extends AbstractComsSetup {
filterOutput = me.getFilter().pidGet();
}
assertEquals(me.getType() + " output was incorrect.", expectedOutput, filterOutput, 0.00005);
assertEquals(me.getType() + " output was incorrect.", m_expectedOutput, filterOutput, 0.00005);
}
}

View File

@@ -7,25 +7,28 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.TiltPanCameraFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertEquals;
/**
* Tests that the {@link TiltPanCameraFixture}.
*/
public class GyroTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(GyroTest.class.getName());
public static final double TEST_ANGLE = 90.0;
private TiltPanCameraFixture tpcam;
private TiltPanCameraFixture m_tpcam;
@Override
protected Logger getClassLogger() {
@@ -35,20 +38,20 @@ public class GyroTest extends AbstractComsSetup {
@Before
public void setUp() throws Exception {
logger.fine("Setup: TiltPan camera");
tpcam = TestBench.getInstance().getTiltPanCam();
tpcam.setup();
m_tpcam = TestBench.getInstance().getTiltPanCam();
m_tpcam.setup();
}
@After
public void tearDown() throws Exception {
tpcam.teardown();
m_tpcam.teardown();
}
@Test
public void testAllGyroTests() {
testInitial(tpcam.getGyro());
testDeviationOverTime(tpcam.getGyro());
testGyroAngle(tpcam.getGyro());
testInitial(m_tpcam.getGyro());
testDeviationOverTime(m_tpcam.getGyro());
testGyroAngle(m_tpcam.getGyro());
testGyroAngleCalibratedParameters();
}
@@ -58,15 +61,14 @@ public class GyroTest extends AbstractComsSetup {
}
/**
* Test to see if the Servo and the gyroscope is turning 90 degrees Note servo
* on TestBench is not the same type of servo that servo class was designed
* for so setAngle is significantly off. This has been calibrated for the
* servo on the rig.
* Test to see if the Servo and the gyroscope is turning 90 degrees Note servo on TestBench is not
* the same type of servo that servo class was designed for so setAngle is significantly off. This
* has been calibrated for the servo on the rig.
*/
public void testGyroAngle(AnalogGyro gyro) {
// Set angle
for (int i = 0; i < 5; i++) {
tpcam.getPan().set(0);
m_tpcam.getPan().set(0);
Timer.delay(.1);
}
@@ -77,7 +79,7 @@ public class GyroTest extends AbstractComsSetup {
// Perform test
for (int i = 0; i < 53; i++) {
tpcam.getPan().set(i / 100.0);
m_tpcam.getPan().set(i / 100.0);
Timer.delay(0.05);
}
Timer.delay(1.2);
@@ -91,7 +93,8 @@ public class GyroTest extends AbstractComsSetup {
assertEquals(errorMessage(diff, TEST_ANGLE), TEST_ANGLE, angle, 10);
}
public void testDeviationOverTime(AnalogGyro gyro) {
protected void testDeviationOverTime(AnalogGyro gyro) {
// Make sure that the test isn't influenced by any previous motions.
Timer.delay(0.5);
gyro.reset();
@@ -104,20 +107,20 @@ public class GyroTest extends AbstractComsSetup {
}
/**
* Gets calibrated parameters from already calibrated gyro, allocates a
* new gyro with the center and offset parameters, and re-runs the test.
* Gets calibrated parameters from already calibrated gyro, allocates a new gyro with the center
* and offset parameters, and re-runs the test.
*/
public void testGyroAngleCalibratedParameters() {
// Get calibrated parameters to make new Gyro with parameters
double cOffset = tpcam.getGyro().getOffset();
int cCenter = tpcam.getGyro().getCenter();
tpcam.freeGyro();
tpcam.setupGyroParam(cCenter, cOffset);
final double calibratedOffset = m_tpcam.getGyro().getOffset();
final int calibratedCenter = m_tpcam.getGyro().getCenter();
m_tpcam.freeGyro();
m_tpcam.setupGyroParam(calibratedCenter, calibratedOffset);
Timer.delay(TiltPanCameraFixture.RESET_TIME);
// Repeat tests
testInitial(tpcam.getGyroParam());
testDeviationOverTime(tpcam.getGyroParam());
testGyroAngle(tpcam.getGyroParam());
testInitial(m_tpcam.getGyroParam());
testDeviationOverTime(m_tpcam.getGyroParam());
testGyroAngle(m_tpcam.getGyroParam());
}
private String errorMessage(double difference, double target) {

View File

@@ -7,14 +7,6 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -23,10 +15,18 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(Parameterized.class)
public class MotorEncoderTest extends AbstractComsSetup {
@@ -43,17 +43,23 @@ public class MotorEncoderTest extends AbstractComsSetup {
return logger;
}
/**
* Constructs the test
*
* @param mef The fixture under test.
*/
public MotorEncoderTest(MotorEncoderFixture<?> mef) {
logger.fine("Constructor with: " + mef.getType());
if (me != null && !me.equals(mef))
if (me != null && !me.equals(mef)) {
me.teardown();
}
me = mef;
}
@Parameters(name = "{index}: {0}")
public static Collection<MotorEncoderFixture<?>[]> generateData() {
// logger.fine("Loading the MotorList");
return Arrays.asList(new MotorEncoderFixture<?>[][] { {TestBench.getInstance().getTalonPair()},
return Arrays.asList(new MotorEncoderFixture<?>[][]{{TestBench.getInstance().getTalonPair()},
{TestBench.getInstance().getVictorPair()}, {TestBench.getInstance().getJaguarPair()}});
}
@@ -80,9 +86,8 @@ public class MotorEncoderTest extends AbstractComsSetup {
}
/**
* Test to ensure that the isMotorWithinRange method is functioning properly.
* Really only needs to run on one MotorEncoderFixture to ensure that it is
* working correctly.
* Test to ensure that the isMotorWithinRange method is functioning properly. Really only needs to
* run on one MotorEncoderFixture to ensure that it is working correctly.
*/
@Test
public void testIsMotorWithinRange() {
@@ -94,8 +99,8 @@ public class MotorEncoderTest extends AbstractComsSetup {
}
/**
* This test is designed to see if the values of different motors will
* increment when spun forward
* This test is designed to see if the values of different motors will increment when spun
* forward.
*/
@Test
public void testIncrement() {
@@ -110,8 +115,8 @@ public class MotorEncoderTest extends AbstractComsSetup {
}
/**
* This test is designed to see if the values of different motors will
* decrement when spun in reverse
* This test is designed to see if the values of different motors will decrement when spun in
* reverse.
*/
@Test
public void testDecrement() {
@@ -125,12 +130,12 @@ public class MotorEncoderTest extends AbstractComsSetup {
}
/**
* This method test if the counters count when the motors rotate
* This method test if the counters count when the motors rotate.
*/
@Test
public void testCounter() {
int counter1Start = me.getCounters()[0].get();
int counter2Start = me.getCounters()[1].get();
final int counter1Start = me.getCounters()[0].get();
final int counter2Start = me.getCounters()[1].get();
me.getMotor().set(.75);
Timer.delay(MOTOR_RUNTIME);
@@ -145,8 +150,8 @@ public class MotorEncoderTest extends AbstractComsSetup {
}
/**
* Tests to see if you set the speed to something not {@literal <=} 1.0 if the code
* appropriately throttles the value
* Tests to see if you set the speed to something not {@literal <=} 1.0 if the code appropriately
* throttles the value.
*/
@Test
public void testSetHighForwardSpeed() {
@@ -156,8 +161,8 @@ public class MotorEncoderTest extends AbstractComsSetup {
}
/**
* Tests to see if you set the speed to something not {@literal >=} -1.0 if the code
* appropriately throttles the value
* Tests to see if you set the speed to something not {@literal >=} -1.0 if the code appropriately
* throttles the value.
*/
@Test
public void testSetHighReverseSpeed() {
@@ -180,8 +185,8 @@ public class MotorEncoderTest extends AbstractComsSetup {
pid.disable();
assertTrue(
"PID loop did not reach setpoint within 10 seconds. The average error was: " + pid.getAvgError() +
"The current error was" + pid.getError(), pid.onTarget());
"PID loop did not reach setpoint within 10 seconds. The average error was: " + pid
.getAvgError() + "The current error was" + pid.getError(), pid.onTarget());
pid.free();
}
@@ -208,9 +213,8 @@ public class MotorEncoderTest extends AbstractComsSetup {
}
/**
* Checks to see if the encoders and counters are appropriately reset to zero
* when reset
*$
* Checks to see if the encoders and counters are appropriately reset to zero when reset.
*
* @param me The MotorEncoderFixture under test
*/
private void encodersResetCheck(MotorEncoderFixture<?> me) {
@@ -223,7 +227,7 @@ public class MotorEncoderTest extends AbstractComsSetup {
assertEquals(me.getType() + " Counter2 value was incorrect after reset.",
me.getCounters()[1].get(), 0);
Timer.delay(0.5); // so this doesn't fail with the 0.5 second default
// timeout on the encoders
// timeout on the encoders
assertTrue(me.getType() + " Encoder.getStopped() returned false after the motor was reset.", me
.getEncoder().getStopped());
}

View File

@@ -7,25 +7,26 @@
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Tests Inversion of motors using the SpeedController setInverted
* Tests Inversion of motors using the SpeedController setInverted.
*/
@RunWith(Parameterized.class)
public class MotorInvertingTest extends AbstractComsSetup {
@@ -34,18 +35,24 @@ public class MotorInvertingTest extends AbstractComsSetup {
private static final double delaytime = 0.3;
/**
* Constructs the test.
*
* @param afixture The fixture under test.
*/
public MotorInvertingTest(MotorEncoderFixture<?> afixture) {
logger.fine("Constructor with: " + afixture.getType());
if (fixture != null && !fixture.equals(afixture))
if (fixture != null && !fixture.equals(afixture)) {
fixture.teardown();
}
fixture = afixture;
fixture.setup();
}
@Parameterized.Parameters(name = "{index}: {0}")
@Parameters(name = "{index}: {0}")
public static Collection<MotorEncoderFixture<?>[]> generateData() {
// logger.fine("Loading the MotorList");
return Arrays.asList(new MotorEncoderFixture<?>[][] { {TestBench.getInstance().getTalonPair()},
return Arrays.asList(new MotorEncoderFixture<?>[][]{{TestBench.getInstance().getTalonPair()},
{TestBench.getInstance().getVictorPair()}, {TestBench.getInstance().getJaguarPair()}});
}
@@ -74,7 +81,7 @@ public class MotorInvertingTest extends AbstractComsSetup {
fixture.getMotor().setInverted(false);
fixture.getMotor().set(motorspeed);
Timer.delay(delaytime);
boolean initDirection = fixture.getEncoder().getDirection();
final boolean initDirection = fixture.getEncoder().getDirection();
fixture.getMotor().setInverted(true);
fixture.getMotor().set(motorspeed);
Timer.delay(delaytime);
@@ -88,7 +95,7 @@ public class MotorInvertingTest extends AbstractComsSetup {
fixture.getMotor().setInverted(false);
fixture.getMotor().set(-motorspeed);
Timer.delay(delaytime);
boolean initDirection = fixture.getEncoder().getDirection();
final boolean initDirection = fixture.getEncoder().getDirection();
fixture.getMotor().setInverted(true);
fixture.getMotor().set(-motorspeed);
Timer.delay(delaytime);
@@ -102,7 +109,7 @@ public class MotorInvertingTest extends AbstractComsSetup {
fixture.getMotor().setInverted(false);
fixture.getMotor().set(motorspeed);
Timer.delay(delaytime);
boolean initDirection = fixture.getEncoder().getDirection();
final boolean initDirection = fixture.getEncoder().getDirection();
fixture.getMotor().setInverted(true);
fixture.getMotor().set(-motorspeed);
Timer.delay(delaytime);
@@ -116,7 +123,7 @@ public class MotorInvertingTest extends AbstractComsSetup {
fixture.getMotor().setInverted(false);
fixture.getMotor().set(-motorspeed);
Timer.delay(delaytime);
boolean initDirection = fixture.getEncoder().getDirection();
final boolean initDirection = fixture.getEncoder().getDirection();
fixture.getMotor().setInverted(true);
fixture.getMotor().set(motorspeed);
Timer.delay(delaytime);

View File

@@ -7,22 +7,23 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.*;
import java.util.concurrent.Delayed;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Kacper Puczydlowski
* Test that covers the {@link Compressor}.
*
* @author Kacper Puczydlowski
*/
public class PCMTest extends AbstractComsSetup {
@@ -48,7 +49,8 @@ public class PCMTest extends AbstractComsSetup {
private static DigitalOutput fakePressureSwitch;
private static AnalogInput fakeCompressor;
private static DigitalInput fakeSolenoid1, fakeSolenoid2;
private static DigitalInput fakeSolenoid1;
private static DigitalInput fakeSolenoid2;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
@@ -72,24 +74,18 @@ public class PCMTest extends AbstractComsSetup {
fakeSolenoid2.free();
}
@Before
public void setUp() throws Exception {}
@Before
public void reset() throws Exception {
compressor.stop();
fakePressureSwitch.set(false);
}
@After
public void tearDown() throws Exception {}
/**
* Test if the compressor turns on and off when the pressure switch is toggled
* Test if the compressor turns on and off when the pressure switch is toggled.
*/
@Test
public void testPressureSwitch() throws Exception {
double range = 0.5;
final double range = 0.1;
reset();
compressor.setClosedLoopControl(true);
@@ -107,7 +103,7 @@ public class PCMTest extends AbstractComsSetup {
}
/**
* Test if the correct solenoids turn on and off when they should
* Test if the correct solenoids turn on and off when they should.
*/
@Test
public void testSolenoid() throws Exception {
@@ -156,8 +152,8 @@ public class PCMTest extends AbstractComsSetup {
}
/**
* Test if the correct solenoids turn on and off when they should when used
* with the DoubleSolenoid class.
* Test if the correct solenoids turn on and off when they should when used with the
* DoubleSolenoid class.
*/
@Test
public void doubleSolenoid() {
@@ -173,13 +169,15 @@ public class PCMTest extends AbstractComsSetup {
Timer.delay(kSolenoidDelayTime);
assertFalse("Solenoid #1 did not turn on", fakeSolenoid1.get());
assertTrue("Solenoid #2 did not turn off", fakeSolenoid2.get());
assertTrue("DoubleSolenoid did not report Forward", (solenoid.get() == DoubleSolenoid.Value.kForward));
assertTrue("DoubleSolenoid did not report Forward", (solenoid.get() == DoubleSolenoid.Value
.kForward));
solenoid.set(DoubleSolenoid.Value.kReverse);
Timer.delay(kSolenoidDelayTime);
assertTrue("Solenoid #1 did not turn off", fakeSolenoid1.get());
assertFalse("Solenoid #2 did not turn on", fakeSolenoid2.get());
assertTrue("DoubleSolenoid did not report Reverse", (solenoid.get() == DoubleSolenoid.Value.kReverse));
assertTrue("DoubleSolenoid did not report Reverse", (solenoid.get() == DoubleSolenoid.Value
.kReverse));
solenoid.free();
}

View File

@@ -7,15 +7,6 @@
package edu.wpi.first.wpilibj;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -24,18 +15,30 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.can.CANMessageNotFoundException;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* Test that covers the {@link PowerDistributionPanel}.
*/
@RunWith(Parameterized.class)
public class PDPTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(PCMTest.class.getName());
private static PowerDistributionPanel pdp;
private static MotorEncoderFixture<?> me;
private final double expectedStoppedCurrentDraw;
private final double m_expectedStoppedCurrentDraw;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
@@ -51,20 +54,22 @@ public class PDPTest extends AbstractComsSetup {
}
@SuppressWarnings("JavadocMethod")
public PDPTest(MotorEncoderFixture<?> mef, Double expectedCurrentDraw) {
logger.fine("Constructor with: " + mef.getType());
if (me != null && !me.equals(mef))
if (me != null && !me.equals(mef)) {
me.teardown();
}
me = mef;
me.setup();
this.expectedStoppedCurrentDraw = expectedCurrentDraw;
m_expectedStoppedCurrentDraw = expectedCurrentDraw;
}
@Parameters(name = "{index}: {0}, Expected Stopped Current Draw: {1}")
public static Collection<Object[]> generateData() {
// logger.fine("Loading the MotorList");
return Arrays.asList(new Object[][] {
return Arrays.asList(new Object[][]{
{TestBench.getInstance().getTalonPair(), new Double(0.0)}});
}
@@ -74,24 +79,23 @@ public class PDPTest extends AbstractComsSetup {
}
/**
* Test if the current changes when the motor is driven using a talon
* Test if the current changes when the motor is driven using a talon.
*/
@Test
public void CheckStoppedCurrentForSpeedController() throws CANMessageNotFoundException {
public void checkStoppedCurrentForSpeedController() throws CANMessageNotFoundException {
Timer.delay(0.25);
/* The Current should be 0 */
assertEquals("The low current was not within the expected range.", expectedStoppedCurrentDraw,
assertEquals("The low current was not within the expected range.", m_expectedStoppedCurrentDraw,
pdp.getCurrent(me.getPDPChannel()), 0.001);
}
/**
* Test if the current changes when the motor is driven using a talon
* Test if the current changes when the motor is driven using a talon.
*/
@Test
public void CheckRunningCurrentForSpeedController() throws CANMessageNotFoundException {
public void checkRunningCurrentForSpeedController() throws CANMessageNotFoundException {
/* Set the motor to full forward */
me.getMotor().set(1.0);
@@ -99,7 +103,7 @@ public class PDPTest extends AbstractComsSetup {
/* The current should now be greater than the low current */
assertThat("The driven current is not greater than the resting current.",
pdp.getCurrent(me.getPDPChannel()), is(greaterThan(expectedStoppedCurrentDraw)));
pdp.getCurrent(me.getPDPChannel()), is(greaterThan(m_expectedStoppedCurrentDraw)));
}
@Override

View File

@@ -7,18 +7,6 @@
package edu.wpi.first.wpilibj;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -28,29 +16,43 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Test that covers the {@link PIDController}.
*
* @author Kacper Puczydlowski
* @author Jonathan Leitschuh
*
*/
@RunWith(Parameterized.class)
public class PIDTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(PIDTest.class.getName());
private NetworkTable table;
private NetworkTable m_table;
private static final double absoluteTolerance = 50;
private static final double outputRange = 0.25;
private PIDController controller = null;
private PIDController m_controller = null;
private static MotorEncoderFixture me = null;
@SuppressWarnings({"MemberName", "EmptyLineSeparator", "MultipleVariableDeclarations"})
private final Double k_p, k_i, k_d;
@Override
@@ -59,10 +61,12 @@ public class PIDTest extends AbstractComsSetup {
}
@SuppressWarnings({"ParameterName", "JavadocMethod"})
public PIDTest(Double p, Double i, Double d, MotorEncoderFixture mef) {
logger.fine("Constructor with: " + mef.getType());
if (PIDTest.me != null && !PIDTest.me.equals(mef))
if (PIDTest.me != null && !PIDTest.me.equals(mef)) {
PIDTest.me.teardown();
}
PIDTest.me = mef;
this.k_p = p;
this.k_i = i;
@@ -78,7 +82,7 @@ public class PIDTest extends AbstractComsSetup {
double ki = 0.0005;
double kd = 0.0;
for (int i = 0; i < 1; i++) {
data.addAll(Arrays.asList(new Object[][] {
data.addAll(Arrays.asList(new Object[][]{
{kp, ki, kd, TestBench.getInstance().getTalonPair()},
{kp, ki, kd, TestBench.getInstance().getVictorPair()},
{kp, ki, kd, TestBench.getInstance().getJaguarPair()}}));
@@ -86,15 +90,10 @@ public class PIDTest extends AbstractComsSetup {
return data;
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
public static void setUpBeforeClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
logger.fine("TearDownAfterClass: " + me.getType());
@@ -102,36 +101,30 @@ public class PIDTest extends AbstractComsSetup {
me = null;
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
logger.fine("Setup: " + me.getType());
me.setup();
table = NetworkTable.getTable("TEST_PID");
controller = new PIDController(k_p, k_i, k_d, me.getEncoder(), me.getMotor());
controller.initTable(table);
m_table = NetworkTable.getTable("TEST_PID");
m_controller = new PIDController(k_p, k_i, k_d, me.getEncoder(), me.getMotor());
m_controller.initTable(m_table);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
logger.fine("Teardown: " + me.getType());
controller.disable();
controller.free();
controller = null;
m_controller.disable();
m_controller.free();
m_controller = null;
me.reset();
}
private void setupAbsoluteTolerance() {
controller.setAbsoluteTolerance(absoluteTolerance);
m_controller.setAbsoluteTolerance(absoluteTolerance);
}
private void setupOutputRange() {
controller.setOutputRange(-outputRange, outputRange);
m_controller.setOutputRange(-outputRange, outputRange);
}
@Test
@@ -139,14 +132,15 @@ public class PIDTest extends AbstractComsSetup {
setupAbsoluteTolerance();
setupOutputRange();
double setpoint = 2500.0;
controller.setSetpoint(setpoint);
assertFalse("PID did not begin disabled", controller.isEnable());
assertEquals("PID.getError() did not start at " + setpoint, setpoint, controller.getError(), 0);
assertEquals(k_p, table.getNumber("p"), 0);
assertEquals(k_i, table.getNumber("i"), 0);
assertEquals(k_d, table.getNumber("d"), 0);
assertEquals(setpoint, table.getNumber("setpoint"), 0);
assertFalse(table.getBoolean("enabled"));
m_controller.setSetpoint(setpoint);
assertFalse("PID did not begin disabled", m_controller.isEnable());
assertEquals("PID.getError() did not start at " + setpoint, setpoint,
m_controller.getError(), 0);
assertEquals(k_p, m_table.getNumber("p"), 0);
assertEquals(k_i, m_table.getNumber("i"), 0);
assertEquals(k_d, m_table.getNumber("d"), 0);
assertEquals(setpoint, m_table.getNumber("setpoint"), 0);
assertFalse(m_table.getBoolean("enabled"));
}
@Test
@@ -154,15 +148,15 @@ public class PIDTest extends AbstractComsSetup {
setupAbsoluteTolerance();
setupOutputRange();
double setpoint = 2500.0;
controller.setSetpoint(setpoint);
controller.enable();
m_controller.setSetpoint(setpoint);
m_controller.enable();
Timer.delay(.5);
assertTrue(table.getBoolean("enabled"));
assertTrue(controller.isEnable());
assertTrue(m_table.getBoolean("enabled"));
assertTrue(m_controller.isEnable());
assertThat(0.0, is(not(me.getMotor().get())));
controller.reset();
assertFalse(table.getBoolean("enabled"));
assertFalse(controller.isEnable());
m_controller.reset();
assertFalse(m_table.getBoolean("enabled"));
assertFalse(m_controller.isEnable());
assertEquals(0, me.getMotor().get(), 0);
}
@@ -171,10 +165,11 @@ public class PIDTest extends AbstractComsSetup {
setupAbsoluteTolerance();
setupOutputRange();
Double setpoint = 2500.0;
controller.disable();
controller.setSetpoint(setpoint);
controller.enable();
assertEquals("Did not correctly set set-point", setpoint, new Double(controller.getSetpoint()));
m_controller.disable();
m_controller.setSetpoint(setpoint);
m_controller.enable();
assertEquals("Did not correctly set set-point", setpoint, new Double(m_controller
.getSetpoint()));
}
@Test(timeout = 10000)
@@ -182,26 +177,26 @@ public class PIDTest extends AbstractComsSetup {
setupAbsoluteTolerance();
setupOutputRange();
double setpoint = 1000.0;
assertEquals(pidData() + "did not start at 0", 0, controller.get(), 0);
controller.setSetpoint(setpoint);
assertEquals(pidData() + "did not start at 0", 0, m_controller.get(), 0);
m_controller.setSetpoint(setpoint);
assertEquals(pidData() + "did not have an error of " + setpoint, setpoint,
controller.getError(), 0);
controller.enable();
m_controller.getError(), 0);
m_controller.enable();
Timer.delay(5);
controller.disable();
assertTrue(pidData() + "Was not on Target. Controller Error: " + controller.getError(),
controller.onTarget());
m_controller.disable();
assertTrue(pidData() + "Was not on Target. Controller Error: " + m_controller.getError(),
m_controller.onTarget());
}
private String pidData() {
return me.getType() + " PID {P:" + controller.getP() + " I:" + controller.getI() + " D:"
+ controller.getD() + "} ";
return me.getType() + " PID {P:" + m_controller.getP() + " I:" + m_controller.getI() + " D:"
+ m_controller.getD() + "} ";
}
@Test(expected = RuntimeException.class)
public void testOnTargetNoToleranceSet() {
setupOutputRange();
controller.onTarget();
m_controller.onTarget();
}
}

View File

@@ -1,88 +1,105 @@
package edu.wpi.first.wpilibj;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PIDToleranceTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(PIDToleranceTest.class.getName());
private PIDController pid;
private final double setPoint = 50.0;
private final double tolerance = 10.0;
private final double range = 200;
private class fakeInput implements PIDSource{
public double val;
public fakeInput(){
val = 0;
}
@Override
public PIDSourceType getPIDSourceType() {
return PIDSourceType.kDisplacement;
}
private static final Logger logger = Logger.getLogger(PIDToleranceTest.class.getName());
private PIDController m_pid;
private final double m_setPoint = 50.0;
private final double m_tolerance = 10.0;
private final double m_range = 200;
@Override
public double pidGet() {
return val;
}
private class FakeInput implements PIDSource {
public double m_val;
@Override
public void setPIDSourceType(PIDSourceType arg0) {}
};
private fakeInput inp;
private PIDOutput out = new PIDOutput(){
@Override
public void pidWrite(double out) {
}
};
@Override
protected Logger getClassLogger() {
return logger;
}
@Before
public void setUp() throws Exception{
inp = new fakeInput();
pid = new PIDController(0.05,0.0,0.0,inp,out);
pid.setInputRange(-range/2, range/2);
}
@After
public void tearDown() throws Exception{
pid.free();
pid = null;
}
@Test
public void testAbsoluteTolerance(){
pid.setAbsoluteTolerance(tolerance);
pid.setSetpoint(setPoint);
pid.enable();
Timer.delay(1);
assertFalse("Error was in tolerance when it should not have been. Error was "+pid.getAvgError(),pid.onTarget());
inp.val = setPoint+tolerance/2;
Timer.delay(1.0);
assertTrue("Error was not in tolerance when it should have been. Error was "+pid.getAvgError(),pid.onTarget());
inp.val = setPoint + 10*tolerance;
Timer.delay(1.0);
assertFalse("Error was in tolerance when it should not have been. Error was "+pid.getAvgError(),pid.onTarget());
}
@Test
public void testPercentTolerance(){
pid.setPercentTolerance(tolerance);
pid.setSetpoint(setPoint);
pid.enable();
assertFalse("Error was in tolerance when it should not have been. Error was "+pid.getAvgError(),pid.onTarget());
inp.val = setPoint+(tolerance)/200*range;//half of percent tolerance away from setPoint
Timer.delay(1.0);
assertTrue("Error was not in tolerance when it should have been. Error was "+pid.getAvgError(),pid.onTarget());
inp.val = setPoint + (tolerance)/50*range;//double percent tolerance away from setPoint
Timer.delay(1.0);
assertFalse("Error was in tolerance when it should not have been. Error was "+pid.getAvgError(),pid.onTarget());
}
public FakeInput() {
m_val = 0;
}
@Override
public PIDSourceType getPIDSourceType() {
return PIDSourceType.kDisplacement;
}
@Override
public double pidGet() {
return m_val;
}
@Override
public void setPIDSourceType(PIDSourceType arg0) {
}
}
private FakeInput m_inp;
private PIDOutput m_out = new PIDOutput() {
@Override
public void pidWrite(double out) {
}
};
@Override
protected Logger getClassLogger() {
return logger;
}
@Before
public void setUp() throws Exception {
m_inp = new FakeInput();
m_pid = new PIDController(0.05, 0.0, 0.0, m_inp, m_out);
m_pid.setInputRange(-m_range / 2, m_range / 2);
}
@After
public void tearDown() throws Exception {
m_pid.free();
m_pid = null;
}
@Test
public void testAbsoluteTolerance() {
m_pid.setAbsoluteTolerance(m_tolerance);
m_pid.setSetpoint(m_setPoint);
m_pid.enable();
Timer.delay(1);
assertFalse("Error was in tolerance when it should not have been. Error was "
+ m_pid.getAvgError(), m_pid.onTarget());
m_inp.m_val = m_setPoint + m_tolerance / 2;
Timer.delay(1.0);
assertTrue("Error was not in tolerance when it should have been. Error was "
+ m_pid.getAvgError(), m_pid.onTarget());
m_inp.m_val = m_setPoint + 10 * m_tolerance;
Timer.delay(1.0);
assertFalse("Error was in tolerance when it should not have been. Error was "
+ m_pid.getAvgError(), m_pid.onTarget());
}
@Test
public void testPercentTolerance() {
m_pid.setPercentTolerance(m_tolerance);
m_pid.setSetpoint(m_setPoint);
m_pid.enable();
assertFalse("Error was in tolerance when it should not have been. Error was "
+ m_pid.getAvgError(), m_pid.onTarget());
//half of percent tolerance away from setPoint
m_inp.m_val = m_setPoint + (m_tolerance) / 200 * m_range;
Timer.delay(1.0);
assertTrue("Error was not in tolerance when it should have been. Error was "
+ m_pid.getAvgError(), m_pid.onTarget());
//double percent tolerance away from setPoint
m_inp.m_val = m_setPoint + (m_tolerance) / 50 * m_range;
Timer.delay(1.0);
assertFalse("Error was in tolerance when it should not have been. Error was "
+ m_pid.getAvgError(), m_pid.onTarget());
}
}

View File

@@ -7,9 +7,8 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
@@ -17,22 +16,24 @@ import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author jonathanleitschuh
* Tests the {@link Preferences}.
*
* @author jonathanleitschuh
*/
public class PreferencesTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(PreferencesTest.class.getName());
private NetworkTable prefTable;
private Preferences pref;
private long check;
private NetworkTable m_prefTable;
private Preferences m_pref;
private long m_check;
@Override
protected Logger getClassLogger() {
@@ -40,9 +41,6 @@ public class PreferencesTest extends AbstractComsSetup {
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
NetworkTable.shutdown();
@@ -55,70 +53,75 @@ public class PreferencesTest extends AbstractComsSetup {
file.createNewFile();
OutputStream output = new FileOutputStream(file);
output
.write("[NetworkTables Storage 3.0]\ndouble \"/Preferences/checkedValueInt\"=2\ndouble \"/Preferences/checkedValueDouble\"=.2\ndouble \"/Preferences/checkedValueFloat\"=3.14\ndouble \"/Preferences/checkedValueLong\"=172\nstring \"/Preferences/checkedValueString\"=\"hello \\nHow are you ?\"\nboolean \"/Preferences/checkedValueBoolean\"=false\n"
.write(("[NetworkTables Storage 3.0]\ndouble \"/Preferences/checkedValueInt\"=2\ndouble "
+ "\"/Preferences/checkedValueDouble\"=.2\ndouble "
+ "\"/Preferences/checkedValueFloat\"=3.14\ndouble "
+ "\"/Preferences/checkedValueLong\"=172\nstring "
+ "\"/Preferences/checkedValueString\"=\"hello \\nHow are you ?\"\nboolean "
+ "\"/Preferences/checkedValueBoolean\"=false\n")
.getBytes());
} catch (IOException e) {
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
NetworkTable.initialize();
pref = Preferences.getInstance();
prefTable = NetworkTable.getTable("Preferences");
check = System.currentTimeMillis();
m_pref = Preferences.getInstance();
m_prefTable = NetworkTable.getTable("Preferences");
m_check = System.currentTimeMillis();
}
public void remove() {
pref.remove("checkedValueLong");
pref.remove("checkedValueDouble");
pref.remove("checkedValueString");
pref.remove("checkedValueInt");
pref.remove("checkedValueFloat");
pref.remove("checkedValueBoolean");
protected void remove() {
m_pref.remove("checkedValueLong");
m_pref.remove("checkedValueDouble");
m_pref.remove("checkedValueString");
m_pref.remove("checkedValueInt");
m_pref.remove("checkedValueFloat");
m_pref.remove("checkedValueBoolean");
}
public void addCheckedValue() {
pref.putLong("checkedValueLong", check);
pref.putDouble("checkedValueDouble", 1);
pref.putString("checkedValueString", "checked");
pref.putInt("checkedValueInt", 1);
pref.putFloat("checkedValueFloat", 1);
pref.putBoolean("checkedValueBoolean", true);
protected void addCheckedValue() {
m_pref.putLong("checkedValueLong", m_check);
m_pref.putDouble("checkedValueDouble", 1);
m_pref.putString("checkedValueString", "checked");
m_pref.putInt("checkedValueInt", 1);
m_pref.putFloat("checkedValueFloat", 1);
m_pref.putBoolean("checkedValueBoolean", true);
}
@Test
public void testAddRemoveSave() {
assertEquals(pref.getLong("checkedValueLong", 0), 172L);
assertEquals(pref.getDouble("checkedValueDouble", 0), .2, 0);
assertEquals(pref.getString("checkedValueString", ""), "hello \nHow are you ?");
assertEquals(pref.getInt("checkedValueInt", 0), 2);
assertEquals(pref.getFloat("checkedValueFloat", 0), 3.14, .001);
assertFalse(pref.getBoolean("checkedValueBoolean", true));
assertEquals(m_pref.getLong("checkedValueLong", 0), 172L);
assertEquals(m_pref.getDouble("checkedValueDouble", 0), .2, 0);
assertEquals(m_pref.getString("checkedValueString", ""), "hello \nHow are you ?");
assertEquals(m_pref.getInt("checkedValueInt", 0), 2);
assertEquals(m_pref.getFloat("checkedValueFloat", 0), 3.14, .001);
assertFalse(m_pref.getBoolean("checkedValueBoolean", true));
remove();
assertEquals(pref.getLong("checkedValueLong", 0), 0);
assertEquals(pref.getDouble("checkedValueDouble", 0), 0, 0);
assertEquals(pref.getString("checkedValueString", ""), "");
assertEquals(pref.getInt("checkedValueInt", 0), 0);
assertEquals(pref.getFloat("checkedValueFloat", 0), 0, 0);
assertFalse(pref.getBoolean("checkedValueBoolean", false));
assertEquals(m_pref.getLong("checkedValueLong", 0), 0);
assertEquals(m_pref.getDouble("checkedValueDouble", 0), 0, 0);
assertEquals(m_pref.getString("checkedValueString", ""), "");
assertEquals(m_pref.getInt("checkedValueInt", 0), 0);
assertEquals(m_pref.getFloat("checkedValueFloat", 0), 0, 0);
assertFalse(m_pref.getBoolean("checkedValueBoolean", false));
addCheckedValue();
pref.save();
assertEquals(check, pref.getLong("checkedValueLong", 0));
assertEquals(pref.getDouble("checkedValueDouble", 0), 1, 0);
assertEquals(pref.getString("checkedValueString", ""), "checked");
assertEquals(pref.getInt("checkedValueInt", 0), 1);
assertEquals(pref.getFloat("checkedValueFloat", 0), 1, 0);
assertTrue(pref.getBoolean("checkedValueBoolean", false));
m_pref.save();
assertEquals(m_check, m_pref.getLong("checkedValueLong", 0));
assertEquals(m_pref.getDouble("checkedValueDouble", 0), 1, 0);
assertEquals(m_pref.getString("checkedValueString", ""), "checked");
assertEquals(m_pref.getInt("checkedValueInt", 0), 1);
assertEquals(m_pref.getFloat("checkedValueFloat", 0), 1, 0);
assertTrue(m_pref.getBoolean("checkedValueBoolean", false));
}
@Test
public void testPreferencesToNetworkTables() {
String networkedNumber = "networkCheckedValue";
int networkNumberValue = 100;
pref.putInt(networkedNumber, networkNumberValue);
assertEquals(networkNumberValue, (int)(prefTable.getNumber(networkedNumber)));
pref.remove(networkedNumber);
m_pref.putInt(networkedNumber, networkNumberValue);
assertEquals(networkNumberValue, (int) (m_prefTable.getNumber(networkedNumber)));
m_pref.remove(networkedNumber);
}
}

View File

@@ -7,18 +7,12 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.wpi.first.wpilibj.Relay.Direction;
import edu.wpi.first.wpilibj.Relay.InvalidValueException;
import edu.wpi.first.wpilibj.Relay.Value;
@@ -27,87 +21,90 @@ import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author jonathanleitschuh
* Tests the {@link RelayCrossConnectFixture}.
*
* @author jonathanleitschuh
*/
public class RelayCrossConnectTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(RelayCrossConnectTest.class.getName());
private static final NetworkTable table = NetworkTable.getTable("_RELAY_CROSS_CONNECT_TEST_");
private RelayCrossConnectFixture relayFixture;
private RelayCrossConnectFixture m_relayFixture;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
relayFixture = TestBench.getRelayCrossConnectFixture();
relayFixture.setup();
relayFixture.getRelay().initTable(table);
m_relayFixture = TestBench.getRelayCrossConnectFixture();
m_relayFixture.setup();
m_relayFixture.getRelay().initTable(table);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
relayFixture.reset();
relayFixture.teardown();
m_relayFixture.reset();
m_relayFixture.teardown();
}
@Test
public void testBothHigh() {
relayFixture.getRelay().setDirection(Direction.kBoth);
relayFixture.getRelay().set(Value.kOn);
relayFixture.getRelay().updateTable();
assertTrue("Input one was not high when relay set both high", relayFixture.getInputOne().get());
assertTrue("Input two was not high when relay set both high", relayFixture.getInputTwo().get());
m_relayFixture.getRelay().setDirection(Direction.kBoth);
m_relayFixture.getRelay().set(Value.kOn);
m_relayFixture.getRelay().updateTable();
assertTrue("Input one was not high when relay set both high", m_relayFixture.getInputOne()
.get());
assertTrue("Input two was not high when relay set both high", m_relayFixture.getInputTwo()
.get());
assertEquals("On", table.getString("Value"));
}
@Test
public void testFirstHigh() {
relayFixture.getRelay().setDirection(Direction.kBoth);
relayFixture.getRelay().set(Value.kForward);
relayFixture.getRelay().updateTable();
assertFalse("Input one was not low when relay set Value.kForward", relayFixture.getInputOne()
m_relayFixture.getRelay().setDirection(Direction.kBoth);
m_relayFixture.getRelay().set(Value.kForward);
m_relayFixture.getRelay().updateTable();
assertFalse("Input one was not low when relay set Value.kForward", m_relayFixture.getInputOne()
.get());
assertTrue("Input two was not high when relay set Value.kForward", relayFixture.getInputTwo()
assertTrue("Input two was not high when relay set Value.kForward", m_relayFixture
.getInputTwo()
.get());
assertEquals("Forward", table.getString("Value"));
}
@Test
public void testSecondHigh() {
relayFixture.getRelay().setDirection(Direction.kBoth);
relayFixture.getRelay().set(Value.kReverse);
relayFixture.getRelay().updateTable();
assertTrue("Input one was not high when relay set Value.kReverse", relayFixture.getInputOne()
m_relayFixture.getRelay().setDirection(Direction.kBoth);
m_relayFixture.getRelay().set(Value.kReverse);
m_relayFixture.getRelay().updateTable();
assertTrue("Input one was not high when relay set Value.kReverse", m_relayFixture.getInputOne()
.get());
assertFalse("Input two was not low when relay set Value.kReverse", relayFixture.getInputTwo()
assertFalse("Input two was not low when relay set Value.kReverse", m_relayFixture
.getInputTwo()
.get());
assertEquals("Reverse", table.getString("Value"));
}
@Test(expected = InvalidValueException.class)
public void testSetValueForwardWithDirectionReverseThrowingException() {
relayFixture.getRelay().setDirection(Direction.kForward);
relayFixture.getRelay().set(Value.kReverse);
m_relayFixture.getRelay().setDirection(Direction.kForward);
m_relayFixture.getRelay().set(Value.kReverse);
}
@Test(expected = InvalidValueException.class)
public void testSetValueReverseWithDirectionForwardThrowingException() {
relayFixture.getRelay().setDirection(Direction.kReverse);
relayFixture.getRelay().set(Value.kForward);
m_relayFixture.getRelay().setDirection(Direction.kReverse);
m_relayFixture.getRelay().set(Value.kForward);
}
@Test
public void testInitialSettings() {
assertEquals(Value.kOff, relayFixture.getRelay().get());
assertEquals(Value.kOff, m_relayFixture.getRelay().get());
// Initially both outputs should be off
assertFalse(relayFixture.getInputOne().get());
assertFalse(relayFixture.getInputTwo().get());
assertFalse(m_relayFixture.getInputOne().get());
assertFalse(m_relayFixture.getInputTwo().get());
assertEquals("Off", table.getString("Value"));
}

View File

@@ -7,27 +7,24 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertTrue;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.fixtures.SampleFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.CANTalon;
import static org.junit.Assert.assertTrue;
/**
* Sample test for a sample PID controller. This demonstrates the general
* pattern of how to create a test and use testing fixtures and categories.
*$
* All tests must extend from {@link AbstractComsSetup} in order to ensure that
* Network Communications are set up before the tests are run.
*$
* Sample test for a sample PID controller. This demonstrates the general pattern of how to create a
* test and use testing fixtures and categories. All tests must extend from {@link
* AbstractComsSetup} in order to ensure that Network Communications are set up before the tests are
* run.
*
* @author Fredric Silberberg
*/
public class SampleTest extends AbstractComsSetup {
@@ -58,8 +55,8 @@ public class SampleTest extends AbstractComsSetup {
}
/**
* This is just a sample test that asserts true. Any traditional junit code
* can be used, these are ordinary junit tests!
* This is just a sample test that asserts true. Any traditional junit code can be used, these are
* ordinary junit tests!
*/
@Test
public void test() {

View File

@@ -7,14 +7,14 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.util.logging.Logger;
import org.junit.Test;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
public class TimerTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(TimerTest.class.getName());

View File

@@ -14,9 +14,10 @@ import org.junit.runners.Suite.SuiteClasses;
import edu.wpi.first.wpilibj.test.AbstractTestSuite;
/**
* @author Jonathan Leitschuh Holds all of the tests in the root wpilibj
* directory Please list alphabetically so that it is easy to determine
* if a test is missing from the list
* Holds all of the tests in the root wpilibj directory. Please list alphabetically so that it is
* easy to determine if a test is missing from the list.
*
* @author Jonathan Leitschuh
*/
@RunWith(Suite.class)
@SuiteClasses({AnalogCrossConnectTest.class, AnalogPotentiometerTest.class,
@@ -25,7 +26,7 @@ import edu.wpi.first.wpilibj.test.AbstractTestSuite;
DIOCrossConnectTest.class, EncoderTest.class, FilterNoiseTest.class,
FilterOutputTest.class, GyroTest.class, MotorEncoderTest.class,
MotorInvertingTest.class, PCMTest.class, PDPTest.class, PIDTest.class,
PIDToleranceTest.class, PreferencesTest.class, RelayCrossConnectTest.class,
PIDToleranceTest.class, PreferencesTest.class, RelayCrossConnectTest.class,
SampleTest.class, TimerTest.class})
public class WpiLibJTestSuite extends AbstractTestSuite {
}

View File

@@ -18,12 +18,10 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
/**
* Provides a base implementation for CAN Tests that forces a test of a
* particular mode to provide tests of a certain type. This also allows for a
* standardized base setup for each test.
*$
* @author jonathanleitschuh
* Provides a base implementation for CAN Tests that forces a test of a particular mode to provide
* tests of a certain type. This also allows for a standardized base setup for each test.
*
* @author jonathanleitschuh
*/
public abstract class AbstractCANTest extends AbstractComsSetup {
public static final double kMotorStopTime = 2;
@@ -36,27 +34,26 @@ public abstract class AbstractCANTest extends AbstractComsSetup {
public static final double kStartupTime = 0.50;
public static final double kEncoderPositionTolerance = .75;
public static final double kPotentiometerPositionTolerance = 10.0 / 360.0; // +/-10
// degrees
// degrees
public static final double kCurrentTolerance = 0.1;
/**
* Stores the status value for the previous test. This is set immediately
* after a failure or success and before the me is torn down.
* Stores the status value for the previous test. This is set immediately after a failure or
* success and before the me is torn down.
*/
private String status = "";
private String m_status = "";
/**
* Extends the default test watcher in order to provide more information about
* a tests failure at runtime.
*$
* @author jonathanleitschuh
* Extends the default test watcher in order to provide more information about a tests failure at
* runtime.
*
* @author jonathanleitschuh
*/
public class CANTestWatcher extends DefaultTestWatcher {
@Override
protected void failed(Throwable e, Description description) {
super.failed(e, description, status);
protected void failed(Throwable exception, Description description) {
super.failed(exception, description, m_status);
}
}
@@ -65,27 +62,29 @@ public abstract class AbstractCANTest extends AbstractComsSetup {
return new CANTestWatcher();
}
/** The Fixture under test */
private CANMotorEncoderFixture me;
/**
* The Fixture under test.
*/
private CANMotorEncoderFixture m_me;
/**
* Retrieves the CANMotorEncoderFixture
*$
* Retrieves the CANMotorEncoderFixture.
*
* @return the CANMotorEncoderFixture for this test.
*/
public CANMotorEncoderFixture getME() {
return me;
return m_me;
}
/**
* This runs BEFORE the setup of the inherited class
* This runs BEFORE the setup of the inherited class.
*/
@Before
public final void preSetup() {
status = "";
me = TestBench.getInstance().getCanJaguarPair();
me.setup();
me.getMotor().setSafetyEnabled(false);
m_status = "";
m_me = TestBench.getInstance().getCanJaguarPair();
m_me.setup();
m_me.getMotor().setSafetyEnabled(false);
}
@After
@@ -93,11 +92,11 @@ public abstract class AbstractCANTest extends AbstractComsSetup {
try {
// Stores the status data before tearing it down.
// If the test fails unexpectedly then this could cause an exception.
status = me.printStatus();
m_status = m_me.printStatus();
} finally {
me.teardown();
m_me.teardown();
}
me = null;
m_me = null;
}
protected void setCANJaguar(double seconds, double value) {

View File

@@ -7,20 +7,21 @@
package edu.wpi.first.wpilibj.can;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
import static org.junit.Assert.assertEquals;
/**
* @author jonathanleitschuh
* Tests the CAN Motor Controller in Current Quad Encoder mode.
*
* @author jonathanleitschuh
*/
public class CANCurrentQuadEncoderModeTest extends AbstractCANTest {
private static Logger logger = Logger.getLogger(CANCurrentQuadEncoderModeTest.class.getName());
@@ -29,7 +30,7 @@ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor()
*/
protected void stopMotor() {
@@ -38,7 +39,7 @@ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward()
*/
protected void runMotorForward() {
@@ -47,7 +48,7 @@ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse()
*/
protected void runMotorReverse() {
@@ -96,7 +97,8 @@ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest {
for (int i = 0; i < 10; i++) {
setCANJaguar(1.0, setpoint);
if (Math.abs(getME().getMotor().getOutputCurrent() - Math.abs(setpoint)) <= kCurrentTolerance) {
if (Math.abs(getME().getMotor().getOutputCurrent() - Math.abs(setpoint))
<= kCurrentTolerance) {
break;
}
}

View File

@@ -7,6 +7,18 @@
package edu.wpi.first.wpilibj.can;
import com.googlecode.junittoolbox.PollingWait;
import com.googlecode.junittoolbox.RunnableAssert;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
@@ -14,25 +26,14 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import com.googlecode.junittoolbox.PollingWait;
import com.googlecode.junittoolbox.RunnableAssert;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
/**
* @author jonathanleitschuh
* The default test set to run against the CAN Motor Controllers.
*
* @author jonathanleitschuh
*/
public class CANDefaultTest extends AbstractCANTest {
private static final Logger logger = Logger.getLogger(CANDefaultTest.class.getName());
private final PollingWait wait = new PollingWait().timeoutAfter(65, TimeUnit.MILLISECONDS)
private final PollingWait m_wait = new PollingWait().timeoutAfter(65, TimeUnit.MILLISECONDS)
.pollEvery(10, TimeUnit.MILLISECONDS);
private static final double kSpikeTime = .5;
@@ -42,9 +43,6 @@ public class CANDefaultTest extends AbstractCANTest {
return logger;
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
getME().getMotor().enableControl();
@@ -55,17 +53,18 @@ public class CANDefaultTest extends AbstractCANTest {
@Test
public void testDefaultGet() {
wait.until(new RunnableAssert("Waiting for CAN Jaguar get to return 0") {
m_wait.until(new RunnableAssert("Waiting for CAN Jaguar get to return 0") {
@Override
public void run() {
assertEquals("CAN Jaguar did not initialize stopped", 0.0, getME().getMotor().get(), .01f);
assertEquals("CAN Jaguar did not initialize stopped", 0.0, getME().getMotor().get(),
.01f);
}
});
}
@Test
public void testDefaultBusVoltage() {
wait.until(new RunnableAssert("Waiting for default bus voltage to be correct") {
m_wait.until(new RunnableAssert("Waiting for default bus voltage to be correct") {
@Override
public void run() {
assertEquals("CAN Jaguar did not start at 14 volts", 14.0f, getME().getMotor()
@@ -76,7 +75,7 @@ public class CANDefaultTest extends AbstractCANTest {
@Test
public void testDefaultOutputVoltage() {
wait.until(new RunnableAssert("Waiting for output voltage to be correct") {
m_wait.until(new RunnableAssert("Waiting for output voltage to be correct") {
@Override
public void run() {
assertEquals("CAN Jaguar did not start with an output voltage of 0", 0.0f, getME()
@@ -87,7 +86,7 @@ public class CANDefaultTest extends AbstractCANTest {
@Test
public void testDefaultOutputCurrent() {
wait.until(new RunnableAssert("Waiting for output current to be correct") {
m_wait.until(new RunnableAssert("Waiting for output current to be correct") {
@Override
public void run() {
assertEquals("CAN Jaguar did not start with an output current of 0", 0.0f, getME()
@@ -99,7 +98,7 @@ public class CANDefaultTest extends AbstractCANTest {
@Test
public void testDefaultTemperature() {
final double room_temp = 18.0f;
wait.until(new RunnableAssert("Waiting for temperature to be correct") {
m_wait.until(new RunnableAssert("Waiting for temperature to be correct") {
@Override
public void run() {
assertThat(
@@ -112,11 +111,12 @@ public class CANDefaultTest extends AbstractCANTest {
@Test
public void testDefaultForwardLimit() {
getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly);
wait.until(new RunnableAssert("Waiting for forward limit to not be set") {
m_wait.until(new RunnableAssert("Waiting for forward limit to not be set") {
@Override
public void run() {
getME().getMotor().set(0);
assertTrue("CAN Jaguar did not start with the Forward Limit Switch Off", getME().getMotor()
assertTrue("CAN Jaguar did not start with the Forward Limit Switch Off", getME()
.getMotor()
.getForwardLimitOK());
}
});
@@ -125,11 +125,12 @@ public class CANDefaultTest extends AbstractCANTest {
@Test
public void testDefaultReverseLimit() {
getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly);
wait.until(new RunnableAssert("Waiting for reverse limit to not be set") {
m_wait.until(new RunnableAssert("Waiting for reverse limit to not be set") {
@Override
public void run() {
getME().getMotor().set(0);
assertTrue("CAN Jaguar did not start with the Reverse Limit Switch Off", getME().getMotor()
assertTrue("CAN Jaguar did not start with the Reverse Limit Switch Off", getME()
.getMotor()
.getReverseLimitOK());
}
});
@@ -137,7 +138,7 @@ public class CANDefaultTest extends AbstractCANTest {
@Test
public void testDefaultNoFaults() {
wait.until(new RunnableAssert("Waiting for no faults") {
m_wait.until(new RunnableAssert("Waiting for no faults") {
@Override
public void run() {
assertEquals("CAN Jaguar initialized with Faults", 0, getME().getMotor().getFaults());
@@ -146,7 +147,6 @@ public class CANDefaultTest extends AbstractCANTest {
}
@Test
public void testFakeLimitSwitchForwards() {
// Given
@@ -165,7 +165,8 @@ public class CANDefaultTest extends AbstractCANTest {
public void run() throws Exception {
getME().getMotor().set(0);
assertFalse(
"Setting the forward limit switch high did not cause the forward limit switch to trigger",
"Setting the forward limit switch high did not cause the forward limit switch to "
+ "trigger",
getME().getMotor().getForwardLimitOK());
}
});
@@ -190,7 +191,8 @@ public class CANDefaultTest extends AbstractCANTest {
public void run() throws Exception {
getME().getMotor().set(0);
assertFalse(
"Setting the reverse limit switch high did not cause the forward limit switch to trigger",
"Setting the reverse limit switch high did not cause the forward limit switch to "
+ "trigger",
getME().getMotor().getReverseLimitOK());
}
});

View File

@@ -7,22 +7,27 @@
package edu.wpi.first.wpilibj.can;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
import static org.junit.Assert.assertTrue;
/**
* Created by Patrick Murphy on 3/30/15.
* Tests the CAN Jaguar inverted.
*
* <p>Created by Patrick Murphy on 3/30/15.
*/
public class CANJaguarInversionTest extends AbstractCANTest {
private static final Logger logger = Logger.getLogger(CANJaguarInversionTest.class.getName());
private static final double motorVoltage = 2.0;
private static final double motorPercent = 0.1;
private static final double motorSpeed = 10;
private static final double delayTime = 0.75;
private static final double speedModeDelayTime = 2.0;
private static final double m_motorVoltage = 2.0;
private static final double m_motorPercent = 0.1;
private static final double m_motorSpeed = 10;
private static final double m_delayTime = 0.75;
private static final double m_speedModeDelayTime = 2.0;
@Override
protected Logger getClassLogger() {
@@ -32,54 +37,52 @@ public class CANJaguarInversionTest extends AbstractCANTest {
@Test
public void testInvertingVoltageMode() {
getME().getMotor().setVoltageMode(CANJaguar.kQuadEncoder, 360);
InversionTest(motorVoltage, delayTime);
inversionTest(m_motorVoltage, m_delayTime);
}
@Test
public void testInvertingPercentMode() {
getME().getMotor().setPercentMode(CANJaguar.kQuadEncoder, 360);
InversionTest(motorPercent, delayTime);
inversionTest(m_motorPercent, m_delayTime);
}
@Test
public void testInvertingSpeedMode() {
getME().getMotor().setSpeedMode(CANJaguar.kQuadEncoder, 360, 0.1, 0.003, 0.01);
InversionTest(motorSpeed, speedModeDelayTime);
inversionTest(m_motorSpeed, m_speedModeDelayTime);
}
/**
* Runs an inversion test To use set the jaguar to the proper
* mode(PercentVbus, voltage, speed)
*$
* @param setpoint the speed/voltage/percent to set the motor to
* @param delayTime the amount of time to delay between starting a motor and
* checking the encoder
* Runs an inversion test To use set the jaguar to the proper mode(PercentVbus, voltage, speed).
*
* @param setPoint the speed/voltage/percent to set the motor to
* @param delayTime the amount of time to delay between starting a motor and checking the encoder
*/
private void InversionTest(double setpoint, double delayTime) {
CANJaguar jag = this.getME().getMotor();
private void inversionTest(double setPoint, double delayTime) {
final CANJaguar jag = getME().getMotor();
jag.enableControl();
jag.setInverted(false);
jag.set(setpoint);
jag.set(setPoint);
Timer.delay(delayTime);
double initialSpeed = jag.getSpeed();
final double initialSpeed = jag.getSpeed();
jag.set(0.0);
jag.setInverted(true);
jag.set(setpoint);
jag.set(setPoint);
Timer.delay(delayTime);
jag.set(0.0);
double finalSpeed = jag.getSpeed();
final double finalSpeed = jag.getSpeed();
assertTrue("Inverting with Positive value does not invert direction",
Math.signum(initialSpeed) != Math.signum(finalSpeed));
jag.set(-setpoint);
jag.set(-setPoint);
Timer.delay(delayTime);
initialSpeed = jag.getSpeed();
final double newInitialSpeed = jag.getSpeed();
jag.set(0.0);
jag.setInverted(false);
jag.set(-setpoint);
jag.set(-setPoint);
Timer.delay(delayTime);
finalSpeed = jag.getSpeed();
final double newFinalSpeed = jag.getSpeed();
jag.set(0.0);
assertTrue("Inverting with Negative value does not invert direction",
Math.signum(initialSpeed) != Math.signum(finalSpeed));
Math.signum(newInitialSpeed) != Math.signum(newFinalSpeed));
}
}

View File

@@ -7,6 +7,20 @@
package edu.wpi.first.wpilibj.can;
import com.googlecode.junittoolbox.PollingWait;
import com.googlecode.junittoolbox.RunnableAssert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
@@ -15,24 +29,12 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.googlecode.junittoolbox.PollingWait;
import com.googlecode.junittoolbox.RunnableAssert;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
/**
* @author jonathanleitschuh
* Tests the CAN motor in PercentQuadEncoderMode.
*
* @author jonathanleitschuh
*/
@SuppressWarnings("AbbreviationAsWordInName")
public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
private static final Logger logger = Logger.getLogger(CANPercentQuadEncoderModeTest.class
.getName());
@@ -41,7 +43,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor()
*/
protected void stopMotor() {
@@ -50,7 +52,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward()
*/
protected void runMotorForward() {
@@ -59,7 +61,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse()
*/
protected void runMotorReverse() {
@@ -148,8 +150,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
}
/**
* Test if we can limit the Jaguar to not rotate forwards when the fake limit
* switch is tripped
* Test if we can limit the Jaguar to not rotate forwards when the fake limit switch is tripped.
*/
@Test
public void shouldNotRotateForwards_WhenFakeLimitSwitchForwardsIsTripped() {
@@ -196,7 +197,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
/**
* Test if we can rotate in reverse when the limit switch
* Test if we can rotate in reverse when the limit switch.
*/
@Test
public void shouldRotateReverse_WhenFakeLimitSwitchForwardsIsTripped() {
@@ -251,8 +252,7 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
}
/**
* Test if we can limit the Jaguar to only moving forwards with a fake limit
* switch.
* Test if we can limit the Jaguar to only moving forwards with a fake limit switch.
*/
@Test
public void shouldNotRotateReverse_WhenFakeLimitSwitchReversesIsTripped() {
@@ -301,9 +301,6 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
* Test if we can limit the Jaguar to only moving forwards with a fake limit
* switch.
*/
/**
*$
*/
@Test
public void shouldRotateForward_WhenFakeLimitSwitchReversesIsTripped() {
// Given
@@ -368,7 +365,8 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
@Override
public boolean getAsBoolean() {
return Math.abs((getME().getMotor().getPosition() - jagInitialPosition)
- (getME().getEncoder().get() - encoderInitialPosition)) < kEncoderPositionTolerance;
- (getME().getEncoder().get() - encoderInitialPosition))
< kEncoderPositionTolerance;
}
});
@@ -391,7 +389,8 @@ public class CANPercentQuadEncoderModeTest extends AbstractCANTest {
@Override
public boolean getAsBoolean() {
return Math.abs((getME().getMotor().getPosition() - jagInitialPosition)
- (getME().getEncoder().get() - encoderInitialPosition)) < kEncoderPositionTolerance;
- (getME().getEncoder().get() - encoderInitialPosition))
< kEncoderPositionTolerance;
}
});
assertEquals(getME().getMotor().getPosition() - jagInitialPosition, getME().getEncoder().get()

View File

@@ -7,28 +7,29 @@
package edu.wpi.first.wpilibj.can;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import com.googlecode.junittoolbox.PollingWait;
import com.googlecode.junittoolbox.RunnableAssert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.googlecode.junittoolbox.PollingWait;
import com.googlecode.junittoolbox.RunnableAssert;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* @author jonathanleitschuh
* Tests the CAN Motor controller in Potentiometer Mode.
*
* @author jonathanleitschuh
*/
public class CANPositionPotentiometerModeTest extends AbstractCANTest {
private static final Logger logger = Logger.getLogger(CANPositionPotentiometerModeTest.class
@@ -41,7 +42,7 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor()
*/
protected void stopMotor() {
@@ -50,7 +51,7 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward()
*/
protected void runMotorForward() {
@@ -59,7 +60,7 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse()
*/
protected void runMotorReverse() {
@@ -85,13 +86,13 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest {
/**
* NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead
* of the one built into the CAN Jaguar
* NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead of the one built
* into the CAN Jaguar.
*/
@Ignore("Encoder is not yet wired to the FPGA")
@Test
public void testRotateForward() {
int initialPosition = getME().getEncoder().get();
final int initialPosition = getME().getEncoder().get();
/* Drive the speed controller briefly to move the encoder */
getME().getMotor().set(kStoppedValue);
Timer.delay(kMotorTimeSettling);
@@ -104,13 +105,13 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest {
}
/**
* NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead
* of the one built into the CAN Jaguar
* NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead of the one built
* into the CAN Jaguar.
*/
@Ignore("Encoder is not yet wired to the FPGA")
@Test
public void testRotateReverse() {
int initialPosition = getME().getEncoder().get();
final int initialPosition = getME().getEncoder().get();
/* Drive the speed controller briefly to move the encoder */
getME().getMotor().set(kStoppedValue);
Timer.delay(kMotorTimeSettling);
@@ -123,8 +124,8 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest {
}
/**
* Test if we can get a position in potentiometer mode, using an analog output
* as a fake potentiometer.
* Test if we can get a position in potentiometer mode, using an analog output as a fake
* potentiometer.
*/
@Test
public void testFakePotentiometerPosition() {
@@ -141,7 +142,8 @@ public class CANPositionPotentiometerModeTest extends AbstractCANTest {
public void run() throws Exception {
getME().getMotor().set(0);
assertEquals(
"CAN Jaguar should have returned the potentiometer position set by the analog output",
"CAN Jaguar should have returned the potentiometer position set by the analog "
+ "output",
getME().getFakePot().getVoltage(), getME().getMotor().getPosition() * 3,
kPotentiometerPositionTolerance * 3);
}

View File

@@ -7,21 +7,22 @@
package edu.wpi.first.wpilibj.can;
import static org.junit.Assert.assertEquals;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
import static org.junit.Assert.assertEquals;
/**
* @author jonathanleitschuh
* Tests the CAN Motor Encoders in QuadEncoder mode.
*
* @author jonathanleitschuh
*/
public class CANPositionQuadEncoderModeTest extends AbstractCANTest {
private static final Logger logger = Logger.getLogger(CANPositionQuadEncoderModeTest.class
@@ -35,7 +36,7 @@ public class CANPositionQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward()
*/
protected void runMotorForward() {
@@ -46,7 +47,7 @@ public class CANPositionQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse()
*/
protected void runMotorReverse() {
@@ -84,8 +85,7 @@ public class CANPositionQuadEncoderModeTest extends AbstractCANTest {
}
/**
* Test if we can set a position and reach that position with PID control on
* the Jaguar.
* Test if we can set a position and reach that position with PID control on the Jaguar.
*/
@Test
public void testEncoderPositionPIDForward() {
@@ -101,8 +101,7 @@ public class CANPositionQuadEncoderModeTest extends AbstractCANTest {
}
/**
* Test if we can set a position and reach that position with PID control on
* the Jaguar.
* Test if we can set a position and reach that position with PID control on the Jaguar.
*/
@Test
public void testEncoderPositionPIDReverse() {

View File

@@ -7,30 +7,35 @@
package edu.wpi.first.wpilibj.can;
import org.junit.Before;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
/**
* @author jonathanleitschuh
* Tests the CAN Speed controllers in quad mode.
*
* @author jonathanleitschuh
*/
public class CANSpeedQuadEncoderModeTest extends AbstractCANTest {
private static final Logger logger = Logger.getLogger(CANPercentQuadEncoderModeTest.class
.getName());
/** The stopped value in rev/min */
/**
* The stopped value in rev/min.
*/
private static final double kStoppedValue = 0;
/** The running value in rev/min */
/**
* The running value in rev/min.
*/
private static final double kRunningValue = 50;
@Override
@@ -49,14 +54,14 @@ public class CANSpeedQuadEncoderModeTest extends AbstractCANTest {
@Test
public void testDefaultSpeed() {
assertEquals("CAN Jaguar did not start with an initial speed of zero", 0.0f, getME().getMotor()
assertEquals("CAN Jaguar did not start with an initial speed of zero", 0.0f, getME()
.getMotor()
.getSpeed(), 0.3f);
}
/**
* Test if we can drive the motor forward in Speed mode and get a position
* back
* Test if we can drive the motor forward in Speed mode and get a position back.
*/
@Test
public void testRotateForwardSpeed() {
@@ -70,8 +75,7 @@ public class CANSpeedQuadEncoderModeTest extends AbstractCANTest {
}
/**
* Test if we can drive the motor backwards in Speed mode and get a position
* back
* Test if we can drive the motor backwards in Speed mode and get a position back.
*/
@Test
public void testRotateReverseSpeed() {
@@ -80,7 +84,8 @@ public class CANSpeedQuadEncoderModeTest extends AbstractCANTest {
setCANJaguar(2 * kMotorTime, speed);
assertEquals("The motor did not reach the required speed in speed mode", speed, getME()
.getMotor().getSpeed(), kEncoderSpeedTolerance);
assertThat("The motor did not move in reverse in speed mode", getME().getMotor().getPosition(),
assertThat("The motor did not move in reverse in speed mode", getME().getMotor()
.getPosition(),
is(lessThan(initialPosition)));
}

View File

@@ -14,8 +14,9 @@ import org.junit.runners.Suite.SuiteClasses;
import edu.wpi.first.wpilibj.test.AbstractTestSuite;
/**
* @author jonathanleitschuh
* All of the tests to cover the CAN Motor Controllers.
*
* @author jonathanleitschuh
*/
@RunWith(Suite.class)
@SuiteClasses({CANCurrentQuadEncoderModeTest.class, CANDefaultTest.class,

View File

@@ -7,34 +7,39 @@
package edu.wpi.first.wpilibj.can;
import com.googlecode.junittoolbox.PollingWait;
import com.googlecode.junittoolbox.RunnableAssert;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import com.googlecode.junittoolbox.PollingWait;
import com.googlecode.junittoolbox.RunnableAssert;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Timer;
/**
* @author jonathanleitschuh
* Tests the CAN motor controllers in voltage mode work correctly.
*
* @author Jonathan Leitschuh
*/
public class CANVoltageQuadEncoderModeTest extends AbstractCANTest {
private static final Logger logger = Logger.getLogger(CANVoltageQuadEncoderModeTest.class
.getName());
/** The stopped value in volts */
/**
* The stopped value in volts.
*/
private static final double kStoppedValue = 0;
/** The running value in volts */
/**
* The running value in volts.
*/
private static final double kRunningValue = 4;
private static final double kVoltageTolerance = .25;
@@ -44,7 +49,7 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor()
*/
protected void stopMotor() {
@@ -53,7 +58,7 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward()
*/
protected void runMotorForward() {
@@ -62,7 +67,7 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse()
*/
protected void runMotorReverse() {
@@ -74,8 +79,11 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest {
return logger;
}
/**
* Sets up the test.
*/
@Before
public void setUp() throws Exception {
public void setUp() {
getME().getMotor().setVoltageMode(CANJaguar.kQuadEncoder, 360);
getME().getMotor().set(kStoppedValue);
getME().getMotor().enableControl();
@@ -100,11 +108,10 @@ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest {
/**
* Sets up the test to have the CANJaguar running at the target voltage
*$
* Sets up the test to have the CANJaguar running at the target voltage.
*
* @param targetValue the target voltage
* @param wait the PollingWait to to use to wait for the setup to complete
* with
* @param wait the PollingWait to to use to wait for the setup to complete with
*/
private void setupMotorVoltageForTest(final double targetValue, PollingWait wait) {
getME().getMotor().enableControl();

View File

@@ -1,9 +1,7 @@
/**
* Provides a suite of tests to cover CANJaguar fully in all different control
* modes and with each supported positional input. Different setup parameters
* are provided in each Test class. All test classes that want to take advantage
* of the default test setup frameworks in place should extend
* {@link edu.wpi.first.wpilibj.can.AbstractCANTest AbstractCANTest}
*$
* Provides a suite of tests to cover CANJaguar fully in all different control modes and with each
* supported positional input. Different setup parameters are provided in each Test class. All test
* classes that want to take advantage of the default test setup frameworks in place should extend
* {@link edu.wpi.first.wpilibj.can.AbstractCANTest AbstractCANTest}.
*/
package edu.wpi.first.wpilibj.can;
package edu.wpi.first.wpilibj.can;

View File

@@ -7,17 +7,18 @@
package edu.wpi.first.wpilibj.command;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Before;
import edu.wpi.first.wpilibj.mocks.MockCommand;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author jonathanleitschuh
* The basic test for all {@link Command} tests.
*
* @author jonathanleitschuh
*/
public abstract class AbstractCommandTest extends AbstractComsSetup {
@@ -28,21 +29,22 @@ public abstract class AbstractCommandTest extends AbstractComsSetup {
}
public class ASubsystem extends Subsystem {
Command command;
Command m_command;
protected void initDefaultCommand() {
if (command != null) {
setDefaultCommand(command);
if (m_command != null) {
setDefaultCommand(m_command);
}
}
public void init(Command command) {
this.command = command;
m_command = command;
}
}
public void assertCommandState(MockCommand command, int initialize, int execute, int isFinished,
int end, int interrupted) {
protected void assertCommandState(MockCommand command, int initialize, int execute,
int isFinished, int end, int interrupted) {
assertEquals(initialize, command.getInitializeCount());
assertEquals(execute, command.getExecuteCount());
assertEquals(isFinished, command.getIsFinishedCount());
@@ -50,7 +52,7 @@ public abstract class AbstractCommandTest extends AbstractComsSetup {
assertEquals(interrupted, command.getInterruptedCount());
}
public void sleep(int time) {
protected void sleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException ex) {

View File

@@ -7,80 +7,58 @@
package edu.wpi.first.wpilibj.command;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.buttons.InternalButton;
import edu.wpi.first.wpilibj.mocks.MockCommand;
/**
* Test that covers the {@link edu.wpi.first.wpilibj.buttons.Button} with the {@link Command}
* library.
*
* @author Mitchell
* @author jonathanleitschuh
*
*/
public class ButtonTest extends AbstractCommandTest {
private static final Logger logger = Logger.getLogger(ButtonTest.class.getName());
private InternalButton button1;
private InternalButton button2;
private InternalButton m_button1;
private InternalButton m_button2;
protected Logger getClassLogger() {
return logger;
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
button1 = new InternalButton();
button2 = new InternalButton();
m_button1 = new InternalButton();
m_button2 = new InternalButton();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
/**
* Simple Button Test
* Simple Button Test.
*/
@Test
public void test() {
MockCommand command1 = new MockCommand();
MockCommand command2 = new MockCommand();
MockCommand command3 = new MockCommand();
MockCommand command4 = new MockCommand();
final MockCommand command1 = new MockCommand();
final MockCommand command2 = new MockCommand();
final MockCommand command3 = new MockCommand();
final MockCommand command4 = new MockCommand();
button1.whenPressed(command1);
button1.whenReleased(command2);
button1.whileHeld(command3);
button2.whileHeld(command4);
m_button1.whenPressed(command1);
m_button1.whenReleased(command2);
m_button1.whileHeld(command3);
m_button2.whileHeld(command4);
assertCommandState(command1, 0, 0, 0, 0, 0);
assertCommandState(command2, 0, 0, 0, 0, 0);
assertCommandState(command3, 0, 0, 0, 0, 0);
assertCommandState(command4, 0, 0, 0, 0, 0);
button1.setPressed(true);
m_button1.setPressed(true);
assertCommandState(command1, 0, 0, 0, 0, 0);
assertCommandState(command2, 0, 0, 0, 0, 0);
assertCommandState(command3, 0, 0, 0, 0, 0);
@@ -100,7 +78,7 @@ public class ButtonTest extends AbstractCommandTest {
assertCommandState(command2, 0, 0, 0, 0, 0);
assertCommandState(command3, 1, 2, 2, 0, 0);
assertCommandState(command4, 0, 0, 0, 0, 0);
button2.setPressed(true);
m_button2.setPressed(true);
Scheduler.getInstance().run();
assertCommandState(command1, 1, 3, 3, 0, 0);
assertCommandState(command2, 0, 0, 0, 0, 0);
@@ -111,7 +89,7 @@ public class ButtonTest extends AbstractCommandTest {
assertCommandState(command2, 0, 0, 0, 0, 0);
assertCommandState(command3, 1, 4, 4, 0, 0);
assertCommandState(command4, 1, 1, 1, 0, 0);
button1.setPressed(false);
m_button1.setPressed(false);
Scheduler.getInstance().run();
assertCommandState(command1, 1, 5, 5, 0, 0);
assertCommandState(command2, 0, 0, 0, 0, 0);
@@ -122,7 +100,7 @@ public class ButtonTest extends AbstractCommandTest {
assertCommandState(command2, 1, 1, 1, 0, 0);
assertCommandState(command3, 1, 4, 4, 0, 1);
assertCommandState(command4, 1, 3, 3, 0, 0);
button2.setPressed(false);
m_button2.setPressed(false);
Scheduler.getInstance().run();
assertCommandState(command1, 1, 7, 7, 0, 0);
assertCommandState(command2, 1, 2, 2, 0, 0);

View File

@@ -7,22 +7,15 @@
package edu.wpi.first.wpilibj.command;
import static org.junit.Assert.*;
import org.junit.Test;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.wpi.first.wpilibj.mocks.MockCommand;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
/**
* Ported from the old CrioTest Classes
*$
* Ported from the old CrioTest Classes.
*
* @author Mitchell
* @author Jonathan Leitschuh
*/
@@ -34,38 +27,14 @@ public class CommandParallelGroupTest extends AbstractCommandTest {
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
/**
* Simple Parallel Command Group With 2 commands one command terminates first
* Simple Parallel Command Group With 2 commands one command terminates first.
*/
@Test
public void testParallelCommandGroupWithTwoCommands() {
MockCommand command1 = new MockCommand();
MockCommand command2 = new MockCommand();
final MockCommand command1 = new MockCommand();
final MockCommand command2 = new MockCommand();
CommandGroup commandGroup = new CommandGroup();
final CommandGroup commandGroup = new CommandGroup();
commandGroup.addParallel(command1);
commandGroup.addParallel(command2);
@@ -97,11 +66,4 @@ public class CommandParallelGroupTest extends AbstractCommandTest {
}
public void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
fail("Sleep Interrupted!?!?!?!?");
}
}
}

View File

@@ -7,21 +7,15 @@
package edu.wpi.first.wpilibj.command;
import static org.junit.Assert.*;
import org.junit.Test;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.wpi.first.wpilibj.mocks.MockCommand;
/**
* Ported from the old CrioTest Classes
*$
* Ported from the old CrioTest Classes.
*
* @author Mitchell
* @author Jonathan Leitschuh
*/
@@ -33,36 +27,11 @@ public class CommandScheduleTest extends AbstractCommandTest {
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
/**
* Simple scheduling of a command and making sure the command is run and
* successfully terminates
* Simple scheduling of a command and making sure the command is run and successfully terminates.
*/
@Test
public void testRunAndTerminate() {
MockCommand command = new MockCommand();
final MockCommand command = new MockCommand();
command.start();
assertCommandState(command, 0, 0, 0, 0, 0);
Scheduler.getInstance().run();
@@ -80,12 +49,11 @@ public class CommandScheduleTest extends AbstractCommandTest {
}
/**
* Simple scheduling of a command and making sure the command is run and
* cancels correctly
* Simple scheduling of a command and making sure the command is run and cancels correctly.
*/
@Test
public void testRunAndCancel() {
MockCommand command = new MockCommand();
final MockCommand command = new MockCommand();
command.start();
assertCommandState(command, 0, 0, 0, 0, 0);
Scheduler.getInstance().run();

View File

@@ -7,20 +7,15 @@
package edu.wpi.first.wpilibj.command;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.mocks.MockCommand;
/**
* Ported from the old CrioTest Classes
*$
* Ported from the old CrioTest Classes.
*
* @author Mitchell
* @author Jonathan Leitschuh
*/
@@ -32,32 +27,8 @@ public class CommandSequentialGroupTest extends AbstractCommandTest {
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
/**
* Simple Command Group With 3 commands that all depend on a subsystem. Some
* commands have a timeout
* Simple Command Group With 3 commands that all depend on a subsystem. Some commands have a
* timeout.
*/
@Test(timeout = 20000)
public void testThreeCommandOnSubSystem() {
@@ -65,26 +36,26 @@ public class CommandSequentialGroupTest extends AbstractCommandTest {
final ASubsystem subsystem = new ASubsystem();
logger.finest("Creating Mock Command1");
MockCommand command1 = new MockCommand() {
final MockCommand command1 = new MockCommand() {
{
requires(subsystem);
}
};
logger.finest("Creating Mock Command2");
MockCommand command2 = new MockCommand() {
final MockCommand command2 = new MockCommand() {
{
requires(subsystem);
}
};
logger.finest("Creating Mock Command3");
MockCommand command3 = new MockCommand() {
final MockCommand command3 = new MockCommand() {
{
requires(subsystem);
}
};
logger.finest("Creating Command Group");
CommandGroup commandGroup = new CommandGroup();
final CommandGroup commandGroup = new CommandGroup();
commandGroup.addSequential(command1, 1.0);
commandGroup.addSequential(command2, 2.0);
commandGroup.addSequential(command3);

View File

@@ -7,19 +7,15 @@
package edu.wpi.first.wpilibj.command;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.mocks.MockCommand;
/**
* Ported from the old CrioTest Classes
*$
* Ported from the old CrioTest Classes.
*
* @author Mitchell
* @author Jonathan Leitschuh
*/
@@ -31,43 +27,19 @@ public class CommandSupersedeTest extends AbstractCommandTest {
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
/**
* Testing one command superseding another because of dependencies
* Testing one command superseding another because of dependencies.
*/
@Test
public void testOneCommandSupersedingAnotherBecauseOfDependencies() {
final ASubsystem subsystem = new ASubsystem();
MockCommand command1 = new MockCommand() {
final MockCommand command1 = new MockCommand() {
{
requires(subsystem);
}
};
MockCommand command2 = new MockCommand() {
final MockCommand command2 = new MockCommand() {
{
requires(subsystem);
}
@@ -108,21 +80,21 @@ public class CommandSupersedeTest extends AbstractCommandTest {
}
/**
* Testing one command failing superseding another because of dependencies
* because the first command cannot be interrupted"
* Testing one command failing superseding another because of dependencies because the first
* command cannot be interrupted.
*/
@Test
public void testCommandFailingSupersedingBecauseFirstCanNotBeInterrupted() {
final ASubsystem subsystem = new ASubsystem();
MockCommand command1 = new MockCommand() {
final MockCommand command1 = new MockCommand() {
{
requires(subsystem);
setInterruptible(false);
}
};
MockCommand command2 = new MockCommand() {
final MockCommand command2 = new MockCommand() {
{
requires(subsystem);
}

View File

@@ -14,8 +14,8 @@ import org.junit.runners.Suite.SuiteClasses;
import edu.wpi.first.wpilibj.test.AbstractTestSuite;
/**
* Contains a listing of all of the {@link Command} tests.
* @author jonathanleitschuh
*
*/
@RunWith(Suite.class)
@SuiteClasses({ButtonTest.class, CommandParallelGroupTest.class, CommandScheduleTest.class,

View File

@@ -7,21 +7,16 @@
package edu.wpi.first.wpilibj.command;
import static org.junit.Assert.*;
import org.junit.Test;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.wpi.first.wpilibj.mocks.MockCommand;
/**
* @author jonathanleitschuh
* Test a {@link Command} that times out.
*
* @author jonathanleitschuh
*/
public class CommandTimeoutTest extends AbstractCommandTest {
private static final Logger logger = Logger.getLogger(CommandTimeoutTest.class.getName());
@@ -31,38 +26,14 @@ public class CommandTimeoutTest extends AbstractCommandTest {
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
/**
* Command 2 second Timeout Test
* Command 2 second Timeout Test.
*/
@Test
public void testTwoSecondTimeout() {
final ASubsystem subsystem = new ASubsystem();
MockCommand command = new MockCommand() {
final MockCommand command = new MockCommand() {
{
requires(subsystem);
setTimeout(2);

View File

@@ -7,21 +7,16 @@
package edu.wpi.first.wpilibj.command;
import static org.junit.Assert.*;
import org.junit.Test;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.wpi.first.wpilibj.mocks.MockCommand;
/**
* @author jonathanleitschuh
* Tests the {@link Command} library.
*
* @author jonathanleitschuh
*/
public class DefaultCommandTest extends AbstractCommandTest {
private static final Logger logger = Logger.getLogger(DefaultCommandTest.class.getName());
@@ -30,45 +25,22 @@ public class DefaultCommandTest extends AbstractCommandTest {
return logger;
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
/**
* Testing of default commands where the interrupting command ends itself
* Testing of default commands where the interrupting command ends itself.
*/
@Test
public void testDefaultCommandWhereTheInteruptingCommandEndsItself() {
final ASubsystem subsystem = new ASubsystem();
MockCommand defaultCommand = new MockCommand() {
final MockCommand defaultCommand = new MockCommand() {
{
requires(subsystem);
}
};
MockCommand anotherCommand = new MockCommand() {
final MockCommand anotherCommand = new MockCommand() {
{
requires(subsystem);
}
@@ -112,20 +84,20 @@ public class DefaultCommandTest extends AbstractCommandTest {
/**
* Testing of default commands where the interrupting command is canceled
* Testing of default commands where the interrupting command is canceled.
*/
@Test
public void testDefaultCommandsInterruptingCommandCanceled() {
final ASubsystem subsystem = new ASubsystem();
MockCommand defaultCommand = new MockCommand() {
final MockCommand defaultCommand = new MockCommand() {
{
requires(subsystem);
}
};
MockCommand anotherCommand = new MockCommand() {
final MockCommand anotherCommand = new MockCommand() {
{
requires(subsystem);
}

View File

@@ -11,45 +11,46 @@ import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.AnalogOutput;
/**
* @author jonathanleitschuh
* A fixture that connects an {@link AnalogInput} and an {@link AnalogOutput}.
*
* @author jonathanleitschuh
*/
public abstract class AnalogCrossConnectFixture implements ITestFixture {
private boolean initialized = false;
private boolean m_initialized = false;
private AnalogInput input;
private AnalogOutput output;
private AnalogInput m_input;
private AnalogOutput m_output;
abstract protected AnalogInput giveAnalogInput();
protected abstract AnalogInput giveAnalogInput();
abstract protected AnalogOutput giveAnalogOutput();
protected abstract AnalogOutput giveAnalogOutput();
private void initialize() {
synchronized (this) {
if (!initialized) {
input = giveAnalogInput();
output = giveAnalogOutput();
initialized = true;
if (!m_initialized) {
m_input = giveAnalogInput();
m_output = giveAnalogOutput();
m_initialized = true;
}
}
}
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup()
*/
@Override
public boolean setup() {
initialize();
output.setVoltage(0);
m_output.setVoltage(0);
return true;
}
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset()
*/
@Override
@@ -60,27 +61,27 @@ public abstract class AnalogCrossConnectFixture implements ITestFixture {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown()
*/
@Override
public boolean teardown() {
input.free();
output.free();
m_input.free();
m_output.free();
return true;
}
/**
* @return Analog Output
* Analog Output.
*/
final public AnalogOutput getOutput() {
public final AnalogOutput getOutput() {
initialize();
return output;
return m_output;
}
final public AnalogInput getInput() {
public final AnalogInput getInput() {
initialize();
return input;
return m_input;
}

View File

@@ -18,18 +18,19 @@ import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.mockhardware.FakePotentiometerSource;
/**
* @author jonathanleitschuh
* A fixture that wraps a {@link CANJaguar}.
*
* @author jonathanleitschuh
*/
public abstract class CANMotorEncoderFixture extends MotorEncoderFixture<CANJaguar> implements
ITestFixture {
private static final Logger logger = Logger.getLogger(CANMotorEncoderFixture.class.getName());
public static final double RELAY_POWER_UP_TIME = .75;
private FakePotentiometerSource potSource;
private DigitalOutput forwardLimit;
private DigitalOutput reverseLimit;
private Relay powerCycler;
private boolean initialized = false;
private FakePotentiometerSource m_potSource;
private DigitalOutput m_forwardLimit;
private DigitalOutput m_reverseLimit;
private Relay m_powerCycler;
private boolean m_initialized = false;
protected abstract FakePotentiometerSource giveFakePotentiometerSource();
@@ -39,24 +40,25 @@ public abstract class CANMotorEncoderFixture extends MotorEncoderFixture<CANJagu
protected abstract Relay givePowerCycleRelay();
public CANMotorEncoderFixture() {}
public CANMotorEncoderFixture() {
}
private void initialize() {
synchronized (this) {
if (!initialized) {
initialized = true;// This ensures it is only initialized once
if (!m_initialized) {
m_initialized = true;// This ensures it is only initialized once
powerCycler = givePowerCycleRelay();
powerCycler.setDirection(Direction.kForward);
m_powerCycler = givePowerCycleRelay();
m_powerCycler.setDirection(Direction.kForward);
logger.fine("Turning on the power!");
powerCycler.set(Value.kForward);
forwardLimit = giveFakeForwardLimit();
reverseLimit = giveFakeReverseLimit();
forwardLimit.set(false);
reverseLimit.set(false);
potSource = giveFakePotentiometerSource();
m_powerCycler.set(Value.kForward);
m_forwardLimit = giveFakeForwardLimit();
m_reverseLimit = giveFakeReverseLimit();
m_forwardLimit.set(false);
m_reverseLimit.set(false);
m_potSource = giveFakePotentiometerSource();
Timer.delay(RELAY_POWER_UP_TIME); // Delay so the relay has time to boot
// up
// up
}
}
}
@@ -71,34 +73,37 @@ public abstract class CANMotorEncoderFixture extends MotorEncoderFixture<CANJagu
@Override
public boolean reset() {
initialize();
potSource.reset();
forwardLimit.set(false);
reverseLimit.set(false);
m_potSource.reset();
m_forwardLimit.set(false);
m_reverseLimit.set(false);
getMotor().setPercentMode(); // Get the Jaguar into a mode where setting the
// speed means stop
// speed means stop
return super.reset();
}
@Override
public boolean teardown() {
boolean wasNull = false;
if (potSource != null) {
potSource.free();
potSource = null;
} else
if (m_potSource != null) {
m_potSource.free();
m_potSource = null;
} else {
wasNull = true;
if (forwardLimit != null) {
forwardLimit.set(false);
forwardLimit.free();
forwardLimit = null;
} else
}
if (m_forwardLimit != null) {
m_forwardLimit.set(false);
m_forwardLimit.free();
m_forwardLimit = null;
} else {
wasNull = true;
if (reverseLimit != null) {
reverseLimit.set(false);
reverseLimit.free();
reverseLimit = null;
} else
}
if (m_reverseLimit != null) {
m_reverseLimit.set(false);
m_reverseLimit.free();
m_reverseLimit = null;
} else {
wasNull = true;
}
boolean superTornDown = false;
try {
superTornDown = super.teardown();
@@ -107,14 +112,16 @@ public abstract class CANMotorEncoderFixture extends MotorEncoderFixture<CANJagu
if (getMotor() != null) {
getMotor().disableControl();
getMotor().free();
} else
} else {
wasNull = true;
}
} finally {
if (powerCycler != null) {
powerCycler.free();
powerCycler = null;
} else
if (m_powerCycler != null) {
m_powerCycler.free();
m_powerCycler = null;
} else {
wasNull = true;
}
}
}
if (wasNull) {
@@ -126,19 +133,22 @@ public abstract class CANMotorEncoderFixture extends MotorEncoderFixture<CANJagu
public FakePotentiometerSource getFakePot() {
initialize();
return potSource;
return m_potSource;
}
public DigitalOutput getForwardLimit() {
initialize();
return forwardLimit;
return m_forwardLimit;
}
public DigitalOutput getReverseLimit() {
initialize();
return reverseLimit;
return m_reverseLimit;
}
/**
* Prints the current status of the fixture.
*/
public String printStatus() {
StringBuilder status = new StringBuilder("CAN Motor Encoder Status: ");
if (getMotor() != null) {
@@ -152,13 +162,13 @@ public abstract class CANMotorEncoderFixture extends MotorEncoderFixture<CANJagu
} else {
status.append("\t" + "CANJaguar Motor = null" + "\n");
}
if (forwardLimit != null) {
status.append("\tForward Limit Output = " + forwardLimit + "\n");
if (m_forwardLimit != null) {
status.append("\tForward Limit Output = " + m_forwardLimit + "\n");
} else {
status.append("\tForward Limit Output = null" + "\n");
}
if (reverseLimit != null) {
status.append("\tReverse Limit Output = " + reverseLimit + "\n");
if (m_reverseLimit != null) {
status.append("\tReverse Limit Output = " + m_reverseLimit + "\n");
} else {
status.append("\tReverse Limit Output = null" + "\n");
}
@@ -166,6 +176,11 @@ public abstract class CANMotorEncoderFixture extends MotorEncoderFixture<CANJagu
return status.toString();
}
/**
* Browns out the fixture for a specific ammount of time.
*
* @param seconds The number of seconds to brown out for.
*/
public void brownOut(double seconds) {
initialize();
powerOff();
@@ -175,12 +190,12 @@ public abstract class CANMotorEncoderFixture extends MotorEncoderFixture<CANJagu
public void powerOff() {
initialize();
powerCycler.set(Value.kOff);
m_powerCycler.set(Value.kOff);
}
public void powerOn() {
initialize();
powerCycler.set(Value.kForward);
m_powerCycler.set(Value.kForward);
}
}

View File

@@ -13,37 +13,54 @@ import java.util.logging.Logger;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DigitalOutput;
/**
* Connects a digital input to a digital output.
*
* @author Jonathan Leitschuh
*/
public class DIOCrossConnectFixture implements ITestFixture {
private static final Logger logger = Logger.getLogger(DIOCrossConnectFixture.class.getName());
private final DigitalInput input;
private final DigitalOutput output;
private final DigitalInput m_input;
private final DigitalOutput m_output;
private boolean m_allocated;
/**
* Constructs using two pre-allocated digital objects.
*
* @param input The input
* @param output The output.
*/
public DIOCrossConnectFixture(DigitalInput input, DigitalOutput output) {
assert input != null;
assert output != null;
this.input = input;
this.output = output;
m_input = input;
m_output = output;
m_allocated = false;
}
/**
* Constructs a {@link DIOCrossConnectFixture} using the ports of the digital objects.
*
* @param input The port of the {@link DigitalInput}
* @param output The port of the {@link DigitalOutput}
*/
public DIOCrossConnectFixture(Integer input, Integer output) {
assert input != null;
assert output != null;
assert !input.equals(output);
this.input = new DigitalInput(input);
this.output = new DigitalOutput(output);
m_input = new DigitalInput(input);
m_output = new DigitalOutput(output);
m_allocated = true;
}
public DigitalInput getInput() {
return input;
return m_input;
}
public DigitalOutput getOutput() {
return output;
return m_output;
}
@Override
@@ -54,11 +71,11 @@ public class DIOCrossConnectFixture implements ITestFixture {
@Override
public boolean reset() {
try {
input.cancelInterrupts();
} catch (IllegalStateException e) {
m_input.cancelInterrupts();
} catch (IllegalStateException ex) {
// This will happen if the interrupt has not been allocated for this test.
}
output.set(false);
m_output.set(false);
return true;
}
@@ -66,8 +83,8 @@ public class DIOCrossConnectFixture implements ITestFixture {
public boolean teardown() {
logger.log(Level.FINE, "Begining teardown");
if (m_allocated) {
input.free();
output.free();
m_input.free();
m_output.free();
m_allocated = false;
}
return true;

View File

@@ -14,66 +14,66 @@ import edu.wpi.first.wpilibj.Counter;
import edu.wpi.first.wpilibj.mockhardware.FakeCounterSource;
/**
* @author jonathanleitschuh
* A fixture that can test the {@link Counter} using a {@link DIOCrossConnectFixture}.
*
* @author jonathanleitschuh
*/
public class FakeCounterFixture implements ITestFixture {
private static final Logger logger = Logger.getLogger(FakeEncoderFixture.class.getName());
private final DIOCrossConnectFixture dio;
private final DIOCrossConnectFixture m_dio;
private boolean m_allocated;
private final FakeCounterSource source;
private final Counter counter;
private final FakeCounterSource m_source;
private final Counter m_counter;
/**
* Constructs a FakeCounterFixture.
*$
* @param dio A previously allocated DIOCrossConnectFixture (must be freed
* outside this class)
*
* @param dio A previously allocated DIOCrossConnectFixture (must be freed outside this class)
*/
public FakeCounterFixture(DIOCrossConnectFixture dio) {
this.dio = dio;
m_dio = dio;
m_allocated = false;
source = new FakeCounterSource(dio.getOutput());
counter = new Counter(dio.getInput());
m_source = new FakeCounterSource(dio.getOutput());
m_counter = new Counter(dio.getInput());
}
/**
* Constructs a FakeCounterFixture using two port numbers
*$
* @param input the input port
* Constructs a FakeCounterFixture using two port numbers.
*
* @param input the input port
* @param output the output port
*/
public FakeCounterFixture(int input, int output) {
this.dio = new DIOCrossConnectFixture(input, output);
m_dio = new DIOCrossConnectFixture(input, output);
m_allocated = true;
source = new FakeCounterSource(dio.getOutput());
counter = new Counter(dio.getInput());
m_source = new FakeCounterSource(m_dio.getOutput());
m_counter = new Counter(m_dio.getInput());
}
/**
* Retrieves the FakeCouterSource for use
*$
* Retrieves the FakeCouterSource for use.
*
* @return the FakeCounterSource
*/
public FakeCounterSource getFakeCounterSource() {
return source;
return m_source;
}
/**
* Gets the Counter for use
*$
* Gets the Counter for use.
*
* @return the Counter
*/
public Counter getCounter() {
return counter;
return m_counter;
}
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup()
*/
@Override
@@ -84,32 +84,31 @@ public class FakeCounterFixture implements ITestFixture {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset()
*/
@Override
public boolean reset() {
counter.reset();
m_counter.reset();
return true;
}
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown()
*/
@Override
public boolean teardown() {
logger.log(Level.FINE, "Begining teardown");
counter.free();
source.free();
m_counter.free();
m_source.free();
if (m_allocated) { // Only tear down the dio if this class allocated it
dio.teardown();
m_dio.teardown();
m_allocated = false;
}
return true;
}
}

View File

@@ -7,15 +7,16 @@
package edu.wpi.first.wpilibj.fixtures;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.mockhardware.FakeEncoderSource;
/**
* @author jonathanleitschuh
* An encoder that uses two {@link DIOCrossConnectFixture DIOCrossConnectFixtures} to test the
* {@link Encoder}.
*
* @author jonathanleitschuh
*/
public class FakeEncoderFixture implements ITestFixture {
private static final Logger logger = Logger.getLogger(FakeEncoderFixture.class.getName());
@@ -25,33 +26,25 @@ public class FakeEncoderFixture implements ITestFixture {
private boolean m_allocated;
private final FakeEncoderSource m_source;
private int m_sourcePort[] = new int[2];
private int[] m_sourcePort = new int[2];
private final Encoder m_encoder;
private int m_encoderPort[] = new int[2];
private int[] m_encoderPort = new int[2];
/**
* Constructs a FakeEncoderFixture from two DIOCrossConnectFixture
*$
* @param dio1
* @param dio2
* Constructs a FakeEncoderFixture from two DIOCrossConnectFixture.
*/
public FakeEncoderFixture(DIOCrossConnectFixture dio1, DIOCrossConnectFixture dio2) {
assert dio1 != null;
assert dio2 != null;
this.m_dio1 = dio1;
this.m_dio2 = dio2;
m_dio1 = dio1;
m_dio2 = dio2;
m_allocated = false;
m_source = new FakeEncoderSource(dio1.getOutput(), dio2.getOutput());
m_encoder = new Encoder(dio1.getInput(), dio2.getInput());
}
/**
* Construcst a FakeEncoderFixture from a set of Digital I/O ports
*$
* @param inputA
* @param outputA
* @param inputB
* @param outputB
* Construcst a FakeEncoderFixture from a set of Digital I/O ports.
*/
public FakeEncoderFixture(int inputA, int outputA, int inputB, int outputB) {
assert outputA != outputB;
@@ -60,8 +53,8 @@ public class FakeEncoderFixture implements ITestFixture {
assert outputB != inputA;
assert outputB != inputB;
assert inputA != inputB;
this.m_dio1 = new DIOCrossConnectFixture(inputA, outputA);
this.m_dio2 = new DIOCrossConnectFixture(inputB, outputB);
m_dio1 = new DIOCrossConnectFixture(inputA, outputA);
m_dio2 = new DIOCrossConnectFixture(inputB, outputB);
m_allocated = true;
m_sourcePort[0] = outputA;
m_sourcePort[1] = outputB;
@@ -81,7 +74,7 @@ public class FakeEncoderFixture implements ITestFixture {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup()
*/
@Override
@@ -91,7 +84,7 @@ public class FakeEncoderFixture implements ITestFixture {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset()
*/
@Override
@@ -104,7 +97,7 @@ public class FakeEncoderFixture implements ITestFixture {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown()
*/
@Override

View File

@@ -8,48 +8,45 @@
package edu.wpi.first.wpilibj.fixtures;
import java.lang.reflect.ParameterizedType;
import java.util.logging.Logger;
import java.util.Random;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.PIDSourceType;
import edu.wpi.first.wpilibj.test.TestBench;
/**
* Represents a physically connected Motor and Encoder to allow for unit tests
* on these different pairs<br>
* Designed to allow the user to easily setup and tear down the fixture to allow
* for reuse. This class should be explicitly instantiated in the TestBed class
* to allow any test to access this fixture. This allows tests to be mailable so
* that you can easily reconfigure the physical testbed without breaking the
* tests.
* Represents a physically connected Motor and Encoder to allow for unit tests on these different
* pairs<br> Designed to allow the user to easily setup and tear down the fixture to allow for
* reuse. This class should be explicitly instantiated in the TestBed class to allow any test to
* access this fixture. This allows tests to be mailable so that you can easily reconfigure the
* physical testbed without breaking the tests.
*/
public abstract class FilterNoiseFixture<T extends PIDSource> implements ITestFixture {
private static final Logger logger = Logger.getLogger(FilterNoiseFixture.class.getName());
private boolean initialized = false;
private boolean tornDown = false;
protected T filter;
private NoiseGenerator data;
private boolean m_initialized = false;
private boolean m_tornDown = false;
protected T m_filter;
private NoiseGenerator m_data;
/**
* Where the implementer of this class should pass the filter constructor
*$
* @return
* Where the implementer of this class should pass the filter constructor.
*/
abstract protected T giveFilter(PIDSource source);
protected abstract T giveFilter(PIDSource source);
final private void initialize() {
private void initialize() {
synchronized (this) {
if (!initialized) {
initialized = true; // This ensures it is only initialized once
if (!m_initialized) {
m_initialized = true; // This ensures it is only initialized once
data = new NoiseGenerator(TestBench.kStdDev) {
m_data = new NoiseGenerator(TestBench.kStdDev) {
@Override
@SuppressWarnings("ParameterName")
public double getData(double t) {
return 100.0 * Math.sin(2.0 * Math.PI * t);
}
};
filter = giveFilter(data);
m_filter = giveFilter(m_data);
}
}
}
@@ -61,33 +58,33 @@ public abstract class FilterNoiseFixture<T extends PIDSource> implements ITestFi
}
/**
* Gets the filter for this Object
*$
* Gets the filter for this Object.
*
* @return the filter this object refers too
*/
public T getFilter() {
initialize();
return filter;
return m_filter;
}
/**
* Gets the noise generator for this object
*$
* Gets the noise generator for this object.
*
* @return the noise generator that this object refers too
*/
public NoiseGenerator getNoiseGenerator() {
initialize();
return data;
return m_data;
}
/**
* Retrieves the name of the filter that this object refers to
*$
* Retrieves the name of the filter that this object refers to.
*
* @return The simple name of the filter {@link Class#getSimpleName()}
*/
public String getType() {
initialize();
return filter.getClass().getSimpleName();
return m_filter.getClass().getSimpleName();
}
// test here?
@@ -108,61 +105,55 @@ public abstract class FilterNoiseFixture<T extends PIDSource> implements ITestFi
// Get the generic type as a class
@SuppressWarnings("unchecked")
Class<T> class1 =
(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
string.append(class1.getSimpleName());
string.append(">");
return string.toString();
}
/**
* Adds Gaussian white noise to a function returning data. The noise will have
* the standard deviation provided in the constructor.
* Adds Gaussian white noise to a function returning data. The noise will have the standard
* deviation provided in the constructor.
*/
public abstract class NoiseGenerator implements PIDSource {
private double noise = 0.0;
private double m_noise = 0.0;
// Make sure first call to pidGet() uses count == 0
private double count = -TestBench.kFilterStep;
private double m_count = -TestBench.kFilterStep;
private double stdDev;
private Random gen = new Random();
private double m_stdDev;
private Random m_gen = new Random();
NoiseGenerator(double stdDev) {
this.stdDev = stdDev;
m_stdDev = stdDev;
}
abstract public double getData(double t);
@SuppressWarnings("ParameterName")
public abstract double getData(double t);
/**
* {@inheritDoc}
*/
@Override
public void setPIDSourceType(PIDSourceType pidSource) {}
public void setPIDSourceType(PIDSourceType pidSource) {
}
/**
* {@inheritDoc}
*/
@Override
public PIDSourceType getPIDSourceType() {
return PIDSourceType.kDisplacement;
}
public double get() {
return getData(count) + noise;
return getData(m_count) + m_noise;
}
/**
* {@inheritDoc}
*/
@Override
public double pidGet() {
noise = gen.nextGaussian() * stdDev;
count += TestBench.kFilterStep;
return getData(count) + noise;
m_noise = m_gen.nextGaussian() * m_stdDev;
m_count += TestBench.kFilterStep;
return getData(m_count) + m_noise;
}
public void reset() {
count = -TestBench.kFilterStep;
m_count = -TestBench.kFilterStep;
}
}
}

View File

@@ -15,52 +15,49 @@ import edu.wpi.first.wpilibj.PIDSourceType;
import edu.wpi.first.wpilibj.test.TestBench;
/**
* Represents a filterphysically connected Motor and Encoder to allow for unit tests
* on these different pairs<br>
* Designed to allow the user to easily setup and tear down the fixture to allow
* for reuse. This class should be explicitly instantiated in the TestBed class
* to allow any test to access this fixture. This allows tests to be mailable so
* that you can easily reconfigure the physical testbed without breaking the
* tests.
* Represents a filterphysically connected Motor and Encoder to allow for unit tests on these
* different pairs<br> Designed to allow the user to easily setup and tear down the fixture to allow
* for reuse. This class should be explicitly instantiated in the TestBed class to allow any test to
* access this fixture. This allows tests to be mailable so that you can easily reconfigure the
* physical testbed without breaking the tests.
*/
public abstract class FilterOutputFixture<T extends PIDSource> implements ITestFixture {
private static final Logger logger = Logger.getLogger(FilterOutputFixture.class.getName());
private boolean initialized = false;
private boolean tornDown = false;
protected T filter;
private DataWrapper data;
private double expectedOutput;
private boolean m_initialized = false;
private boolean m_tornDown = false;
protected T m_filter;
private DataWrapper m_data;
private double m_expectedOutput;
public FilterOutputFixture(double expectedOutput) {
this.expectedOutput = expectedOutput;
m_expectedOutput = expectedOutput;
}
/**
* Get expected output of fixture
* Get expected output of fixture.
*/
public double getExpectedOutput() {
return expectedOutput;
return m_expectedOutput;
}
/**
* Where the implementer of this class should pass the filter constructor
*$
* @return
* Where the implementer of this class should pass the filter constructor.
*/
abstract protected T giveFilter(PIDSource source);
protected abstract T giveFilter(PIDSource source);
final private void initialize() {
private void initialize() {
synchronized (this) {
if (!initialized) {
initialized = true; // This ensures it is only initialized once
if (!m_initialized) {
m_initialized = true; // This ensures it is only initialized once
data = new DataWrapper() {
m_data = new DataWrapper() {
@Override
@SuppressWarnings("ParameterName")
public double getData(double t) {
return 100.0 * Math.sin(2.0 * Math.PI * t) + 20.0 * Math.cos(50.0 * Math.PI * t);
}
};
filter = giveFilter(data);
m_filter = giveFilter(m_data);
}
}
}
@@ -72,38 +69,38 @@ public abstract class FilterOutputFixture<T extends PIDSource> implements ITestF
}
/**
* Gets the filter for this Object
*$
* Gets the filter for this Object.
*
* @return the filter this object refers too
*/
public T getFilter() {
initialize();
return filter;
return m_filter;
}
/**
* Gets the data wrapper for this object
*$
* Gets the data wrapper for this object.
*
* @return the data wrapper that this object refers too
*/
public DataWrapper getDataWrapper() {
initialize();
return data;
return m_data;
}
/**
* Retrieves the name of the filter that this object refers to
*$
* Retrieves the name of the filter that this object refers to.
*
* @return The simple name of the filter {@link Class#getSimpleName()}
*/
public String getType() {
initialize();
return filter.getClass().getSimpleName();
return m_filter.getClass().getSimpleName();
}
@Override
public boolean reset() {
data.reset();
m_data.reset();
return true;
}
@@ -118,7 +115,8 @@ public abstract class FilterOutputFixture<T extends PIDSource> implements ITestF
// Get the generic type as a class
@SuppressWarnings("unchecked")
Class<T> class1 =
(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
string.append(class1.getSimpleName());
string.append(">");
return string.toString();
@@ -126,35 +124,31 @@ public abstract class FilterOutputFixture<T extends PIDSource> implements ITestF
public abstract class DataWrapper implements PIDSource {
// Make sure first call to pidGet() uses count == 0
private double count = -TestBench.kFilterStep;
private double m_count = -TestBench.kFilterStep;
abstract public double getData(double t);
@SuppressWarnings("ParameterName")
public abstract double getData(double t);
/**
* {@inheritDoc}
*/
@Override
public void setPIDSourceType(PIDSourceType pidSource) {}
public void setPIDSourceType(PIDSourceType pidSource) {
}
/**
* {@inheritDoc}
*/
@Override
public PIDSourceType getPIDSourceType() {
return PIDSourceType.kDisplacement;
}
/**
* {@inheritDoc}
*/
@Override
public double pidGet() {
count += TestBench.kFilterStep;
return getData(count);
m_count += TestBench.kFilterStep;
return getData(m_count);
}
public void reset() {
count = -TestBench.kFilterStep;
m_count = -TestBench.kFilterStep;
}
}
}

View File

@@ -10,44 +10,40 @@ package edu.wpi.first.wpilibj.fixtures;
import edu.wpi.first.wpilibj.test.TestBench;
/**
* Master interface for all test fixtures. This ensures that all test fixtures
* have setup and teardown methods, to ensure that the tests run properly.
*$
* Test fixtures should be modeled around the content of a test, rather than the
* actual physical layout of the testing board. They should obtain references to
* hardware from the {@link TestBench} class, which is a singleton. Testing
* Fixtures are responsible for ensuring that the hardware is in an appropriate
* state for the start of a test, and ensuring that future tests will not be
* affected by the results of a test.
*$
* Master interface for all test fixtures. This ensures that all test fixtures have setup and
* teardown methods, to ensure that the tests run properly. Test fixtures should be modeled around
* the content of a test, rather than the actual physical layout of the testing board. They should
* obtain references to hardware from the {@link TestBench} class, which is a singleton. Testing
* Fixtures are responsible for ensuring that the hardware is in an appropriate state for the start
* of a test, and ensuring that future tests will not be affected by the results of a test.
*
* @author Fredric Silberberg
*/
public interface ITestFixture {
/**
* Performs any required setup for this fixture, ensuring that all fixture
* elements are ready for testing.
*$
* Performs any required setup for this fixture, ensuring that all fixture elements are ready for
* testing.
*
* @return True if the fixture is ready for testing
*/
boolean setup();
/**
* Resets the fixture back to test start state. This should be called by the
* test class in the test setup method to ensure that the hardware is in the
* default state. This differs from {@link ITestFixture#setup()} as that is
* called once, before the class is constructed, so it may need to start
* sensors. This method should not have to start anything, just reset sensors
* and ensure that motors are stopped.
*$
* Resets the fixture back to test start state. This should be called by the test class in the
* test setup method to ensure that the hardware is in the default state. This differs from {@link
* ITestFixture#setup()} as that is called once, before the class is constructed, so it may need
* to start sensors. This method should not have to start anything, just reset sensors and ensure
* that motors are stopped.
*
* @return True if the fixture is ready for testing
*/
boolean reset();
/**
* Performs any required teardown after use of the fixture, ensuring that
* future tests will not run into conflicts.
*$
* Performs any required teardown after use of the fixture, ensuring that future tests will not
* run into conflicts.
*
* @return True if the teardown succeeded
*/
boolean teardown();

View File

@@ -19,74 +19,74 @@ import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.test.TestBench;
/**
* Represents a physically connected Motor and Encoder to allow for unit tests
* on these different pairs<br>
* Designed to allow the user to easily setup and tear down the fixture to allow
* for reuse. This class should be explicitly instantiated in the TestBed class
* to allow any test to access this fixture. This allows tests to be mailable so
* that you can easily reconfigure the physical testbed without breaking the
* tests.
* Represents a physically connected Motor and Encoder to allow for unit tests on these different
* pairs<br> Designed to allow the user to easily setup and tear down the fixture to allow for
* reuse. This class should be explicitly instantiated in the TestBed class to allow any test to
* access this fixture. This allows tests to be mailable so that you can easily reconfigure the
* physical testbed without breaking the tests.
*
* @author Jonathan Leitschuh
*
*/
public abstract class MotorEncoderFixture<T extends SpeedController> implements ITestFixture {
private static final Logger logger = Logger.getLogger(MotorEncoderFixture.class.getName());
private boolean initialized = false;
private boolean tornDown = false;
protected T motor;
private Encoder encoder;
private final Counter counters[] = new Counter[2];
protected DigitalInput aSource; // Stored so it can be freed at tear down
protected DigitalInput bSource;
private boolean m_initialized = false;
private boolean m_tornDown = false;
protected T m_motor;
private Encoder m_encoder;
private final Counter[] m_counters = new Counter[2];
protected DigitalInput m_alphaSource; // Stored so it can be freed at tear down
protected DigitalInput m_betaSource;
/**
* Default constructor for a MotorEncoderFixture
* Default constructor for a MotorEncoderFixture.
*/
public MotorEncoderFixture() {}
public MotorEncoderFixture() {
}
abstract public int getPDPChannel();
public abstract int getPDPChannel();
/**
* Where the implementer of this class should pass the speed controller
* Constructor should only be called from outside this class if the Speed
* controller is not also an implementation of PWM interface
*$
* Where the implementer of this class should pass the speed controller Constructor should only be
* called from outside this class if the Speed controller is not also an implementation of PWM
* interface.
*
* @return SpeedController
*/
abstract protected T giveSpeedController();
protected abstract T giveSpeedController();
/**
* Where the implementer of this class should pass one of the digital inputs<br>
* CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS!
*$
* Where the implementer of this class should pass one of the digital inputs.
*
* <p>CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS!
*
* @return DigitalInput
*/
abstract protected DigitalInput giveDigitalInputA();
protected abstract DigitalInput giveDigitalInputA();
/**
* Where the implementer fo this class should pass the other digital input<br>
* CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS!
*$
* Where the implementer fo this class should pass the other digital input.
*
* <p>CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS!
*
* @return Input B to be used when this class is instantiated
*/
abstract protected DigitalInput giveDigitalInputB();
protected abstract DigitalInput giveDigitalInputB();
final private void initialize() {
private final void initialize() {
synchronized (this) {
if (!initialized) {
initialized = true; // This ensures it is only initialized once
if (!m_initialized) {
m_initialized = true; // This ensures it is only initialized once
aSource = giveDigitalInputA();
bSource = giveDigitalInputB();
m_alphaSource = giveDigitalInputA();
m_betaSource = giveDigitalInputB();
encoder = new Encoder(aSource, bSource);
counters[0] = new Counter(aSource);
counters[1] = new Counter(bSource);
m_encoder = new Encoder(m_alphaSource, m_betaSource);
m_counters[0] = new Counter(m_alphaSource);
m_counters[1] = new Counter(m_betaSource);
logger.fine("Creating the speed controller!");
motor = giveSpeedController(); // CANJaguar throws an exception if it
// doesn't get the message
m_motor = giveSpeedController(); // CANJaguar throws an exception if it
// doesn't get the message
}
}
}
@@ -98,70 +98,68 @@ public abstract class MotorEncoderFixture<T extends SpeedController> implements
}
/**
* Gets the motor for this Object
*$
* Gets the motor for this Object.
*
* @return the motor this object refers too
*/
public T getMotor() {
initialize();
return motor;
return m_motor;
}
/**
* Gets the encoder for this object
*$
* Gets the encoder for this object.
*
* @return the encoder that this object refers too
*/
public Encoder getEncoder() {
initialize();
return encoder;
return m_encoder;
}
public Counter[] getCounters() {
initialize();
return counters;
return m_counters;
}
/**
* Retrieves the name of the motor that this object refers to
*$
* Retrieves the name of the motor that this object refers to.
*
* @return The simple name of the motor {@link Class#getSimpleName()}
*/
public String getType() {
initialize();
return motor.getClass().getSimpleName();
return m_motor.getClass().getSimpleName();
}
/**
* Checks to see if the speed of the motor is within some range of a given
* value. This is used instead of equals() because doubles can have
* inaccuracies.
*$
* @param value The value to compare against
* Checks to see if the speed of the motor is within some range of a given value. This is used
* instead of equals() because doubles can have inaccuracies.
*
* @param value The value to compare against
* @param accuracy The accuracy range to check against to see if the
* @return true if the range of values between motors speed accuracy contains
* the 'value'.
* @return true if the range of values between motors speed accuracy contains the 'value'.
*/
public boolean isMotorSpeedWithinRange(double value, double accuracy) {
initialize();
return Math.abs((Math.abs(motor.get()) - Math.abs(value))) < Math.abs(accuracy);
return Math.abs((Math.abs(m_motor.get()) - Math.abs(value))) < Math.abs(accuracy);
}
@Override
public boolean reset() {
initialize();
boolean wasReset = true;
motor.setInverted(false);
motor.set(0);
m_motor.setInverted(false);
m_motor.set(0);
Timer.delay(TestBench.MOTOR_STOP_TIME); // DEFINED IN THE TestBench
encoder.reset();
for (Counter c : counters) {
m_encoder.reset();
for (Counter c : m_counters) {
c.reset();
}
wasReset = wasReset && motor.get() == 0;
wasReset = wasReset && encoder.get() == 0;
for (Counter c : counters) {
boolean wasReset = true;
wasReset = wasReset && m_motor.get() == 0;
wasReset = wasReset && m_encoder.get() == 0;
for (Counter c : m_counters) {
wasReset = wasReset && c.get() == 0;
}
@@ -169,54 +167,59 @@ public abstract class MotorEncoderFixture<T extends SpeedController> implements
}
/**
* Safely tears down the MotorEncoder Fixture in a way that makes sure that
* even if an object fails to initialize the rest of the fixture can still be
* torn down and the resources deallocated
* Safely tears down the MotorEncoder Fixture in a way that makes sure that even if an object
* fails to initialize the rest of the fixture can still be torn down and the resources
* deallocated.
*/
@Override
public boolean teardown() {
String type;
if (motor != null) {
if (m_motor != null) {
type = getType();
} else {
type = "null";
}
if (!tornDown) {
if (!m_tornDown) {
boolean wasNull = false;
if (motor instanceof PWM && motor != null) {
((PWM) motor).free();
motor = null;
} else if (motor == null)
if (m_motor instanceof PWM && m_motor != null) {
((PWM) m_motor).free();
m_motor = null;
} else if (m_motor == null) {
wasNull = true;
if (encoder != null) {
encoder.free();
encoder = null;
} else
}
if (m_encoder != null) {
m_encoder.free();
m_encoder = null;
} else {
wasNull = true;
if (counters[0] != null) {
counters[0].free();
counters[0] = null;
} else
}
if (m_counters[0] != null) {
m_counters[0].free();
m_counters[0] = null;
} else {
wasNull = true;
if (counters[1] != null) {
counters[1].free();
counters[1] = null;
} else
}
if (m_counters[1] != null) {
m_counters[1].free();
m_counters[1] = null;
} else {
wasNull = true;
if (aSource != null) {
aSource.free();
aSource = null;
} else
}
if (m_alphaSource != null) {
m_alphaSource.free();
m_alphaSource = null;
} else {
wasNull = true;
if (bSource != null) {
bSource.free();
bSource = null;
} else
}
if (m_betaSource != null) {
m_betaSource.free();
m_betaSource = null;
} else {
wasNull = true;
}
tornDown = true;
m_tornDown = true;
if (wasNull) {
throw new NullPointerException("MotorEncoderFixture had null params at teardown");
@@ -234,7 +237,8 @@ public abstract class MotorEncoderFixture<T extends SpeedController> implements
// Get the generic type as a class
@SuppressWarnings("unchecked")
Class<T> class1 =
(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
string.append(class1.getSimpleName());
string.append(">");
return string.toString();

View File

@@ -9,22 +9,19 @@ package edu.wpi.first.wpilibj.fixtures;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.Relay.Direction;
import edu.wpi.first.wpilibj.Relay.Value;
/**
* A connection between a {@link Relay} and two {@link DigitalInput DigitalInputs}.
* @author jonathanleitschuh
*
*/
public abstract class RelayCrossConnectFixture implements ITestFixture {
private DigitalInput inputOne;
private DigitalInput inputTwo;
private Relay relay;
private boolean initialized = false;
private boolean freed = false;
private DigitalInput m_inputOne;
private DigitalInput m_inputTwo;
private Relay m_relay;
private boolean m_initialized = false;
private boolean m_freed = false;
protected abstract Relay giveRelay();
@@ -35,33 +32,33 @@ public abstract class RelayCrossConnectFixture implements ITestFixture {
private void initialize() {
synchronized (this) {
if (!initialized) {
relay = giveRelay();
inputOne = giveInputOne();
inputTwo = giveInputTwo();
initialized = true;
if (!m_initialized) {
m_relay = giveRelay();
m_inputOne = giveInputOne();
m_inputTwo = giveInputTwo();
m_initialized = true;
}
}
}
public Relay getRelay() {
initialize();
return relay;
return m_relay;
}
public DigitalInput getInputOne() {
initialize();
return inputOne;
return m_inputOne;
}
public DigitalInput getInputTwo() {
initialize();
return inputTwo;
return m_inputTwo;
}
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup()
*/
@Override
@@ -72,7 +69,7 @@ public abstract class RelayCrossConnectFixture implements ITestFixture {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset()
*/
@Override
@@ -83,16 +80,16 @@ public abstract class RelayCrossConnectFixture implements ITestFixture {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown()
*/
@Override
public boolean teardown() {
if (!freed) {
relay.free();
inputOne.free();
inputTwo.free();
freed = true;
if (!m_freed) {
m_relay.free();
m_inputOne.free();
m_inputTwo.free();
m_freed = true;
} else {
throw new RuntimeException("You attempted to free the "
+ RelayCrossConnectFixture.class.getSimpleName() + " multiple times");

View File

@@ -9,17 +9,13 @@ package edu.wpi.first.wpilibj.fixtures;
/**
* This is an example of how to use the {@link ITestFixture} interface to create
* test fixtures for a test.
*$
* This is an example of how to use the {@link ITestFixture} interface to create test fixtures for a
* test.
*
* @author Fredric Silberberg
*$
*/
public class SampleFixture implements ITestFixture {
/**
* {@inheritDoc}
*/
@Override
public boolean setup() {
/*
@@ -42,9 +38,6 @@ public class SampleFixture implements ITestFixture {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean teardown() {
/*

View File

@@ -14,21 +14,20 @@ import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.Timer;
/**
* A class to represent the a physical Camera with two servos (tilt and pan)
* designed to test to see if the gyroscope is operating normally.
* A class to represent the a physical Camera with two servos (tilt and pan) designed to test to see
* if the gyroscope is operating normally.
*
* @author Jonathan Leitschuh
*
*/
public abstract class TiltPanCameraFixture implements ITestFixture {
public static final Logger logger = Logger.getLogger(TiltPanCameraFixture.class.getName());
public static final double RESET_TIME = 2.0;
private AnalogGyro gyro;
private AnalogGyro gyroParam;
private Servo tilt;
private Servo pan;
private boolean initialized = false;
private AnalogGyro m_gyro;
private AnalogGyro m_gyroParam;
private Servo m_tilt;
private Servo m_pan;
private boolean m_initialized = false;
protected abstract AnalogGyro giveGyro();
@@ -40,24 +39,25 @@ public abstract class TiltPanCameraFixture implements ITestFixture {
protected abstract Servo givePan();
/**
* Constructs the TiltPanCamera
* Constructs the TiltPanCamera.
*/
public TiltPanCameraFixture() {}
public TiltPanCameraFixture() {
}
@Override
public boolean setup() {
boolean wasSetup = false;
if (!initialized) {
initialized = true;
tilt = giveTilt();
tilt.set(0);
pan = givePan();
pan.set(0);
if (!m_initialized) {
m_initialized = true;
m_tilt = giveTilt();
m_tilt.set(0);
m_pan = givePan();
m_pan.set(0);
Timer.delay(RESET_TIME);
logger.fine("Initializing the gyro");
gyro = giveGyro();
gyro.reset();
m_gyro = giveGyro();
m_gyro.reset();
wasSetup = true;
}
return wasSetup;
@@ -65,50 +65,52 @@ public abstract class TiltPanCameraFixture implements ITestFixture {
@Override
public boolean reset() {
if(gyro != null)
gyro.reset();
if (m_gyro != null) {
m_gyro.reset();
}
return true;
}
public Servo getTilt() {
return tilt;
return m_tilt;
}
public Servo getPan() {
return pan;
return m_pan;
}
public AnalogGyro getGyro() {
return gyro;
return m_gyro;
}
public AnalogGyro getGyroParam() {
return gyroParam;
return m_gyroParam;
}
// Do not call unless all other instances of Gyro have been deallocated
public void setupGyroParam(int center, double offset) {
gyroParam = giveGyroParam(center, offset);
gyroParam.reset();
m_gyroParam = giveGyroParam(center, offset);
m_gyroParam.reset();
}
public void freeGyro() {
gyro.free();
gyro = null;
m_gyro.free();
m_gyro = null;
}
@Override
public boolean teardown() {
tilt.free();
tilt = null;
pan.free();
pan = null;
if(gyro !=null){//in case not freed during gyro tests
gyro.free();
gyro = null;
m_tilt.free();
m_tilt = null;
m_pan.free();
m_pan = null;
if (m_gyro != null) { //in case not freed during gyro tests
m_gyro.free();
m_gyro = null;
}
if(gyroParam != null){//in case gyro tests failed before getting to this point
gyroParam.free();
gyroParam = null;
if (m_gyroParam != null) { //in case gyro tests failed before getting to this point
m_gyroParam.free();
m_gyroParam = null;
}
return true;
}

View File

@@ -11,19 +11,20 @@ import edu.wpi.first.wpilibj.DigitalOutput;
import edu.wpi.first.wpilibj.Timer;
/**
* Simulates an encoder for testing purposes
* Simulates an encoder for testing purposes.
*
* @author Ryan O'Meara
*/
public class FakeCounterSource {
private Thread m_task;
private int m_count;
private int m_mSec;
private int m_milliSec;
private DigitalOutput m_output;
private boolean m_allocated;
/**
* Thread object that allows emulation of an encoder
* Thread object that allows emulation of an encoder.
*/
private class EncoderThread extends Thread {
@@ -37,19 +38,20 @@ public class FakeCounterSource {
m_encoder.m_output.set(false);
try {
for (int i = 0; i < m_encoder.m_count; i++) {
Thread.sleep(m_encoder.m_mSec);
Thread.sleep(m_encoder.m_milliSec);
m_encoder.m_output.set(true);
Thread.sleep(m_encoder.m_mSec);
Thread.sleep(m_encoder.m_milliSec);
m_encoder.m_output.set(false);
}
} catch (InterruptedException e) {
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
/**
* Create a fake encoder on a given port
*$
* Create a fake encoder on a given port.
*
* @param output the port to output the given signal to
*/
public FakeCounterSource(DigitalOutput output) {
@@ -59,8 +61,8 @@ public class FakeCounterSource {
}
/**
* Create a fake encoder on a given port
*$
* Create a fake encoder on a given port.
*
* @param port The port the encoder is supposed to be on
*/
public FakeCounterSource(int port) {
@@ -70,7 +72,7 @@ public class FakeCounterSource {
}
/**
* Destroy Object with minimum memory leak
* Destroy Object with minimum memory leak.
*/
public void free() {
m_task = null;
@@ -82,36 +84,36 @@ public class FakeCounterSource {
}
/**
* Common initailization code
* Common initailization code.
*/
private void initEncoder() {
m_mSec = 1;
m_milliSec = 1;
m_task = new EncoderThread(this);
m_output.set(false);
}
/**
* Starts the thread execution task
* Starts the thread execution task.
*/
public void start() {
m_task.start();
}
/**
* Waits for the thread to complete
* Waits for the thread to complete.
*/
public void complete() {
try {
m_task.join();
} catch (InterruptedException e) {
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
m_task = new EncoderThread(this);
Timer.delay(.01);
}
/**
* Starts and completes a task set - does not return until thred has finished
* its operations
* Starts and completes a task set - does not return until thred has finished its operations.
*/
public void execute() {
start();
@@ -119,8 +121,8 @@ public class FakeCounterSource {
}
/**
* Sets the count to run encoder
*$
* Sets the count to run encoder.
*
* @param count The count to emulate to the controller
*/
public void setCount(int count) {
@@ -128,11 +130,11 @@ public class FakeCounterSource {
}
/**
* Specify the rate to send pulses
*$
* @param mSec The rate to send out pulses at
* Specify the rate to send pulses.
*
* @param milliSec The rate to send out pulses at
*/
public void setRate(int mSec) {
m_mSec = mSec;
public void setRate(int milliSec) {
m_milliSec = milliSec;
}
}

View File

@@ -11,20 +11,22 @@ import edu.wpi.first.wpilibj.DigitalOutput;
import edu.wpi.first.wpilibj.Timer;
/**
* Emulates a quadrature encoder
* Emulates a quadrature encoder.
*
* @author Ryan O'Meara
*/
public class FakeEncoderSource {
private Thread m_task;
private int m_count;
private int m_mSec;
private int m_milliSec;
private boolean m_forward;
private DigitalOutput m_outputA, m_outputB;
private final boolean allocatedOutputs;
private final DigitalOutput m_outputA;
private final DigitalOutput m_outputB;
private final boolean m_allocatedOutputs;
/**
* Thread object that allows emulation of a quadrature encoder
* Thread object that allows emulation of a quadrature encoder.
*/
private class QuadEncoderThread extends Thread {
@@ -36,7 +38,8 @@ public class FakeEncoderSource {
public void run() {
DigitalOutput lead, lag;
final DigitalOutput lead;
final DigitalOutput lag;
m_encoder.m_outputA.set(false);
m_encoder.m_outputB.set(false);
@@ -52,46 +55,62 @@ public class FakeEncoderSource {
try {
for (int i = 0; i < m_encoder.m_count; i++) {
lead.set(true);
Thread.sleep(m_encoder.m_mSec);
Thread.sleep(m_encoder.m_milliSec);
lag.set(true);
Thread.sleep(m_encoder.m_mSec);
Thread.sleep(m_encoder.m_milliSec);
lead.set(false);
Thread.sleep(m_encoder.m_mSec);
Thread.sleep(m_encoder.m_milliSec);
lag.set(false);
Thread.sleep(m_encoder.m_mSec);
Thread.sleep(m_encoder.m_milliSec);
}
} catch (InterruptedException e) {
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
/**
* Creates an encoder source using two ports.
*
* @param portA The A port
* @param portB The B port
*/
public FakeEncoderSource(int portA, int portB) {
m_outputA = new DigitalOutput(portA);
m_outputB = new DigitalOutput(portB);
allocatedOutputs = true;
m_allocatedOutputs = true;
initQuadEncoder();
}
public FakeEncoderSource(DigitalOutput iA, DigitalOutput iB) {
m_outputA = iA;
m_outputB = iB;
allocatedOutputs = false;
/**
* Creates the fake encoder using two digital outputs.
*
* @param outputA The A digital output
* @param outputB The B digital output
*/
public FakeEncoderSource(DigitalOutput outputA, DigitalOutput outputB) {
m_outputA = outputA;
m_outputB = outputB;
m_allocatedOutputs = false;
initQuadEncoder();
}
/**
* Frees the resource.
*/
public void free() {
m_task = null;
if (allocatedOutputs) {
if (m_allocatedOutputs) {
m_outputA.free();
m_outputB.free();
}
}
/**
* Common initialization code
* Common initialization code.
*/
private final void initQuadEncoder() {
m_mSec = 1;
m_milliSec = 1;
m_forward = true;
m_task = new QuadEncoderThread(this);
m_outputA.set(false);
@@ -99,26 +118,27 @@ public class FakeEncoderSource {
}
/**
* Starts the thread
* Starts the thread.
*/
public void start() {
m_task.start();
}
/**
* Waits for thread to end
* Waits for thread to end.
*/
public void complete() {
try {
m_task.join();
} catch (InterruptedException e) {
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
m_task = new QuadEncoderThread(this);
Timer.delay(.01);
}
/**
* Runs and waits for thread to end before returning
* Runs and waits for thread to end before returning.
*/
public void execute() {
start();
@@ -126,17 +146,17 @@ public class FakeEncoderSource {
}
/**
* Rate of pulses to send
*$
* @param mSec Pulse Rate
* Rate of pulses to send.
*
* @param milliSec Pulse Rate
*/
public void setRate(int mSec) {
m_mSec = mSec;
public void setRate(int milliSec) {
m_milliSec = milliSec;
}
/**
* Set the number of pulses to simulate
*$
* Set the number of pulses to simulate.
*
* @param count Pulse count
*/
public void setCount(int count) {
@@ -144,8 +164,8 @@ public class FakeEncoderSource {
}
/**
* Set which direction the encoder simulates motion in
*$
* Set which direction the encoder simulates motion in.
*
* @param isForward Whether to simulate forward motion
*/
public void setForward(boolean isForward) {
@@ -153,8 +173,8 @@ public class FakeEncoderSource {
}
/**
* Accesses whether the encoder is simulating forward motion
*$
* Accesses whether the encoder is simulating forward motion.
*
* @return Whether the simulated motion is in the forward direction
*/
public boolean isForward() {

View File

@@ -10,76 +10,86 @@ package edu.wpi.first.wpilibj.mockhardware;
import edu.wpi.first.wpilibj.AnalogOutput;
/**
* @author jonathanleitschuh
* A fake source to provide output to a {@link edu.wpi.first.wpilibj.interfaces.Potentiometer}.
*
* @author jonathanleitschuh
*/
public class FakePotentiometerSource {
private AnalogOutput output;
private boolean m_init_output;
private double potMaxAngle;
private double potMaxVoltage = 5.0;
private final double defaultPotMaxAngle;
private AnalogOutput m_output;
private boolean m_initOutput;
private double m_potMaxAngle;
private double m_potMaxVoltage = 5.0;
private final double m_defaultPotMaxAngle;
/**
* Constructs the fake source.
*
* @param output The analog port to output the signal on
* @param defaultPotMaxAngle The default maximum angle the pot supports.
*/
public FakePotentiometerSource(AnalogOutput output, double defaultPotMaxAngle) {
this.defaultPotMaxAngle = defaultPotMaxAngle;
potMaxAngle = defaultPotMaxAngle;
this.output = output;
m_init_output = false;
m_defaultPotMaxAngle = defaultPotMaxAngle;
m_potMaxAngle = defaultPotMaxAngle;
m_output = output;
m_initOutput = false;
}
public FakePotentiometerSource(int port, double defaultPotMaxAngle) {
this(new AnalogOutput(port), defaultPotMaxAngle);
m_init_output = true;
m_initOutput = true;
}
/**
* Sets the maximum voltage output. If not the default is 5.0V
*$
* Sets the maximum voltage output. If not the default is 5.0V.
*
* @param voltage The voltage that indicates that the pot is at the max value.
*/
public void setMaxVoltage(double voltage) {
potMaxVoltage = voltage;
m_potMaxVoltage = voltage;
}
public void setRange(double range) {
potMaxAngle = range;
m_potMaxAngle = range;
}
public void reset() {
potMaxAngle = defaultPotMaxAngle;
output.setVoltage(0.0);
m_potMaxAngle = m_defaultPotMaxAngle;
m_output.setVoltage(0.0);
}
public void setAngle(double angle) {
output.setVoltage((potMaxVoltage / potMaxAngle) * angle);
m_output.setVoltage((m_potMaxVoltage / m_potMaxAngle) * angle);
}
public void setVoltage(double voltage) {
output.setVoltage(voltage);
m_output.setVoltage(voltage);
}
public double getVoltage() {
return output.getVoltage();
return m_output.getVoltage();
}
/**
* Returns the currently set angle
*$
* Returns the currently set angle.
*
* @return the current angle
*/
public double getAngle() {
double voltage = output.getVoltage();
double voltage = m_output.getVoltage();
if (voltage == 0) { // Removes divide by zero error
return 0;
}
return voltage * (potMaxAngle / potMaxVoltage);
return voltage * (m_potMaxAngle / m_potMaxVoltage);
}
/**
* Frees the resouce.
*/
public void free() {
if (m_init_output) {
output.free();
output = null;
m_init_output = false;
if (m_initOutput) {
m_output.free();
m_output = null;
m_initOutput = false;
}
}
}

View File

@@ -10,107 +10,106 @@ package edu.wpi.first.wpilibj.mocks;
import edu.wpi.first.wpilibj.command.Command;
/**
* A class to simulate a simple command The command keeps track of how many
* times each method was called
* A class to simulate a simple command The command keeps track of how many times each method was
* called.
*
* @author mwills
*/
public class MockCommand extends Command {
private int initializeCount = 0;
private int executeCount = 0;
private int isFinishedCount = 0;
private boolean hasFinished = false;
private int endCount = 0;
private int interruptedCount = 0;
private int m_initializeCount = 0;
private int m_executeCount = 0;
private int m_isFinishedCount = 0;
private boolean m_hasFinished = false;
private int m_endCount = 0;
private int m_interruptedCount = 0;
protected void initialize() {
++initializeCount;
++m_initializeCount;
}
protected void execute() {
++executeCount;
++m_executeCount;
}
protected boolean isFinished() {
++isFinishedCount;
++m_isFinishedCount;
return isHasFinished();
}
protected void end() {
++endCount;
++m_endCount;
}
protected void interrupted() {
++interruptedCount;
++m_interruptedCount;
}
/**
* @return how many times the initialize method has been called
* How many times the initialize method has been called.
*/
public int getInitializeCount() {
return initializeCount;
return m_initializeCount;
}
/**
* @return if the initialize method has been called at least once
* If the initialize method has been called at least once.
*/
public boolean hasInitialized() {
return getInitializeCount() > 0;
}
/**
* @return how many time the execute method has been called
* How many time the execute method has been called.
*/
public int getExecuteCount() {
return executeCount;
return m_executeCount;
}
/**
* @return how many times the isFinished method has been called
* How many times the isFinished method has been called.
*/
public int getIsFinishedCount() {
return isFinishedCount;
return m_isFinishedCount;
}
/**
* @return what value the isFinished method will return
* @return what value the isFinished method will return.
*/
public boolean isHasFinished() {
return hasFinished;
return m_hasFinished;
}
/**
* @param hasFinished set what value the isFinished method will return
* @param hasFinished set what value the isFinished method will return.
*/
public void setHasFinished(boolean hasFinished) {
this.hasFinished = hasFinished;
m_hasFinished = hasFinished;
}
/**
* @return how many times the end method has been called
* How many times the end method has been called.
*/
public int getEndCount() {
return endCount;
return m_endCount;
}
/**
* @return if the end method has been called at least once
* If the end method has been called at least once.
*/
public boolean hasEnd() {
return getEndCount() > 0;
}
/**
* @return how many times the interrupted method has been called
* How many times the interrupted method has been called.
*/
public int getInterruptedCount() {
return interruptedCount;
return m_interruptedCount;
}
/**
* @return if the interrupted method has been called at least once
* If the interrupted method has been called at least once.
*/
public boolean hasInterrupted() {
return getInterruptedCount() > 0;

View File

@@ -7,24 +7,21 @@
package edu.wpi.first.wpilibj.smartdashboard;
import static org.junit.Assert.assertEquals;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.networktables.NetworkTableKeyNotDefined;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
/**
* @author jonathanleitschuh
* Test that covers {@link SmartDashboard}.
*
* @author jonathanleitschuh
*/
public class SmartDashboardTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(SmartDashboardTest.class.getName());
@@ -34,30 +31,6 @@ public class SmartDashboardTest extends AbstractComsSetup {
return logger;
}
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {}
@Test(expected = NetworkTableKeyNotDefined.class)
public void testGetBadValue() {
SmartDashboard.getString("_404_STRING_KEY_SHOULD_NOT_BE_FOUND_");
@@ -94,11 +67,11 @@ public class SmartDashboardTest extends AbstractComsSetup {
public void testReplaceString() {
String key = "testReplaceString";
String valueOld = "oldValue";
String valueNew = "newValue";
SmartDashboard.putString(key, valueOld);
assertEquals(valueOld, SmartDashboard.getString(key));
assertEquals(valueOld, table.getString(key));
String valueNew = "newValue";
SmartDashboard.putString(key, valueNew);
assertEquals(valueNew, SmartDashboard.getString(key));
assertEquals(valueNew, table.getString(key));

View File

@@ -14,8 +14,9 @@ import org.junit.runners.Suite.SuiteClasses;
import edu.wpi.first.wpilibj.test.AbstractTestSuite;
/**
* @author jonathanleitschuh
* All tests pertaining to {@link SmartDashboard}.
*
* @author jonathanleitschuh
*/
@RunWith(Suite.class)
@SuiteClasses({SmartDashboardTest.class})

View File

@@ -7,15 +7,15 @@
package edu.wpi.first.wpilibj.test;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runners.model.MultipleFailureException;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.RobotBase;
import edu.wpi.first.wpilibj.Timer;
@@ -23,16 +23,18 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* This class serves as a superclass for all tests that involve the hardware on
* the roboRIO. It uses an {@link BeforeClass} statement to initialize network
* communications. Any test that needs to use the hardware <b>MUST</b> extend
* from this class, to ensure that all of the hardware will be able to run.
*$
* This class serves as a superclass for all tests that involve the hardware on the roboRIO. It uses
* an {@link BeforeClass} statement to initialize network communications. Any test that needs to use
* the hardware <b>MUST</b> extend from this class, to ensure that all of the hardware will be able
* to run.
*
* @author Fredric Silberberg
* @author Jonathan Leitschuh
*/
public abstract class AbstractComsSetup {
/** Stores whether network coms have been initialized */
/**
* Stores whether network coms have been initialized.
*/
private static boolean initialized = false;
/**
@@ -40,7 +42,6 @@ public abstract class AbstractComsSetup {
* station. After starting network coms, it will loop until the driver station
* returns that the robot is enabled, to ensure that tests will be able to run
* on the hardware.
*$
*/
static {
if (!initialized) {
@@ -52,15 +53,15 @@ public abstract class AbstractComsSetup {
TestBench.out().println("Started coms");
// Wait until the robot is enabled before starting the tests
int i = 0;
int enableCounter = 0;
while (!DriverStation.getInstance().isEnabled()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
// Prints the message on one line overwriting itself each time
TestBench.out().print("\rWaiting for enable: " + i++);
TestBench.out().print("\rWaiting for enable: " + enableCounter++);
}
TestBench.out().println();
@@ -74,8 +75,7 @@ public abstract class AbstractComsSetup {
protected abstract Logger getClassLogger();
/**
* This causes a stack trace to be printed as the test is running as well as
* at the end
* This causes a stack trace to be printed as the test is running as well as at the end.
*/
@Rule
public final TestWatcher getTestWatcher() {
@@ -83,8 +83,8 @@ public abstract class AbstractComsSetup {
}
/**
* Given as a way to provide a custom test watcher for a test or set of tests
*$
* Given as a way to provide a custom test watcher for a test or set of tests.
*
* @return the test watcher to use
*/
protected TestWatcher getOverridenTestWatcher() {
@@ -93,68 +93,69 @@ public abstract class AbstractComsSetup {
protected class DefaultTestWatcher extends TestWatcher {
/**
* Allows a failure to supply a custom status message to be displayed along
* with the stack trace.
* Allows a failure to supply a custom status message to be displayed along with the stack
* trace.
*/
protected void failed(Throwable e, Description description, String status) {
protected void failed(Throwable throwable, Description description, String status) {
TestBench.out().println();
// Instance of is the best way I know to retrieve this data.
if (e instanceof MultipleFailureException) {
if (throwable instanceof MultipleFailureException) {
/*
* MultipleFailureExceptions hold multiple exceptions in one exception.
* In order to properly display these stack traces we have to cast the
* throwable and work with the list of thrown exceptions stored within
* it.
*/
int i = 1; // Running exception count
int failureCount = ((MultipleFailureException) e).getFailures().size();
for (Throwable singleThrown : ((MultipleFailureException) e).getFailures()) {
int exceptionCount = 1; // Running exception count
int failureCount = ((MultipleFailureException) throwable).getFailures().size();
for (Throwable singleThrown : ((MultipleFailureException) throwable).getFailures()) {
getClassLogger().logp(
Level.SEVERE,
description.getClassName(),
description.getMethodName(),
(i++) + "/" + failureCount + " " + description.getDisplayName() + " failed "
+ singleThrown.getMessage() + "\n" + status, singleThrown);
(exceptionCount++) + "/" + failureCount + " " + description.getDisplayName() + " "
+ "failed " + singleThrown.getMessage() + "\n" + status, singleThrown);
}
} else {
getClassLogger().logp(Level.SEVERE, description.getClassName(),
description.getMethodName(),
description.getDisplayName() + " failed " + e.getMessage() + "\n" + status, e);
description.getDisplayName() + " failed " + throwable.getMessage() + "\n" + status,
throwable);
}
super.failed(e, description);
super.failed(throwable, description);
}
/*
* (non-Javadoc)
*$
*
* @see org.junit.rules.TestWatcher#failed(java.lang.Throwable,
* org.junit.runner.Description)
*/
@Override
protected void failed(Throwable e, Description description) {
failed(e, description, "");
protected void failed(Throwable exception, Description description) {
failed(exception, description, "");
}
/*
* (non-Javadoc)
*$
*
* @see org.junit.rules.TestWatcher#starting(org.junit.runner.Description)
*/
@Override
protected void starting(Description description) {
TestBench.out().println();
// Wait until the robot is enabled before starting the next tests
int i = 0;
int enableCounter = 0;
while (!DriverStation.getInstance().isEnabled()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
// Prints the message on one line overwriting itself each time
TestBench.out().print("\rWaiting for enable: " + i++);
TestBench.out().print("\rWaiting for enable: " + enableCounter++);
}
getClassLogger().logp(Level.INFO, description.getClassName(), description.getMethodName(),
"Starting");
@@ -167,12 +168,12 @@ public abstract class AbstractComsSetup {
super.succeeded(description);
}
};
}
/**
* Logs a simple message without the logger formatting associated with it.
*$
* @param level The level to log the message at
*
* @param level The level to log the message at
* @param message The message to log
*/
protected void simpleLog(Level level, String message) {
@@ -182,50 +183,50 @@ public abstract class AbstractComsSetup {
}
/**
* Provided as a replacement to lambda functions to allow for repeatable
* checks to see if a correct state is reached
*$
* @author Jonathan Leitschuh
* Provided as a replacement to lambda functions to allow for repeatable checks to see if a
* correct state is reached.
*
* @author Jonathan Leitschuh
*/
public abstract class BooleanCheck {
public BooleanCheck() {}
public BooleanCheck() {
}
/**
* Runs the enclosed code and evaluates it to determine what state it should
* return.
*$
* Runs the enclosed code and evaluates it to determine what state it should return.
*
* @return true if the code provided within the method returns true
*/
abstract public boolean getAsBoolean();
};
public abstract boolean getAsBoolean();
}
/**
* Delays until either the correct state is reached or we reach the timeout.
*$
* @param level The level to log the message at.
* @param timeout How long the delay should run before it should timeout and
* allow the test to continue
* @param message The message to accompany the delay. The message will display
* 'message' took 'timeout' seconds if it passed.
* @param correctState A method to determine if the test has reached a state
* where it is valid to continue
*
* @param level The level to log the message at.
* @param timeout How long the delay should run before it should timeout and allow the test
* to continue
* @param message The message to accompany the delay. The message will display 'message' took
* 'timeout' seconds if it passed.
* @param correctState A method to determine if the test has reached a state where it is valid to
* continue
* @return a double representing how long the delay took to run in seconds.
*/
public double delayTillInCorrectStateWithMessage(Level level, double timeout, String message,
BooleanCheck correctState) {
int i = 0;
BooleanCheck correctState) {
int timeoutIndex;
// As long as we are not in the correct state and the timeout has not been
// reached then continue to run this loop
for (i = 0; i < (timeout * 100) && !correctState.getAsBoolean(); i++) {
for (timeoutIndex = 0; timeoutIndex < (timeout * 100) && !correctState.getAsBoolean();
timeoutIndex++) {
Timer.delay(.01);
}
if (correctState.getAsBoolean()) {
simpleLog(level, message + " took " + (i * .01) + " seconds");
simpleLog(level, message + " took " + (timeoutIndex * .01) + " seconds");
} else {
simpleLog(level, message + " timed out after " + (i * .01) + " seconds");
simpleLog(level, message + " timed out after " + (timeoutIndex * .01) + " seconds");
}
return i * .01;
return timeoutIndex * .01;
}
}

View File

@@ -7,6 +7,11 @@
package edu.wpi.first.wpilibj.test;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.Request;
import org.junit.runners.Suite.SuiteClasses;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Vector;
@@ -14,33 +19,23 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.Request;
import org.junit.runners.Suite.SuiteClasses;
import org.junit.runners.model.InitializationError;
/**
* Allows tests suites and tests to be run selectively from the command line
* using a regex text pattern.
*$
* @author jonathanleitschuh
* Allows tests suites and tests to be run selectively from the command line using a regex text
* pattern.
*
* @author jonathanleitschuh
*/
public abstract class AbstractTestSuite {
private static final Logger logger = Logger.getLogger(AbstractTestSuite.class.getName());
/**
* Gets all of the classes listed within the SuiteClasses annotation. To use
* it, annotate a class with <code>@RunWith(Suite.class)</code> and
* <code>@SuiteClasses({TestClass1.class, ...})</code>. When you run this
* class, it will run all the tests in all the suite classes. When loading the
* tests using regex the test list will be generated from this annotation.
*$
* @return the list of classes listed in the
* <code>@SuiteClasses({TestClass1.class, ...})</code> annotation.
* @throws RuntimeException If the <code>@SuiteClasses</code> annotation is
* missing.
* Gets all of the classes listed within the SuiteClasses annotation. To use it, annotate a class
* with <code>@RunWith(Suite.class)</code> and <code>@SuiteClasses({TestClass1.class,
* ...})</code>. When you run this class, it will run all the tests in all the suite classes. When
* loading the tests using regex the test list will be generated from this annotation.
*
* @return the list of classes listed in the <code>@SuiteClasses({TestClass1.class, ...})</code>.
* @throws RuntimeException If the <code>@SuiteClasses</code> annotation is missing.
*/
protected List<Class<?>> getAnnotatedTestClasses() {
SuiteClasses annotation = getClass().getAnnotation(SuiteClasses.class);
@@ -66,23 +61,22 @@ public abstract class AbstractTestSuite {
}
/**
* Stores a method name and method class pair. Used when searching for methods
* matching a given regex text.
*$
* @author jonathanleitschuh
* Stores a method name and method class pair. Used when searching for methods matching a given
* regex text.
*
* @author jonathanleitschuh
*/
protected class ClassMethodPair {
public final Class<?> methodClass;
public final String methodName;
public final Class<?> m_methodClass;
public final String m_methodName;
public ClassMethodPair(Class<?> klass, Method m) {
this.methodClass = klass;
this.methodName = m.getName();
public ClassMethodPair(Class<?> klass, Method method) {
m_methodClass = klass;
m_methodName = method.getName();
}
public Request getMethodRunRequest() {
return Request.method(methodClass, methodName);
return Request.method(m_methodClass, m_methodName);
}
}
@@ -105,9 +99,9 @@ public abstract class AbstractTestSuite {
/**
* Gets all of the test classes listed in this suite. Does not include any of
* the test suites. All of these classes contain tests.
*$
* Gets all of the test classes listed in this suite. Does not include any of the test suites. All
* of these classes contain tests.
*
* @param runningList the running list of classes to prevent recursion.
* @return The list of base test classes.
*/
@@ -117,21 +111,20 @@ public abstract class AbstractTestSuite {
if (areAnySuperClassesOfTypeAbstractTestSuite(c)) {
// Create a new instance of this class so that we can retrieve its data
try {
AbstractTestSuite suite = null;
Object o = c.newInstance();
suite = (AbstractTestSuite) c.newInstance();
AbstractTestSuite suite = (AbstractTestSuite) c.newInstance();
// Add the tests from this suite that match the regex to the list of
// tests to run
runningList = suite.getAllContainedBaseTests(runningList);
} catch (InstantiationException | IllegalAccessException e) {
} catch (InstantiationException | IllegalAccessException ex) {
// This shouldn't happen unless the constructor is changed in some
// way.
logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", e);
logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.",
ex);
}
} else if (c.getAnnotation(SuiteClasses.class) != null) {
logger.log(Level.SEVERE,
String.format("class '%s' must extend %s to be searchable using regex.", c.getName()),
AbstractTestSuite.class.getName());
String.format("class '%s' must extend %s to be searchable using regex.",
c.getName(), AbstractTestSuite.class.getName()));
} else { // This is a class containing tests
// so add it to the list
runningList.add(c);
@@ -141,9 +134,9 @@ public abstract class AbstractTestSuite {
}
/**
* Gets all of the test classes listed in this suite. Does not include any of
* the test suites. All of these classes contain tests.
*$
* Gets all of the test classes listed in this suite. Does not include any of the test suites. All
* of these classes contain tests.
*
* @return The list of base test classes.
*/
public List<Class<?>> getAllContainedBaseTests() {
@@ -153,10 +146,10 @@ public abstract class AbstractTestSuite {
/**
* Retrieves all of the classes listed in the
* <code>@SuiteClasses</code> annotation that match the given regex text.
*$
* @param regex the text pattern to retrieve.
* Retrieves all of the classes listed in the <code>@SuiteClasses</code> annotation that match the
* given regex text.
*
* @param regex the text pattern to retrieve.
* @param runningList the running list of classes to prevent recursion
* @return The list of classes matching the regex pattern
*/
@@ -171,9 +164,9 @@ public abstract class AbstractTestSuite {
}
/**
* Retrieves all of the classes listed in the
* <code>@SuiteClasses</code> annotation that match the given regex text.
*$
* Retrieves all of the classes listed in the <code>@SuiteClasses</code> annotation that match the
* given regex text.
*
* @param regex the text pattern to retrieve.
* @return The list of classes matching the regex pattern
*/
@@ -183,15 +176,15 @@ public abstract class AbstractTestSuite {
}
/**
* Searches through all of the suites and tests and loads only the test or
* test suites matching the regex text. This method also prevents a single
* test from being loaded multiple times by loading the suite first then
* loading tests from all non loaded suites.
*$
* Searches through all of the suites and tests and loads only the test or test suites matching
* the regex text. This method also prevents a single test from being loaded multiple times by
* loading the suite first then loading tests from all non loaded suites.
*
* @param regex the regex text to search for
* @return the list of suite and/or test classes matching the regex.
*/
private List<Class<?>> getSuiteOrTestMatchingRegex(final String regex, List<Class<?>> runningList) {
private List<Class<?>> getSuiteOrTestMatchingRegex(final String regex, List<Class<?>>
runningList) {
// Get any test suites matching the regex using the superclass methods
runningList = getAllClassMatching(regex, runningList);
@@ -206,22 +199,22 @@ public abstract class AbstractTestSuite {
// Prevents recursively adding tests/suites that have already been added
if (!runningList.contains(c)) {
try {
AbstractTestSuite suite = null;
final AbstractTestSuite suite;
// Check the class to make sure that it is not a test class
if (areAnySuperClassesOfTypeAbstractTestSuite(c)) {
// Create a new instance of this class so that we can retrieve its
// data.
Object o = c.newInstance();
suite = (AbstractTestSuite) c.newInstance();
// Add the tests from this suite that match the regex to the list of
// tests to run
runningList = suite.getSuiteOrTestMatchingRegex(regex, runningList);
}
} catch (InstantiationException | IllegalAccessException e) {
} catch (InstantiationException | IllegalAccessException ex) {
// This shouldn't happen unless the constructor is changed in some
// way.
logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", e);
logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.",
ex);
}
}
}
@@ -229,11 +222,10 @@ public abstract class AbstractTestSuite {
}
/**
* Searches through all of the suites and tests and loads only the test or
* test suites matching the regex text. This method also prevents a single
* test from being loaded multiple times by loading the suite first then
* loading tests from all non loaded suites.
*$
* Searches through all of the suites and tests and loads only the test or test suites matching
* the regex text. This method also prevents a single test from being loaded multiple times by
* loading the suite first then loading tests from all non loaded suites.
*
* @param regex the regex text to search for
* @return the list of suite and/or test classes matching the regex.
*/
@@ -243,26 +235,21 @@ public abstract class AbstractTestSuite {
}
/**
* Retrieves all of the classes listed in the
* <code>@SuiteClasses</code> annotation.
*$
* Retrieves all of the classes listed in the <code>@SuiteClasses</code> annotation.
*
* @return List of SuiteClasses
* @throws RuntimeException If the <code>@SuiteClasses</code> annotation is
* missing.
* @throws RuntimeException If the <code>@SuiteClasses</code> annotation is missing.
*/
public List<Class<?>> getAllClasses() {
return getAnnotatedTestClasses();
}
/**
* Gets the name of all of the classes listed within the
* <code>@SuiteClasses</code> annotation.
*$
* Gets the name of all of the classes listed within the <code>@SuiteClasses</code> annotation.
*
* @return the list of classes.
* @throws RuntimeException If the <code>@SuiteClasses</code> annotation is
* missing.
* @throws RuntimeException If the <code>@SuiteClasses</code> annotation is missing.
*/
public List<String> getAllClassName() {
List<String> classNames = new Vector<String>();

View File

@@ -7,13 +7,6 @@
package edu.wpi.first.wpilibj.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -22,11 +15,20 @@ import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.junit.runners.model.InitializationError;
import java.util.List;
import edu.wpi.first.wpilibj.test.AbstractTestSuite.ClassMethodPair;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
/**
* @author jonathanleitschuh
* Yes, this is the test system testing itself. Functionally, this is making sure that all tests get
* run correctly when you use parametrized arguments.
*
* @author jonathanleitschuh
*/
public class AbstractTestSuiteTest {
@@ -37,20 +39,17 @@ public class AbstractTestSuiteTest {
class TestForAbstractTestSuite extends AbstractTestSuite {
}
TestForAbstractTestSuite testSuite;
TestForAbstractTestSuite m_testSuite;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
testSuite = new TestForAbstractTestSuite();
m_testSuite = new TestForAbstractTestSuite();
}
@Test
public void testGetTestsMatchingAll() throws InitializationError {
// when
List<Class<?>> collectedTests = testSuite.getAllClassMatching(".*");
List<Class<?>> collectedTests = m_testSuite.getAllClassMatching(".*");
// then
assertEquals(7, collectedTests.size());
}
@@ -58,7 +57,7 @@ public class AbstractTestSuiteTest {
@Test
public void testGetTestsMatchingSample() throws InitializationError {
// when
List<Class<?>> collectedTests = testSuite.getAllClassMatching(".*Sample.*");
List<Class<?>> collectedTests = m_testSuite.getAllClassMatching(".*Sample.*");
// then
assertEquals(4, collectedTests.size());
}
@@ -66,7 +65,7 @@ public class AbstractTestSuiteTest {
@Test
public void testGetTestsMatchingUnusual() throws InitializationError {
// when
List<Class<?>> collectedTests = testSuite.getAllClassMatching(".*Unusual.*");
List<Class<?>> collectedTests = m_testSuite.getAllClassMatching(".*Unusual.*");
// then
assertEquals(1, collectedTests.size());
assertEquals(UnusualTest.class, collectedTests.get(0));
@@ -75,7 +74,7 @@ public class AbstractTestSuiteTest {
@Test
public void testGetTestsFromSuiteMatchingAll() throws InitializationError {
// when
List<Class<?>> collectedTests = testSuite.getSuiteOrTestMatchingRegex(".*");
List<Class<?>> collectedTests = m_testSuite.getSuiteOrTestMatchingRegex(".*");
// then
assertEquals(7, collectedTests.size());
}
@@ -83,58 +82,61 @@ public class AbstractTestSuiteTest {
@Test
public void testGetTestsFromSuiteMatchingTest() throws InitializationError {
// when
List<Class<?>> collectedTests = testSuite.getSuiteOrTestMatchingRegex(".*Test.*");
List<Class<?>> collectedTests = m_testSuite.getSuiteOrTestMatchingRegex(".*Test.*");
// then
assertEquals(7, collectedTests.size());
assertThat(collectedTests, hasItems(new Class<?>[] {FirstSubSuiteTest.class,
SecondSubSuiteTest.class, UnusualTest.class}));
assertThat(collectedTests, hasItems(FirstSubSuiteTest.class,
SecondSubSuiteTest.class, UnusualTest.class));
assertThat(collectedTests,
not(hasItems(new Class<?>[] {ExampleSubSuite.class, EmptySuite.class})));
not(hasItems(new Class<?>[]{ExampleSubSuite.class, EmptySuite.class})));
}
@Test
public void testGetMethodFromTest() {
// when
List<ClassMethodPair> pairs = testSuite.getMethodMatching(".*Method.*");
List<ClassMethodPair> pairs = m_testSuite.getMethodMatching(".*Method.*");
// then
assertEquals(1, pairs.size());
assertEquals(FirstSubSuiteTest.class, pairs.get(0).methodClass);
assertEquals(FirstSubSuiteTest.METHODNAME, pairs.get(0).methodName);
assertEquals(FirstSubSuiteTest.class, pairs.get(0).m_methodClass);
assertEquals(FirstSubSuiteTest.METHODNAME, pairs.get(0).m_methodName);
}
}
@SuppressWarnings("OneTopLevelClass")
class FirstSampleTest {
}
@SuppressWarnings("OneTopLevelClass")
class SecondSampleTest {
}
@SuppressWarnings("OneTopLevelClass")
class ThirdSampleTest {
}
@SuppressWarnings("OneTopLevelClass")
class FourthSampleTest {
}
@SuppressWarnings("OneTopLevelClass")
class UnusualTest {
} // This is a member of both suites
@Ignore("Prevents ANT from trying to run these as tests")
@SuppressWarnings("OneTopLevelClass")
class FirstSubSuiteTest {
public static final String METHODNAME = "aTestMethod";
@Test
public void aTestMethod() {}
@SuppressWarnings("MethodName")
public void aTestMethod() {
}
}
@SuppressWarnings("OneTopLevelClass")
class SecondSubSuiteTest {
}
@@ -142,6 +144,7 @@ class SecondSubSuiteTest {
@RunWith(Suite.class)
@SuiteClasses({FirstSubSuiteTest.class, SecondSubSuiteTest.class, UnusualTest.class})
@Ignore("Prevents ANT from trying to run these as tests")
@SuppressWarnings("OneTopLevelClass")
class ExampleSubSuite extends AbstractTestSuite {
}
@@ -149,5 +152,6 @@ class ExampleSubSuite extends AbstractTestSuite {
@Ignore("Prevents ANT from trying to run these as tests")
@RunWith(Suite.class)
@SuiteClasses({})
@SuppressWarnings("OneTopLevelClass")
class EmptySuite extends AbstractTestSuite {
}

View File

@@ -7,8 +7,6 @@
package edu.wpi.first.wpilibj.test;
import java.io.File;
import org.apache.tools.ant.BuildLogger;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
@@ -16,15 +14,21 @@ import org.apache.tools.ant.taskdefs.optional.junit.FormatterElement;
import org.apache.tools.ant.taskdefs.optional.junit.JUnitTask;
import org.apache.tools.ant.taskdefs.optional.junit.JUnitTest;
import java.io.File;
/**
* Provides an entry point for tests to run with ANT. This allows ant to output
* JUnit XML test results for Jenkins.
*$
* @author jonathanleitschuh
* Provides an entry point for tests to run with ANT. This allows ant to output JUnit XML test
* results for Jenkins.
*
* @author jonathanleitschuh
*/
public class AntJunitLanucher {
/**
* Main entry point for jenkins
*
* @param args Arguments passed to java.
*/
public static void main(String... args) {
if (args.length == 0) {
String path =
@@ -35,7 +39,6 @@ public class AntJunitLanucher {
try {
// Create the file to store the test output
new File(pathToReports).mkdirs();
JUnitTask task = new JUnitTask();
project.setProperty("java.io.tmpdir", pathToReports);
@@ -46,6 +49,8 @@ public class AntJunitLanucher {
formatToScreen.setType(typeScreen);
formatToScreen.setUseFile(false);
formatToScreen.setOutput(System.out);
JUnitTask task = new JUnitTask();
task.addFormatter(formatToScreen);
// add a build listener to the project
@@ -73,8 +78,8 @@ public class AntJunitLanucher {
TestBench.out().println("Beginning Test Execution With ANT");
task.execute();
} catch (Exception e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
TestBench.out().println(

View File

@@ -7,19 +7,16 @@
package edu.wpi.first.wpilibj.test;
import java.util.logging.Logger;
import org.junit.Test;
import java.util.logging.Logger;
/**
* This class is designated to allow for simple testing of the library without
* the overlying testing framework. This test is NOT run as a normal part of the
* testing process and must be explicitly selected at runtime by using the
* 'quick' argument.
*$
* This test should never be committed with changes to it but can be used during
* development to aid in feature testing.
*$
* This class is designated to allow for simple testing of the library without the overlying testing
* framework. This test is NOT run as a normal part of the testing process and must be explicitly
* selected at runtime by using the 'quick' argument. This test should never be committed with
* changes to it but can be used during development to aid in feature testing.
*
* @author Jonathan Leitschuh
*/
public class QuickTest extends AbstractComsSetup {
@@ -27,7 +24,7 @@ public class QuickTest extends AbstractComsSetup {
/*
* (non-Javadoc)
*$
*
* @see edu.wpi.first.wpilibj.test.AbstractComsSetup#getClassLogger()
*/
@Override

View File

@@ -7,20 +7,22 @@
package edu.wpi.first.wpilibj.test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This JUnit Rule allows you to apply this rule to any test to allow it to run
* multiple times. This is important if you have a test that fails only
* "sometimes" and needs to be rerun to find the issue.
* This JUnit Rule allows you to apply this rule to any test to allow it to run multiple times. This
* is important if you have a test that fails only "sometimes" and needs to be rerun to find the
* issue.
*
* This code was originally found here: <a href="http://www.codeaffine.com/2013/04/10/running-junit-tests-repeatedly-without-loops/">Running JUnit Tests Repeatedly Without Loops</a>
* <p>This code was originally found here:
* <a href="http://www.codeaffine.com/2013/04/10/running-junit-tests-repeatedly-without-loops/">
* Running JUnit Tests Repeatedly Without Loops</a>
*
* @author Frank Appel
*/
@@ -28,24 +30,27 @@ public class RepeatRule implements TestRule {
@Retention(RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.METHOD})
public @interface Repeat {
public abstract int times();
/**
* The number of times to repeat the test.
*/
int times();
}
private static class RepeatStatement extends Statement {
private final int times;
private final Statement statement;
private final int m_times;
private final Statement m_statement;
private RepeatStatement(int times, Statement statement) {
this.times = times;
this.statement = statement;
m_times = times;
m_statement = statement;
}
@Override
public void evaluate() throws Throwable {
for (int i = 0; i < times; i++) {
statement.evaluate();
for (int i = 0; i < m_times; i++) {
m_statement.evaluate();
}
}
}

View File

@@ -34,23 +34,21 @@ import edu.wpi.first.wpilibj.fixtures.FilterOutputFixture;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.fixtures.RelayCrossConnectFixture;
import edu.wpi.first.wpilibj.fixtures.TiltPanCameraFixture;
import edu.wpi.first.wpilibj.interfaces.Gyro;
import edu.wpi.first.wpilibj.mockhardware.FakePotentiometerSource;
/**
* This class provides access to all of the elements on the test bench, for use
* in fixtures. This class is a singleton, you should use {@link #getInstance()}
* to obtain a reference to the {@code TestBench}.
* This class provides access to all of the elements on the test bench, for use in fixtures. This
* class is a singleton, you should use {@link #getInstance()} to obtain a reference to the {@code
* TestBench}.
*
* TODO: This needs to be updated to the most recent test bench setup.
* <p>TODO: This needs to be updated to the most recent test bench setup.
*
* @author Fredric Silberberg
*/
public final class TestBench {
/**
* The time that it takes to have a motor go from rotating at full speed to
* completely stopped
* The time that it takes to have a motor go from rotating at full speed to completely stopped.
*/
public static final double MOTOR_STOP_TIME = 0.25;
@@ -95,18 +93,21 @@ public final class TestBench {
public static final int kMovAvgTaps = 6;
public static final double kMovAvgExpectedOutput = -10.191644;
/** The Singleton instance of the Test Bench */
/**
* The Singleton instance of the Test Bench.
*/
private static TestBench instance = null;
/**
* The single constructor for the TestBench. This method is private in order
* to prevent multiple TestBench objects from being allocated
* The single constructor for the TestBench. This method is private in order to prevent multiple
* TestBench objects from being allocated.
*/
protected TestBench() {}
protected TestBench() {
}
/**
* Constructs a new set of objects representing a connected set of Talon
* controlled Motors and an encoder
* Constructs a new set of objects representing a connected set of Talon controlled Motors and an
* encoder.
*
* @return a freshly allocated Talon, Encoder pair
*/
@@ -137,8 +138,8 @@ public final class TestBench {
}
/**
* Constructs a new set of objects representing a connected set of Victor
* controlled Motors and an encoder
* Constructs a new set of objects representing a connected set of Victor controlled Motors and an
* encoder.
*
* @return a freshly allocated Victor, Encoder pair
*/
@@ -169,8 +170,8 @@ public final class TestBench {
}
/**
* Constructs a new set of objects representing a connected set of Jaguar
* controlled Motors and an encoder
* Constructs a new set of objects representing a connected set of Jaguar controlled Motors and an
* encoder.
*
* @return a freshly allocated Jaguar, Encoder pair
*/
@@ -232,7 +233,7 @@ public final class TestBench {
/*
* (non-Javadoc)
*$
*
* @see
* edu.wpi.first.wpilibj.fixtures.CANMotorEncoderFixture#givePowerCycleRelay
* ()
@@ -249,10 +250,9 @@ public final class TestBench {
}
/**
* Constructs a new set of objects representing a connected set of CANJaguar
* controlled Motors and an encoder<br>
* Note: The CANJaguar is not freshly allocated because the CANJaguar lacks a
* free() method
* Constructs a new set of objects representing a connected set of CANJaguar controlled Motors and
* an encoder<br> Note: The CANJaguar is not freshly allocated because the CANJaguar lacks a
* free() method.
*
* @return an existing CANJaguar and a freshly allocated Encoder
*/
@@ -302,20 +302,18 @@ public final class TestBench {
}
/**
* Gets two lists of possible DIO pairs for the two pairs
*$
* @return
* Gets two lists of possible DIO pairs for the two pairs.
*/
private List<List<Integer[]>> getDIOCrossConnect() {
List<List<Integer[]>> pairs = new ArrayList<List<Integer[]>>();
List<Integer[]> setA =
Arrays.asList(new Integer[][] {
Arrays.asList(new Integer[][]{
{new Integer(DIOCrossConnectA1), new Integer(DIOCrossConnectA2)},
{new Integer(DIOCrossConnectA2), new Integer(DIOCrossConnectA1)}});
pairs.add(setA);
List<Integer[]> setB =
Arrays.asList(new Integer[][] {
Arrays.asList(new Integer[][]{
{new Integer(DIOCrossConnectB1), new Integer(DIOCrossConnectB2)},
{new Integer(DIOCrossConnectB2), new Integer(DIOCrossConnectB1)}});
pairs.add(setB);
@@ -323,6 +321,7 @@ public final class TestBench {
return pairs;
}
@SuppressWarnings("JavadocMethod")
public static AnalogCrossConnectFixture getAnalogCrossConnectFixture() {
AnalogCrossConnectFixture analogIO = new AnalogCrossConnectFixture() {
@Override
@@ -338,6 +337,7 @@ public final class TestBench {
return analogIO;
}
@SuppressWarnings("JavadocMethod")
public static RelayCrossConnectFixture getRelayCrossConnectFixture() {
RelayCrossConnectFixture relay = new RelayCrossConnectFixture() {
@@ -360,9 +360,9 @@ public final class TestBench {
}
/**
* Return a single Collection containing all of the DIOCrossConnectFixtures in
* all two pair combinations
*$
* Return a single Collection containing all of the DIOCrossConnectFixtures in all two pair
* combinations.
*
* @return pairs of DIOCrossConnectFixtures
*/
public Collection<Integer[]> getDIOCrossConnectCollection() {
@@ -374,19 +374,16 @@ public final class TestBench {
}
/**
* Gets an array of pairs for the encoder to use using two different lists
*$
* @param listA
* @param listB
* Gets an array of pairs for the encoder to use using two different lists.
*
* @param flip whether this encoder needs to be flipped
* @return A list of different inputs to use for the tests
*/
private Collection<Integer[]> getPairArray(List<Integer[]> listA, List<Integer[]> listB,
boolean flip) {
boolean flip) {
Collection<Integer[]> encoderPortPairs = new ArrayList<Integer[]>();
for (Integer[] portPairsA : listA) {
ArrayList<Integer[]> construtorInput = new ArrayList<Integer[]>();
Integer inputs[] = new Integer[5];
Integer[] inputs = new Integer[5];
inputs[0] = portPairsA[0]; // InputA
inputs[1] = portPairsA[1]; // InputB
@@ -396,6 +393,7 @@ public final class TestBench {
inputs[4] = flip ? 0 : 1; // The flip bit
}
ArrayList<Integer[]> construtorInput = new ArrayList<Integer[]>();
construtorInput.add(inputs);
inputs = inputs.clone();
@@ -411,8 +409,8 @@ public final class TestBench {
}
/**
* Constructs the list of inputs to be used for the encoder test
*$
* Constructs the list of inputs to be used for the encoder test.
*
* @return A collection of different input pairs to use for the encoder
*/
public Collection<Integer[]> getEncoderDIOCrossConnectCollection() {
@@ -427,8 +425,7 @@ public final class TestBench {
}
/**
* Constructs a new set of objects representing a single-pole IIR filter with
* a noisy data source
* Constructs a new set of objects representing a single-pole IIR filter with a noisy data source.
*
* @return a single-pole IIR filter with a noisy data source
*/
@@ -437,15 +434,15 @@ public final class TestBench {
@Override
protected LinearDigitalFilter giveFilter(PIDSource source) {
return LinearDigitalFilter.singlePoleIIR(source,
kSinglePoleIIRTimeConstant,
kFilterStep);
kSinglePoleIIRTimeConstant,
kFilterStep);
}
};
}
/**
* Constructs a new set of objects representing a moving average filter with a
* noisy data source using a linear digital filter
* Constructs a new set of objects representing a moving average filter with a noisy data source
* using a linear digital filter.
*
* @return a moving average filter with a noisy data source
*/
@@ -459,8 +456,8 @@ public final class TestBench {
}
/**
* Constructs a new set of objects representing a single-pole IIR filter with
* a repeatable data source
* Constructs a new set of objects representing a single-pole IIR filter with a repeatable data
* source.
*
* @return a single-pole IIR filter with a repeatable data source
*/
@@ -469,15 +466,14 @@ public final class TestBench {
@Override
protected LinearDigitalFilter giveFilter(PIDSource source) {
return LinearDigitalFilter.singlePoleIIR(source,
kSinglePoleIIRTimeConstant,
kFilterStep);
kSinglePoleIIRTimeConstant,
kFilterStep);
}
};
}
/**
* Constructs a new set of objects representing a high-pass filter with a
* repeatable data source
* Constructs a new set of objects representing a high-pass filter with a repeatable data source.
*
* @return a high-pass filter with a repeatable data source
*/
@@ -486,14 +482,14 @@ public final class TestBench {
@Override
protected LinearDigitalFilter giveFilter(PIDSource source) {
return LinearDigitalFilter.highPass(source, kHighPassTimeConstant,
kFilterStep);
kFilterStep);
}
};
}
/**
* Constructs a new set of objects representing a moving average filter with a
* repeatable data source using a linear digital filter
* Constructs a new set of objects representing a moving average filter with a repeatable data
* source using a linear digital filter.
*
* @return a moving average filter with a repeatable data source
*/
@@ -507,9 +503,8 @@ public final class TestBench {
}
/**
* Gets the singleton of the TestBench. If the TestBench is not already
* allocated in constructs an new instance of it. Otherwise it returns the
* existing instance.
* Gets the singleton of the TestBench. If the TestBench is not already allocated in constructs an
* new instance of it. Otherwise it returns the existing instance.
*
* @return The Singleton instance of the TestBench
*/
@@ -521,10 +516,10 @@ public final class TestBench {
}
/**
* Provides access to the output stream for the test system. This should be
* used instead of System.out This is gives us a way to implement changes to
* where the output text of this test system is sent.
*$
* Provides access to the output stream for the test system. This should be used instead of
* System.out This is gives us a way to implement changes to where the output text of this test
* system is sent.
*
* @return The test bench global print stream.
*/
public static PrintStream out() {
@@ -532,10 +527,10 @@ public final class TestBench {
}
/**
* Provides access to the error stream for the test system. This should be
* used instead of System.err This is gives us a way to implement changes to
* where the output text of this test system is sent.
*$
* Provides access to the error stream for the test system. This should be used instead of
* System.err This is gives us a way to implement changes to where the output text of this test
* system is sent.
*
* @return The test bench global print stream.
*/
public static PrintStream err() {

View File

@@ -7,16 +7,6 @@
package edu.wpi.first.wpilibj.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import junit.framework.JUnit4TestAdapter;
import junit.runner.Version;
@@ -27,16 +17,24 @@ import org.junit.runner.notification.Failure;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import edu.wpi.first.wpilibj.WpiLibJTestSuite;
import edu.wpi.first.wpilibj.can.CANTestSuite;
import edu.wpi.first.wpilibj.command.CommandTestSuite;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboardTestSuite;
/**
* The WPILibJ Integeration Test Suite collects all of the tests to be run by
* junit. In order for a test to be run, it must be added the list of suite
* classes below. The tests will be run in the order they are listed in the
* suite classes annotation.
* The WPILibJ Integeration Test Suite collects all of the tests to be run by junit. In order for a
* test to be run, it must be added the list of suite classes below. The tests will be run in the
* order they are listed in the suite classes annotation.
*/
@RunWith(Suite.class)
// These are listed on separate lines to prevent merge conflicts
@@ -47,17 +45,19 @@ public class TestSuite extends AbstractTestSuite {
// Sets up the logging output
final InputStream inputStream = TestSuite.class.getResourceAsStream("/logging.properties");
try {
if (inputStream == null)
if (inputStream == null) {
throw new NullPointerException("./logging.properties was not loaded");
}
LogManager.getLogManager().readConfiguration(inputStream);
Logger.getAnonymousLogger().info("Loaded");
} catch (final IOException | NullPointerException e) {
} catch (final IOException | NullPointerException ex) {
Logger.getAnonymousLogger().severe("Could not load default logging.properties file");
Logger.getAnonymousLogger().severe(e.getMessage());
Logger.getAnonymousLogger().severe(ex.getMessage());
}
TestBench.out().println("Starting Tests");
}
private static final Logger WPILIBJ_ROOT_LOGGER = Logger.getLogger("edu.wpi.first.wpilibj");
private static final Logger WPILIBJ_COMMAND_ROOT_LOGGER = Logger
.getLogger("edu.wpi.first.wpilibj.command");
@@ -72,6 +72,9 @@ public class TestSuite extends AbstractTestSuite {
private static TestSuite instance = null;
/**
* Get the singleton instance of the test suite.
*/
public static TestSuite getInstance() {
if (instance == null) {
instance = new TestSuite();
@@ -80,13 +83,13 @@ public class TestSuite extends AbstractTestSuite {
}
/**
* This has to be public so that the JUnit4
* This has to be public so that the JUnit4.
*/
public TestSuite() {}
public TestSuite() {
}
/**
* Displays a help message for the user when they use the --help flag at
* runtime.
* Displays a help message for the user when they use the --help flag at runtime.
*/
protected static void displayHelp() {
StringBuilder helpMessage = new StringBuilder("Test Parameters help: \n");
@@ -104,7 +107,8 @@ public class TestSuite extends AbstractTestSuite {
+ QUICK_TEST_FLAG + " or " + CLASS_NAME_FILTER
+ " and run them the given number of times.\n");
helpMessage
.append("[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This documentation can be found at "
.append("[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This "
+ "documentation can be found at "
+ "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n");
helpMessage.append("\n");
helpMessage.append("\n");
@@ -113,8 +117,8 @@ public class TestSuite extends AbstractTestSuite {
}
/**
* Lets the user know that they used the TestSuite improperly and gives
* details about how to use it correctly in the future.
* Lets the user know that they used the TestSuite improperly and gives details about how to use
* it correctly in the future.
*/
protected static void displayInvalidUsage(String message, String... args) {
StringBuilder invalidMessage = new StringBuilder("Invalid Usage: " + message + "\n");
@@ -133,16 +137,16 @@ public class TestSuite extends AbstractTestSuite {
/**
* Prints the loaded tests before they are run.
*$
*
* @param classes the classes that were loaded.
*/
protected static void printLoadedTests(final Class<?>... classes) {
StringBuilder loadedTestsMessage = new StringBuilder("The following tests were loaded:\n");
Package p = null;
Package packagE = null;
for (Class<?> c : classes) {
if (c.getPackage().equals(p)) {
p = c.getPackage();
loadedTestsMessage.append(p.getName() + "\n");
if (c.getPackage().equals(packagE)) {
packagE = c.getPackage();
loadedTestsMessage.append(packagE.getName() + "\n");
}
loadedTestsMessage.append("\t" + c.getSimpleName() + "\n");
}
@@ -151,16 +155,15 @@ public class TestSuite extends AbstractTestSuite {
/**
* Parses the arguments passed at runtime and runs the appropriate tests based
* upon these arguments
*$
* Parses the arguments passed at runtime and runs the appropriate tests based upon these
* arguments
*
* @param args the args passed into the program at runtime
* @return the restults of the tests that have run. If no tests were run then
* null is returned.
* @return the restults of the tests that have run. If no tests were run then null is returned.
*/
protected static Result parseArgsRunAndGetResult(final String[] args) {
if (args.length == 0) { // If there are no args passed at runtime then just
// run all of the tests.
// run all of the tests.
printLoadedTests(TestSuite.class);
return JUnitCore.runClasses(TestSuite.class);
}
@@ -171,7 +174,6 @@ public class TestSuite extends AbstractTestSuite {
// The class filter was passed
boolean classFilter = false;
String classRegex = "";
boolean repeatFilter = false;
int repeatCount = 1;
for (String s : args) {
@@ -180,22 +182,20 @@ public class TestSuite extends AbstractTestSuite {
methodRegex = new String(s).replace(METHOD_NAME_FILTER, "");
}
if (Pattern.matches(METHOD_REPEAT_FILTER + ".*", s)) {
repeatFilter = true;
try {
repeatCount = Integer.parseInt(new String(s).replace(METHOD_REPEAT_FILTER, ""));
} catch (NumberFormatException e) {
} catch (NumberFormatException ex) {
displayInvalidUsage("The argument passed to the repeat rule was not a valid integer.",
args);
}
}
if (Pattern.matches(CLASS_NAME_FILTER + ".*", s)) {
classFilter = true;
classRegex = new String(s).replace(CLASS_NAME_FILTER, "");
classRegex = s.replace(CLASS_NAME_FILTER, "");
}
}
ArrayList<String> argsParsed = new ArrayList<String>(Arrays.asList(args));
if (argsParsed.contains(HELP_FLAG)) {
// If the user inputs the help flag then return the help message and exit
@@ -214,46 +214,46 @@ public class TestSuite extends AbstractTestSuite {
*/
class MultipleResult extends Result {
private static final long serialVersionUID = 1L;
private final List<Failure> failures = new Vector<Failure>();
private int runCount = 0;
private int ignoreCount = 0;
private long runTime = 0;
private final List<Failure> m_failures = new ArrayList<>();
private int m_runCount = 0;
private int m_ignoreCount = 0;
private long m_runTime = 0;
@Override
public int getRunCount() {
return runCount;
return m_runCount;
}
@Override
public int getFailureCount() {
return failures.size();
return m_failures.size();
}
@Override
public long getRunTime() {
return runTime;
return m_runTime;
}
@Override
public List<Failure> getFailures() {
return failures;
return m_failures;
}
@Override
public int getIgnoreCount() {
return ignoreCount;
return m_ignoreCount;
}
/**
* Adds the given result's data to this result
*$
* @param r the result to add to this result
* Adds the given result's data to this result.
*
* @param result the result to add to this result
*/
void addResult(Result r) {
failures.addAll(r.getFailures());
runCount += r.getRunCount();
ignoreCount += r.getIgnoreCount();
runTime += r.getRunTime();
void addResult(Result result) {
m_failures.addAll(result.getFailures());
m_runCount += result.getRunCount();
m_ignoreCount += result.getIgnoreCount();
m_runTime += result.getRunTime();
}
}
@@ -261,19 +261,20 @@ public class TestSuite extends AbstractTestSuite {
if (methodFilter) {
List<ClassMethodPair> pairs = (new TestSuite()).getMethodMatching(methodRegex);
if (pairs.size() == 0) {
displayInvalidUsage("None of the arguments passed to the method name filter matched.", args);
displayInvalidUsage("None of the arguments passed to the method name filter matched.",
args);
return null;
}
// Print out the list of tests before we run them
TestBench.out().println("Running the following tests:");
Class<?> classListing = null;
for (ClassMethodPair p : pairs) {
if (!p.methodClass.equals(classListing)) {
if (!p.m_methodClass.equals(classListing)) {
// Only display the class name every time it changes
classListing = p.methodClass;
classListing = p.m_methodClass;
TestBench.out().println(classListing);
}
TestBench.out().println("\t" + p.methodName);
TestBench.out().println("\t" + p.m_methodName);
}
@@ -353,9 +354,9 @@ public class TestSuite extends AbstractTestSuite {
}
/**
* This is used by ant to get the Junit tests. This is required because the
* tests try to load using a JUnit 3 framework. JUnit4 uses annotations to
* load tests. This method allows JUnit3 to load JUnit4 tests.
* This is used by ant to get the Junit tests. This is required because the tests try to load
* using a JUnit 3 framework. JUnit4 uses annotations to load tests. This method allows JUnit3 to
* load JUnit4 tests.
*/
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(TestSuite.class);
@@ -363,8 +364,8 @@ public class TestSuite extends AbstractTestSuite {
/**
* The method called at runtime
*$
* The method called at runtime.
*
* @param args The test suites to run
*/
public static void main(String[] args) {

View File

@@ -1,13 +1,11 @@
/**
* This is the starting point for the integration testing framework. This
* package should contain classes that are not explicitly for testing the
* library but instead provide the framework that the tests can extend from.
* Every test should extend from
* {@link edu.wpi.first.wpilibj.test.AbstractComsSetup} to ensure that Network
* Communications is properly instantiated before the test is run.
*$
* The {@link edu.wpi.first.wpilibj.test.TestBench} should contain the port
* numbers for all of the hardware and these values should not be explicitly
* defined anywhere else in the testing framework.
* This is the starting point for the integration testing framework. This package should contain
* classes that are not explicitly for testing the library but instead provide the framework that
* the tests can extend from. Every test should extend from
* {@link edu.wpi.first.wpilibj.test.AbstractComsSetup}
* to ensure that Network Communications is properly instantiated before the test is run. The
* {@link edu.wpi.first.wpilibj.test.TestBench} should contain the port numbers for all of the
* hardware and these values should not be explicitly defined anywhere else in the testing
* framework.
*/
package edu.wpi.first.wpilibj.test;
package edu.wpi.first.wpilibj.test;