[build] Apply spotless for java formatting (#1768)

Update checkstyle config to be compatible with spotless.

Co-authored-by: Austin Shalit <austinshalit@gmail.com>
This commit is contained in:
Peter Johnson
2020-12-29 22:45:16 -08:00
committed by GitHub
parent e563a0b7db
commit a751fa22d2
883 changed files with 16526 additions and 17751 deletions

View File

@@ -4,15 +4,6 @@
package edu.wpi.first.wpilibj;
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;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
@@ -20,6 +11,13 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
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;
/**
* This class should not be run as a test explicitly. Instead it should be extended by tests that
* use the InterruptableSensorBase.
@@ -34,7 +32,6 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
return m_interruptable;
}
@After
public void interruptTeardown() {
if (m_interruptable != null) {
@@ -43,9 +40,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
}
}
/**
* Give the interruptable sensor base that interrupts can be attached to.
*/
/** Give the interruptable sensor base that interrupts can be attached to. */
abstract InterruptableSensorBase giveInterruptableSensorBase();
/**
@@ -54,17 +49,12 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
*/
abstract void freeInterruptableSensorBase();
/**
* Perform whatever action is required to set the interrupt high.
*/
/** Perform whatever action is required to set the interrupt high. */
abstract void setInterruptHigh();
/**
* Perform whatever action is required to set the interrupt low.
*/
/** Perform whatever action is required to set the interrupt low. */
abstract void setInterruptLow();
private class InterruptCounter {
private final AtomicInteger m_count = new AtomicInteger();
@@ -79,14 +69,11 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
private class TestInterruptHandlerFunction extends InterruptHandlerFunction<InterruptCounter> {
protected final AtomicBoolean m_exceptionThrown = new AtomicBoolean(false);
/**
* Stores the time that the interrupt fires.
*/
/** Stores the time that the interrupt fires. */
final AtomicLong m_interruptFireTime = new AtomicLong();
/**
* Stores if the interrupt has completed at least once.
*/
/** Stores if the interrupt has completed at least once. */
final AtomicBoolean m_interruptComplete = new AtomicBoolean(false);
protected Exception m_ex;
final InterruptCounter m_counter;
@@ -137,7 +124,6 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
Timer.delay(0.005);
}
// Then
assertEquals("The interrupt did not fire the expected number of times", 1, counter.getCount());
// If the test within the interrupt failed
@@ -148,13 +134,13 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
assertThat(
"The interrupt did not fire within the expected time period (values in milliseconds)",
function.m_interruptFireTime.get(),
both(greaterThan(interruptTriggerTime - range)).and(lessThan(interruptTriggerTime
+ range)));
both(greaterThan(interruptTriggerTime - range))
.and(lessThan(interruptTriggerTime + range)));
assertThat(
"The readRisingTimestamp() did not return the correct value (values in seconds)",
getInterruptable().readRisingTimestamp(),
both(greaterThan((interruptTriggerTime - range) / 1e6)).and(
lessThan((interruptTriggerTime + range) / 1e6)));
both(greaterThan((interruptTriggerTime - range) / 1e6))
.and(lessThan((interruptTriggerTime + range) / 1e6)));
}
@Test(timeout = 2000)
@@ -177,13 +163,11 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
}
}
// Then
assertEquals("The interrupt did not fire the expected number of times", fireCount,
counter.getCount());
assertEquals(
"The interrupt did not fire the expected number of times", fireCount, 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))
@@ -192,11 +176,12 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
getInterruptable().requestInterrupts();
final double synchronousDelay = synchronousTimeout / 2.0;
final Runnable runnable = () -> {
Timer.delay(synchronousDelay);
setInterruptLow();
setInterruptHigh();
};
final Runnable runnable =
() -> {
Timer.delay(synchronousDelay);
setInterruptLow();
setInterruptHigh();
};
// When
@@ -211,8 +196,11 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
// Then
// The test will not have timed out and:
final double interruptRunTime = (stopTimeStamp - startTimeStamp) * 1e-6;
assertEquals("The interrupt did not run for the expected amount of time (units in seconds)",
synchronousDelay, interruptRunTime, 0.1);
assertEquals(
"The interrupt did not run for the expected amount of time (units in seconds)",
synchronousDelay,
interruptRunTime,
0.1);
}
@Test(timeout = (long) (synchronousTimeout * 1e3))
@@ -220,12 +208,14 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
// Given
getInterruptable().requestInterrupts();
//Don't fire interrupt. Expect it to timeout.
InterruptableSensorBase.WaitResult result = getInterruptable()
.waitForInterrupt(synchronousTimeout / 2);
// Don't fire interrupt. Expect it to timeout.
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))
@@ -234,18 +224,21 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
getInterruptable().requestInterrupts();
final double synchronousDelay = synchronousTimeout / 2.0;
final Runnable runnable = () -> {
Timer.delay(synchronousDelay);
setInterruptLow();
setInterruptHigh();
};
final Runnable runnable =
() -> {
Timer.delay(synchronousDelay);
setInterruptLow();
setInterruptHigh();
};
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,
assertEquals(
"The interrupt did not fire on the rising edge.",
result,
InterruptableSensorBase.WaitResult.kRisingEdge);
}
@@ -256,22 +249,24 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
getInterruptable().setUpSourceEdge(false, true);
final double synchronousDelay = synchronousTimeout / 2.0;
final Runnable runnable = () -> {
Timer.delay(synchronousDelay);
setInterruptHigh();
setInterruptLow();
};
final Runnable runnable =
() -> {
Timer.delay(synchronousDelay);
setInterruptHigh();
setInterruptLow();
};
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,
assertEquals(
"The interrupt did not fire on the falling edge.",
result,
InterruptableSensorBase.WaitResult.kFallingEdge);
}
@Test(timeout = 4000)
public void testDisableStopsInterruptFiring() {
final InterruptCounter counter = new InterruptCounter();
@@ -301,8 +296,7 @@ public abstract class AbstractInterruptTest extends AbstractComsSetup {
}
// Then
assertEquals("The interrupt did not fire the expected number of times", fireCount,
counter.getCount());
assertEquals(
"The interrupt did not fire the expected number of times", fireCount, counter.getCount());
}
}

View File

@@ -4,24 +4,20 @@
package edu.wpi.first.wpilibj;
import java.util.logging.Logger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.wpilibj.AnalogTriggerOutput.AnalogTriggerType;
import edu.wpi.first.wpilibj.fixtures.AnalogCrossConnectFixture;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
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;
/**
* Test that covers the {@link AnalogCrossConnectFixture}.
*/
/** Test that covers the {@link AnalogCrossConnectFixture}. */
public class AnalogCrossConnectTest extends AbstractInterruptTest {
private static final Logger logger = Logger.getLogger(AnalogCrossConnectTest.class.getName());
@@ -34,7 +30,6 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest {
return logger;
}
@BeforeClass
public static void setUpBeforeClass() {
analogIO = TestBench.getAnalogCrossConnectFixture();
@@ -51,7 +46,6 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest {
analogIO.setup();
}
@Test
public void testAnalogOuput() {
for (int i = 0; i < 50; i++) {
@@ -151,12 +145,11 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest {
InterruptableSensorBase giveInterruptableSensorBase() {
m_interruptTrigger = new AnalogTrigger(analogIO.getInput());
m_interruptTrigger.setLimitsVoltage(2.0, 3.0);
m_interruptTriggerOutput = new AnalogTriggerOutput(m_interruptTrigger,
AnalogTriggerType.kState);
m_interruptTriggerOutput =
new AnalogTriggerOutput(m_interruptTrigger, AnalogTriggerType.kState);
return m_interruptTriggerOutput;
}
/*
* (non-Javadoc)
*
@@ -172,7 +165,6 @@ public class AnalogCrossConnectTest extends AbstractInterruptTest {
m_interruptTrigger = null;
}
/*
* (non-Javadoc)
*

View File

@@ -4,22 +4,18 @@
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.assertEquals;
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 java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Tests the {@link AnalogPotentiometer}.
*/
/** Tests the {@link AnalogPotentiometer}. */
public class AnalogPotentiometerTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(AnalogPotentiometerTest.class.getName());
private AnalogCrossConnectFixture m_analogIO;
@@ -33,7 +29,6 @@ public class AnalogPotentiometerTest extends AbstractComsSetup {
m_analogIO = TestBench.getAnalogCrossConnectFixture();
m_potSource = new FakePotentiometerSource(m_analogIO.getOutput(), 360);
m_pot = new AnalogPotentiometer(m_analogIO.getInput(), 360.0, 0);
}
@After
@@ -62,6 +57,4 @@ public class AnalogPotentiometerTest extends AbstractComsSetup {
assertEquals(i, m_pot.get(), DOUBLE_COMPARISON_DELTA);
}
}
}

View File

@@ -4,21 +4,19 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import edu.wpi.first.wpilibj.interfaces.Accelerometer;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
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 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());
@@ -38,13 +36,13 @@ public class BuiltInAccelerometerTest extends AbstractComsSetup {
Timer.delay(1.0);
}
/**
* Test with all valid ranges to make sure unpacking is always done correctly.
*/
/** Test with all valid ranges to make sure unpacking is always done correctly. */
@Parameters
public static Collection<Accelerometer.Range[]> generateData() {
return Arrays.asList(new Accelerometer.Range[][]{{Accelerometer.Range.k2G},
{Accelerometer.Range.k4G}, {Accelerometer.Range.k8G}});
return Arrays.asList(
new Accelerometer.Range[][] {
{Accelerometer.Range.k2G}, {Accelerometer.Range.k4G}, {Accelerometer.Range.k8G}
});
}
@Override
@@ -62,5 +60,4 @@ public class BuiltInAccelerometerTest extends AbstractComsSetup {
assertEquals(1.0, m_accelerometer.getY(), kAccelerationTolerance);
assertEquals(0.0, m_accelerometer.getZ(), kAccelerationTolerance);
}
}

View File

@@ -4,17 +4,13 @@
package edu.wpi.first.wpilibj;
import java.util.logging.Logger;
import org.junit.Test;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
/**
* Tests for checking our constant and port values.
*/
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import java.util.logging.Logger;
import org.junit.Test;
/** Tests for checking our constant and port values. */
public class ConstantsPortsTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(ConstantsPortsTest.class.getName());
@@ -23,73 +19,55 @@ public class ConstantsPortsTest extends AbstractComsSetup {
return logger;
}
/**
* kDigitalChannels.
*/
/** kDigitalChannels. */
@Test
public void testDigitalChannels() {
assertEquals(31, SensorUtil.kDigitalChannels);
}
/**
* kAnalogInputChannels.
*/
/** kAnalogInputChannels. */
@Test
public void testAnalogInputChannels() {
assertEquals(8, SensorUtil.kAnalogInputChannels);
}
/**
* kAnalogOutputChannels.
*/
/** kAnalogOutputChannels. */
@Test
public void testAnalogOutputChannels() {
assertEquals(2, SensorUtil.kAnalogOutputChannels);
}
/**
* kSolenoidChannels.
*/
/** kSolenoidChannels. */
@Test
public void testSolenoidChannels() {
assertEquals(8, SensorUtil.kSolenoidChannels);
}
/**
* kPwmChannels.
*/
/** kPwmChannels. */
@Test
public void testPwmChannels() {
assertEquals(20, SensorUtil.kPwmChannels);
}
/**
* kRelayChannels.
*/
/** kRelayChannels. */
@Test
public void testRelayChannels() {
assertEquals(4, SensorUtil.kRelayChannels);
}
/**
* kPDPChannels.
*/
/** kPDPChannels. */
@Test
public void testPDPChannels() {
assertEquals(16, SensorUtil.kPDPChannels);
}
/**
* kPDPModules.
*/
/** kPDPModules. */
@Test
public void testPDPModules() {
assertEquals(63, SensorUtil.kPDPModules);
}
/**
* kPCMModules.
*/
/** kPCMModules. */
@Test
public void testPCMModules() {
assertEquals(63, SensorUtil.kPCMModules);

View File

@@ -4,9 +4,14 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.wpilibj.fixtures.FakeCounterFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -15,16 +20,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
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.
*/
/** Tests to see if the Counter is working properly. */
@RunWith(Parameterized.class)
public class CounterTest extends AbstractComsSetup {
private static FakeCounterFixture counter = null;
@@ -41,7 +37,7 @@ public class CounterTest extends AbstractComsSetup {
/**
* Constructs a Counter Test with the given inputs.
*
* @param input The input Port
* @param input The input Port
* @param output The output Port
*/
public CounterTest(Integer input, Integer output) {
@@ -73,10 +69,8 @@ public class CounterTest extends AbstractComsSetup {
return TestBench.getInstance().getDIOCrossConnectCollection();
}
@BeforeClass
public static void setUpBeforeClass() {
}
public static void setUpBeforeClass() {}
@AfterClass
public static void tearDownAfterClass() {
@@ -89,9 +83,7 @@ public class CounterTest extends AbstractComsSetup {
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() {
assertEquals("Counter did not reset to 0", 0, counter.getCounter().get());
@@ -105,8 +97,15 @@ public class CounterTest extends AbstractComsSetup {
final int count = counter.getCounter().get();
assertTrue("Fake Counter, Input: " + m_input + ", Output: " + m_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

@@ -4,9 +4,13 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.wpilibj.fixtures.DIOCrossConnectFixture;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Test;
@@ -14,15 +18,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
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. */
@RunWith(Parameterized.class)
public class DIOCrossConnectTest extends AbstractInterruptTest {
private static final Logger logger = Logger.getLogger(DIOCrossConnectTest.class.getName());
@@ -36,11 +32,11 @@ 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.
* 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 input The port for the input wire
* @param output The port for the output wire
*/
public DIOCrossConnectTest(Integer input, Integer output) {
@@ -50,7 +46,6 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
dio = new DIOCrossConnectFixture(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
@@ -77,9 +72,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
dio.reset();
}
/**
* 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() {
dio.getOutput().set(true);
@@ -88,9 +81,7 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
assertTrue("DIO Not High after .05s delay", dio.getInput().get());
}
/**
* 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() {
dio.getOutput().set(false);
@@ -99,22 +90,20 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
assertFalse("DIO Not Low after .05s delay", dio.getInput().get());
}
/**
* Tests to see if the DIO PWM functionality works.
*/
/** Tests to see if the DIO PWM functionality works. */
@Test
public void testDIOpulseWidthModulation() {
dio.getOutput().set(false);
assertFalse("DIO Not Low after no delay", dio.getInput().get());
//Set frequency to 2.0 Hz
// Set frequency to 2.0 Hz
dio.getOutput().setPWMRate(2.0);
//Enable PWM, but leave it off.
// Enable PWM, but leave it off.
dio.getOutput().enablePWM(0.0);
Timer.delay(0.5);
dio.getOutput().updateDutyCycle(0.5);
dio.getInput().requestInterrupts();
dio.getInput().setUpSourceEdge(false, true);
//TODO: Add return value from WaitForInterrupt
// TODO: Add return value from WaitForInterrupt
dio.getInput().waitForInterrupt(3.0, true);
Timer.delay(0.5);
final boolean firstCycle = dio.getInput().get();
@@ -187,7 +176,5 @@ public class DIOCrossConnectTest extends AbstractInterruptTest {
@Override
void setInterruptLow() {
dio.getOutput().set(false);
}
}

View File

@@ -4,20 +4,15 @@
package edu.wpi.first.wpilibj;
import java.util.logging.Logger;
import org.junit.Test;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
/**
* Test for the DigitalGlitchFilter class.
*/
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import java.util.logging.Logger;
import org.junit.Test;
/** Test for the DigitalGlitchFilter class. */
public class DigitalGlitchFilterTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(
DigitalGlitchFilterTest.class.getName());
private static final Logger logger = Logger.getLogger(DigitalGlitchFilterTest.class.getName());
@Override
protected Logger getClassLogger() {
@@ -26,9 +21,9 @@ public class DigitalGlitchFilterTest extends AbstractComsSetup {
/**
* 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.
* 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() {

View File

@@ -4,14 +4,11 @@
package edu.wpi.first.wpilibj;
import java.util.logging.Logger;
import org.junit.Test;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import java.util.logging.Logger;
import org.junit.Test;
public class DriverStationTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(TimerTest.class.getName());
@@ -34,8 +31,10 @@ public class DriverStationTest extends AbstractComsSetup {
long endTime = RobotController.getFPGATime();
long difference = endTime - startTime;
assertEquals("DriverStation waitForData did not wait long enough", TIMER_RUNTIME, difference,
assertEquals(
"DriverStation waitForData did not wait long enough",
TIMER_RUNTIME,
difference,
TIMER_TOLERANCE * TIMER_RUNTIME);
}
}

View File

@@ -4,9 +4,13 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.wpilibj.fixtures.FakeEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -15,16 +19,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
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.
*/
/** Test to see if the FPGA properly recognizes a mock Encoder input. */
@RunWith(Parameterized.class)
public class EncoderTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(EncoderTest.class.getName());
@@ -42,8 +37,8 @@ public class EncoderTest extends AbstractComsSetup {
}
/**
* 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
* 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
@@ -54,11 +49,11 @@ public class EncoderTest extends AbstractComsSetup {
/**
* Constructs a parametrized Encoder Test.
*
* @param inputA The port number for inputA
* @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) {
m_inputA = inputA;
@@ -81,9 +76,7 @@ public class EncoderTest extends AbstractComsSetup {
encoder = null;
}
/**
* Sets up the test and verifies that the test was reset to the default state.
*/
/** Sets up the test and verifies that the test was reset to the default state. */
@Before
public void setUp() {
encoder.setup();
@@ -95,18 +88,14 @@ public class EncoderTest extends AbstractComsSetup {
encoder.reset();
}
/**
* Tests to see if Encoders initialize to zero.
*/
/** Tests to see if Encoders initialize to zero. */
@Test
public void testDefaultState() {
int value = encoder.getEncoder().get();
assertTrue(errorMessage(0, value), value == 0);
}
/**
* Tests to see if Encoders can count up successfully.
*/
/** Tests to see if Encoders can count up successfully. */
@Test
public void testCountUp() {
int goal = 100;
@@ -115,12 +104,9 @@ public class EncoderTest extends AbstractComsSetup {
encoder.getFakeEncoderSource().execute();
int value = encoder.getEncoder().get();
assertTrue(errorMessage(goal, value), value == goal);
}
/**
* Tests to see if Encoders can count down successfully.
*/
/** Tests to see if Encoders can count down successfully. */
@Test
public void testCountDown() {
int goal = -100;
@@ -129,18 +115,27 @@ public class EncoderTest extends AbstractComsSetup {
encoder.getFakeEncoderSource().execute();
int value = encoder.getEncoder().get();
assertTrue(errorMessage(goal, value), value == goal);
}
/**
* Creates a simple message with the error that was encountered for the Encoders.
*
* @param goal The goal that was trying to be reached
* @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.
*/
private String errorMessage(int goal, int trueValue) {
return "Encoder ({In,Out}): {" + m_inputA + ", " + m_outputA + "},{" + m_inputB + ", "
+ m_outputB + "} Returned: " + trueValue + ", Wanted: " + goal;
return "Encoder ({In,Out}): {"
+ m_inputA
+ ", "
+ m_outputA
+ "},{"
+ m_inputB
+ ", "
+ m_outputB
+ "} Returned: "
+ trueValue
+ ", Wanted: "
+ goal;
}
}

View File

@@ -4,21 +4,17 @@
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.assertEquals;
import edu.wpi.first.wpilibj.fixtures.TiltPanCameraFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Tests that the {@link TiltPanCameraFixture}.
*/
/** Tests that the {@link TiltPanCameraFixture}. */
public class GyroTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(GyroTest.class.getName());
@@ -89,7 +85,6 @@ public class GyroTest extends AbstractComsSetup {
assertEquals(errorMessage(diff, TEST_ANGLE), TEST_ANGLE, angle, 10);
}
protected void testDeviationOverTime(AnalogGyro gyro) {
// Make sure that the test isn't influenced by any previous motions.
Timer.delay(0.5);
@@ -122,5 +117,4 @@ public class GyroTest extends AbstractComsSetup {
private String errorMessage(double difference, double target) {
return "Gyro angle skewed " + difference + " deg away from target " + target;
}
}

View File

@@ -24,41 +24,43 @@ public class MockDS {
@SuppressWarnings("MissingJavadocMethod")
public void start() {
m_thread = new Thread(() -> {
DatagramSocket socket;
try {
socket = new DatagramSocket();
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1110);
byte[] sendData = new byte[6];
DatagramPacket packet = new DatagramPacket(sendData, 0, 6, addr);
short sendCount = 0;
int initCount = 0;
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(20);
generateEnabledDsPacket(sendData, sendCount++);
// ~50 disabled packets are required to make the robot actually enable
// 1 is definitely not enough.
if (initCount < 50) {
initCount++;
sendData[3] = 0;
}
packet.setData(sendData);
socket.send(packet);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
socket.close();
});
m_thread =
new Thread(
() -> {
DatagramSocket socket;
try {
socket = new DatagramSocket();
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1110);
byte[] sendData = new byte[6];
DatagramPacket packet = new DatagramPacket(sendData, 0, 6, addr);
short sendCount = 0;
int initCount = 0;
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(20);
generateEnabledDsPacket(sendData, sendCount++);
// ~50 disabled packets are required to make the robot actually enable
// 1 is definitely not enough.
if (initCount < 50) {
initCount++;
sendData[3] = 0;
}
packet.setData(sendData);
socket.send(packet);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
socket.close();
});
// Because of the test setup in Java, this thread will not be stopped
// So it must be a daemon thread
m_thread.setDaemon(true);

View File

@@ -4,10 +4,18 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.wpilibj.controller.PIDController;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import edu.wpi.first.wpiutil.math.MathUtil;
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;
@@ -16,17 +24,6 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import edu.wpi.first.wpilibj.controller.PIDController;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import edu.wpi.first.wpiutil.math.MathUtil;
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 {
private static final Logger logger = Logger.getLogger(MotorEncoderTest.class.getName());
@@ -58,8 +55,12 @@ public class MotorEncoderTest extends AbstractComsSetup {
@Parameters(name = "{index}: {0}")
public static Collection<MotorEncoderFixture<?>[]> generateData() {
// logger.fine("Loading the MotorList");
return Arrays.asList(new MotorEncoderFixture<?>[][]{{TestBench.getInstance().getTalonPair()},
{TestBench.getInstance().getVictorPair()}, {TestBench.getInstance().getJaguarPair()}});
return Arrays.asList(
new MotorEncoderFixture<?>[][] {
{TestBench.getInstance().getTalonPair()},
{TestBench.getInstance().getVictorPair()},
{TestBench.getInstance().getJaguarPair()}
});
}
@Before
@@ -69,7 +70,6 @@ public class MotorEncoderTest extends AbstractComsSetup {
me.getType() + " Did not start with an initial speed of 0 instead got: " + initialSpeed,
Math.abs(initialSpeed) < 0.001);
me.setup();
}
@After
@@ -109,9 +109,13 @@ public class MotorEncoderTest extends AbstractComsSetup {
me.getMotor().set(0.2);
Timer.delay(MOTOR_RUNTIME);
int currentValue = me.getEncoder().get();
assertTrue(me.getType() + " Encoder not incremented: start: " + startValue + "; current: "
+ currentValue, startValue < currentValue);
assertTrue(
me.getType()
+ " Encoder not incremented: start: "
+ startValue
+ "; current: "
+ currentValue,
startValue < currentValue);
}
/**
@@ -125,13 +129,16 @@ public class MotorEncoderTest extends AbstractComsSetup {
me.getMotor().set(-0.2);
Timer.delay(MOTOR_RUNTIME);
int currentValue = me.getEncoder().get();
assertTrue(me.getType() + " Encoder not decremented: start: " + startValue + "; current: "
+ currentValue, startValue > currentValue);
assertTrue(
me.getType()
+ " Encoder not decremented: start: "
+ startValue
+ "; current: "
+ currentValue,
startValue > currentValue);
}
/**
* 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() {
final int counter1Start = me.getCounters()[0].get();
@@ -141,10 +148,20 @@ public class MotorEncoderTest extends AbstractComsSetup {
Timer.delay(MOTOR_RUNTIME);
int counter1End = me.getCounters()[0].get();
int counter2End = me.getCounters()[1].get();
assertTrue(me.getType() + " Counter not incremented: start: " + counter1Start + "; current: "
+ counter1End, counter1Start < counter1End);
assertTrue(me.getType() + " Counter not incremented: start: " + counter1Start + "; current: "
+ counter2End, counter2Start < counter2End);
assertTrue(
me.getType()
+ " Counter not incremented: start: "
+ counter1Start
+ "; current: "
+ counter1End,
counter1Start < counter1End);
assertTrue(
me.getType()
+ " Counter not incremented: start: "
+ counter1Start
+ "; current: "
+ counter2End,
counter2Start < counter2End);
me.reset();
encodersResetCheck(me);
}
@@ -156,7 +173,8 @@ public class MotorEncoderTest extends AbstractComsSetup {
@Test
public void testSetHighForwardSpeed() {
me.getMotor().set(15);
assertTrue(me.getType() + " Motor speed was not close to 1.0, was: " + me.getMotor().get(),
assertTrue(
me.getType() + " Motor speed was not close to 1.0, was: " + me.getMotor().get(),
me.isMotorSpeedWithinRange(1.0, 0.001));
}
@@ -167,11 +185,11 @@ public class MotorEncoderTest extends AbstractComsSetup {
@Test
public void testSetHighReverseSpeed() {
me.getMotor().set(-15);
assertTrue(me.getType() + " Motor speed was not close to 1.0, was: " + me.getMotor().get(),
assertTrue(
me.getType() + " Motor speed was not close to 1.0, was: " + me.getMotor().get(),
me.isMotorSpeedWithinRange(-1.0, 0.001));
}
@Test
public void testPositionPIDController() {
try (PIDController pidController = new PIDController(0.001, 0.0005, 0)) {
@@ -179,17 +197,20 @@ public class MotorEncoderTest extends AbstractComsSetup {
pidController.setIntegratorRange(-0.2, 0.2);
pidController.setSetpoint(1000);
try (Notifier pidRunner = new Notifier(() -> {
var speed = pidController.calculate(me.getEncoder().getDistance());
me.getMotor().set(MathUtil.clamp(speed, -0.2, 0.2));
})) {
try (Notifier pidRunner =
new Notifier(
() -> {
var speed = pidController.calculate(me.getEncoder().getDistance());
me.getMotor().set(MathUtil.clamp(speed, -0.2, 0.2));
})) {
pidRunner.startPeriodic(pidController.getPeriod());
Timer.delay(10.0);
pidRunner.stop();
assertTrue(
"PID loop did not reach reference within 10 seconds. The current error was"
+ pidController.getPositionError(), pidController.atSetpoint());
+ pidController.getPositionError(),
pidController.atSetpoint());
}
}
}
@@ -201,16 +222,20 @@ public class MotorEncoderTest extends AbstractComsSetup {
pidController.setTolerance(200);
pidController.setSetpoint(600);
try (Notifier pidRunner = new Notifier(() -> {
var speed = filter.calculate(me.getEncoder().getRate());
me.getMotor().set(MathUtil.clamp(speed, -0.3, 0.3));
})) {
try (Notifier pidRunner =
new Notifier(
() -> {
var speed = filter.calculate(me.getEncoder().getRate());
me.getMotor().set(MathUtil.clamp(speed, -0.3, 0.3));
})) {
pidRunner.startPeriodic(pidController.getPeriod());
Timer.delay(10.0);
pidRunner.stop();
assertTrue("PID loop did not reach reference within 10 seconds. The error was: "
+ pidController.getPositionError(), pidController.atSetpoint());
assertTrue(
"PID loop did not reach reference within 10 seconds. The error was: "
+ pidController.getPositionError(),
pidController.atSetpoint());
}
}
}
@@ -221,18 +246,18 @@ public class MotorEncoderTest extends AbstractComsSetup {
* @param me The MotorEncoderFixture under test
*/
private void encodersResetCheck(MotorEncoderFixture<?> me) {
assertEquals(me.getType() + " Encoder value was incorrect after reset.", me.getEncoder().get(),
0);
assertEquals(me.getType() + " Motor value was incorrect after reset.", me.getMotor().get(), 0,
0);
assertEquals(me.getType() + " Counter1 value was incorrect after reset.",
me.getCounters()[0].get(), 0);
assertEquals(me.getType() + " Counter2 value was incorrect after reset.",
me.getCounters()[1].get(), 0);
assertEquals(
me.getType() + " Encoder value was incorrect after reset.", me.getEncoder().get(), 0);
assertEquals(
me.getType() + " Motor value was incorrect after reset.", me.getMotor().get(), 0, 0);
assertEquals(
me.getType() + " Counter1 value was incorrect after reset.", me.getCounters()[0].get(), 0);
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
assertTrue(me.getType() + " Encoder.getStopped() returned false after the motor was reset.",
assertTrue(
me.getType() + " Encoder.getStopped() returned false after the motor was reset.",
me.getEncoder().getStopped());
}
}

View File

@@ -4,10 +4,15 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
@@ -15,23 +20,13 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
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 {
static MotorEncoderFixture<?> fixture = null;
private static final double motorspeed = 0.2;
private static final double delaytime = 0.3;
/**
* Constructs the test.
*
@@ -49,8 +44,12 @@ public class MotorInvertingTest extends AbstractComsSetup {
@Parameters(name = "{index}: {0}")
public static Collection<MotorEncoderFixture<?>[]> generateData() {
// logger.fine("Loading the MotorList");
return Arrays.asList(new MotorEncoderFixture<?>[][]{{TestBench.getInstance().getTalonPair()},
{TestBench.getInstance().getVictorPair()}, {TestBench.getInstance().getJaguarPair()}});
return Arrays.asList(
new MotorEncoderFixture<?>[][] {
{TestBench.getInstance().getTalonPair()},
{TestBench.getInstance().getVictorPair()},
{TestBench.getInstance().getJaguarPair()}
});
}
private static final Logger logger = Logger.getLogger(MotorInvertingTest.class.getName());
@@ -82,8 +81,9 @@ public class MotorInvertingTest extends AbstractComsSetup {
fixture.getMotor().setInverted(true);
fixture.getMotor().set(motorspeed);
Timer.delay(delaytime);
assertFalse("Inverting with Positive value does not change direction", fixture.getEncoder()
.getDirection() == initDirection);
assertFalse(
"Inverting with Positive value does not change direction",
fixture.getEncoder().getDirection() == initDirection);
fixture.getMotor().set(0);
}
@@ -96,8 +96,9 @@ public class MotorInvertingTest extends AbstractComsSetup {
fixture.getMotor().setInverted(true);
fixture.getMotor().set(-motorspeed);
Timer.delay(delaytime);
assertFalse("Inverting with Negative value does not change direction", fixture.getEncoder()
.getDirection() == initDirection);
assertFalse(
"Inverting with Negative value does not change direction",
fixture.getEncoder().getDirection() == initDirection);
fixture.getMotor().set(0);
}
@@ -110,8 +111,9 @@ public class MotorInvertingTest extends AbstractComsSetup {
fixture.getMotor().setInverted(true);
fixture.getMotor().set(-motorspeed);
Timer.delay(delaytime);
assertTrue("Inverting with Switching value does change direction", fixture.getEncoder()
.getDirection() == initDirection);
assertTrue(
"Inverting with Switching value does change direction",
fixture.getEncoder().getDirection() == initDirection);
fixture.getMotor().set(0);
}
@@ -124,8 +126,9 @@ public class MotorInvertingTest extends AbstractComsSetup {
fixture.getMotor().setInverted(true);
fixture.getMotor().set(motorspeed);
Timer.delay(delaytime);
assertTrue("Inverting with Switching value does change direction", fixture.getEncoder()
.getDirection() == initDirection);
assertTrue(
"Inverting with Switching value does change direction",
fixture.getEncoder().getDirection() == initDirection);
fixture.getMotor().set(0);
}
}

View File

@@ -4,23 +4,18 @@
package edu.wpi.first.wpilibj;
import java.util.logging.Logger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
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;
/**
* Test that covers the {@link Compressor}.
*/
/** Test that covers the {@link Compressor}. */
public class PCMTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(PCMTest.class.getName());
/*
@@ -73,9 +68,7 @@ public class PCMTest extends AbstractComsSetup {
fakePressureSwitch.set(false);
}
/**
* 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 {
final double range = 0.5;
@@ -85,19 +78,23 @@ public class PCMTest extends AbstractComsSetup {
// Turn on the compressor
fakePressureSwitch.set(true);
Timer.delay(kCompressorDelayTime);
assertEquals("Compressor did not turn on when the pressure switch turned on.",
kCompressorOnVoltage, fakeCompressor.getVoltage(), range);
assertEquals(
"Compressor did not turn on when the pressure switch turned on.",
kCompressorOnVoltage,
fakeCompressor.getVoltage(),
range);
// Turn off the compressor
fakePressureSwitch.set(false);
Timer.delay(kCompressorDelayTime);
assertEquals("Compressor did not turn off when the pressure switch turned off.",
kCompressorOffVoltage, fakeCompressor.getVoltage(), range);
assertEquals(
"Compressor did not turn off when the pressure switch turned off.",
kCompressorOffVoltage,
fakeCompressor.getVoltage(),
range);
}
/**
* 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 {
reset();
@@ -162,22 +159,20 @@ 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.close();
}
/**
* 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 testOneShot() throws Exception {
reset();

View File

@@ -4,10 +4,18 @@
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 edu.wpi.first.hal.can.CANMessageNotFoundException;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
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;
@@ -16,19 +24,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import edu.wpi.first.hal.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}.
*/
/** Test that covers the {@link PowerDistributionPanel}. */
@RunWith(Parameterized.class)
public class PDPTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(PDPTest.class.getName());
@@ -49,7 +45,6 @@ public class PDPTest extends AbstractComsSetup {
me = null;
}
@SuppressWarnings("MissingJavadocMethod")
public PDPTest(MotorEncoderFixture<?> mef, Double expectedCurrentDraw) {
logger.fine("Constructor with: " + mef.getType());
@@ -65,8 +60,7 @@ public class PDPTest extends AbstractComsSetup {
@Parameters(name = "{index}: {0}, Expected Stopped Current Draw: {1}")
public static Collection<Object[]> generateData() {
// logger.fine("Loading the MotorList");
return Arrays.asList(new Object[][]{
{TestBench.getInstance().getTalonPair(), 0.0}});
return Arrays.asList(new Object[][] {{TestBench.getInstance().getTalonPair(), 0.0}});
}
@After
@@ -74,22 +68,20 @@ public class PDPTest extends AbstractComsSetup {
me.reset();
}
/**
* 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 {
Timer.delay(0.25);
/* The Current should be 0 */
assertEquals("The low current was not within the expected range.", m_expectedStoppedCurrentDraw,
pdp.getCurrent(me.getPDPChannel()), 0.001);
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 {
/* Set the motor to full forward */
@@ -97,8 +89,10 @@ public class PDPTest extends AbstractComsSetup {
Timer.delay(2);
/* 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(m_expectedStoppedCurrentDraw)));
assertThat(
"The driven current is not greater than the resting current.",
pdp.getCurrent(me.getPDPChannel()),
is(greaterThan(m_expectedStoppedCurrentDraw)));
}
@Override

View File

@@ -4,11 +4,21 @@
package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.wpilibj.controller.PIDController;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.smartdashboard.SendableBuilderImpl;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
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;
@@ -18,23 +28,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.wpilibj.controller.PIDController;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.smartdashboard.SendableBuilderImpl;
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;
/**
* Test that covers the {@link PIDController}.
*/
/** Test that covers the {@link PIDController}. */
@RunWith(Parameterized.class)
public class PIDTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(PIDTest.class.getName());
@@ -55,7 +49,6 @@ public class PIDTest extends AbstractComsSetup {
return logger;
}
@SuppressWarnings({"ParameterName", "MissingJavadocMethod"})
public PIDTest(Double p, Double i, Double d, MotorEncoderFixture<?> mef) {
logger.fine("Constructor with: " + mef.getType());
@@ -68,7 +61,6 @@ public class PIDTest extends AbstractComsSetup {
this.k_d = d;
}
@Parameters
public static Collection<Object[]> generateData() {
// logger.fine("Loading the MotorList");
@@ -77,16 +69,19 @@ 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[][]{{kp, ki, kd, TestBench.getInstance().getTalonPair()},
{kp, ki, kd, TestBench.getInstance().getVictorPair()},
{kp, ki, kd, TestBench.getInstance().getJaguarPair()}}));
data.addAll(
Arrays.asList(
new Object[][] {
{kp, ki, kd, TestBench.getInstance().getTalonPair()},
{kp, ki, kd, TestBench.getInstance().getVictorPair()},
{kp, ki, kd, TestBench.getInstance().getJaguarPair()}
}));
}
return data;
}
@BeforeClass
public static void setUpBeforeClass() {
}
public static void setUpBeforeClass() {}
@AfterClass
public static void tearDownAfterClass() {
@@ -127,8 +122,11 @@ public class PIDTest extends AbstractComsSetup {
setupIntegratorRange();
double reference = 2500.0;
m_controller.setSetpoint(reference);
assertEquals("PID.getPositionError() did not start at " + reference,
reference, m_controller.getPositionError(), 0);
assertEquals(
"PID.getPositionError() did not start at " + reference,
reference,
m_controller.getPositionError(),
0);
m_builder.updateTable();
assertEquals(k_p, m_table.getEntry("Kp").getDouble(9999999), 0);
assertEquals(k_i, m_table.getEntry("Ki").getDouble(9999999), 0);
@@ -153,25 +151,35 @@ public class PIDTest extends AbstractComsSetup {
double reference = 1000.0;
assertEquals(pidData() + "did not start at 0", 0, me.getMotor().get(), 0);
m_controller.setSetpoint(reference);
assertEquals(pidData() + "did not have an error of " + reference, reference,
m_controller.getPositionError(), 0);
Notifier pidRunner = new Notifier(
() -> me.getMotor().set(m_controller.calculate(me.getEncoder().getDistance())));
assertEquals(
pidData() + "did not have an error of " + reference,
reference,
m_controller.getPositionError(),
0);
Notifier pidRunner =
new Notifier(
() -> me.getMotor().set(m_controller.calculate(me.getEncoder().getDistance())));
pidRunner.startPeriodic(m_controller.getPeriod());
Timer.delay(5);
pidRunner.stop();
assertTrue(pidData() + "Was not on Target. Controller Error: "
+ m_controller.getPositionError(), m_controller.atSetpoint());
assertTrue(
pidData() + "Was not on Target. Controller Error: " + m_controller.getPositionError(),
m_controller.atSetpoint());
pidRunner.close();
}
private String pidData() {
return me.getType() + " PID {P:" + m_controller.getP() + " I:" + m_controller.getI() + " D:"
+ m_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() {
setupIntegratorRange();

View File

@@ -4,11 +4,9 @@
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.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableInstance;
@@ -19,14 +17,12 @@ import edu.wpi.first.wpilibj.fixtures.RelayCrossConnectFixture;
import edu.wpi.first.wpilibj.smartdashboard.SendableBuilderImpl;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Tests the {@link RelayCrossConnectFixture}.
*/
/** Tests the {@link RelayCrossConnectFixture}. */
public class RelayCrossConnectTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(RelayCrossConnectTest.class.getName());
private static final NetworkTable table =
@@ -34,7 +30,6 @@ public class RelayCrossConnectTest extends AbstractComsSetup {
private RelayCrossConnectFixture m_relayFixture;
private SendableBuilderImpl m_builder;
@Before
public void setUp() {
m_relayFixture = TestBench.getRelayCrossConnectFixture();
@@ -55,10 +50,10 @@ public class RelayCrossConnectTest extends AbstractComsSetup {
m_relayFixture.getRelay().setDirection(Direction.kBoth);
m_relayFixture.getRelay().set(Value.kOn);
m_builder.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());
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(Value.kOn, m_relayFixture.getRelay().get());
assertEquals("On", table.getEntry("Value").getString(""));
}
@@ -68,11 +63,10 @@ public class RelayCrossConnectTest extends AbstractComsSetup {
m_relayFixture.getRelay().setDirection(Direction.kBoth);
m_relayFixture.getRelay().set(Value.kForward);
m_builder.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", m_relayFixture
.getInputTwo()
.get());
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", m_relayFixture.getInputTwo().get());
assertEquals(Value.kForward, m_relayFixture.getRelay().get());
assertEquals("Forward", table.getEntry("Value").getString(""));
}
@@ -82,11 +76,10 @@ public class RelayCrossConnectTest extends AbstractComsSetup {
m_relayFixture.getRelay().setDirection(Direction.kBoth);
m_relayFixture.getRelay().set(Value.kReverse);
m_builder.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", m_relayFixture
.getInputTwo()
.get());
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", m_relayFixture.getInputTwo().get());
assertEquals(Value.kReverse, m_relayFixture.getRelay().get());
assertEquals("Reverse", table.getEntry("Value").getString(""));
}
@@ -96,9 +89,11 @@ public class RelayCrossConnectTest extends AbstractComsSetup {
m_relayFixture.getRelay().setDirection(Direction.kForward);
m_relayFixture.getRelay().set(Value.kOn);
m_builder.updateTable();
assertFalse("Input one was not low when relay set Value.kOn in kForward Direction",
assertFalse(
"Input one was not low when relay set Value.kOn in kForward Direction",
m_relayFixture.getInputOne().get());
assertTrue("Input two was not high when relay set Value.kOn in kForward Direction",
assertTrue(
"Input two was not high when relay set Value.kOn in kForward Direction",
m_relayFixture.getInputTwo().get());
assertEquals(Value.kOn, m_relayFixture.getRelay().get());
assertEquals("On", table.getEntry("Value").getString(""));
@@ -109,9 +104,11 @@ public class RelayCrossConnectTest extends AbstractComsSetup {
m_relayFixture.getRelay().setDirection(Direction.kReverse);
m_relayFixture.getRelay().set(Value.kOn);
m_builder.updateTable();
assertTrue("Input one was not high when relay set Value.kOn in kReverse Direction",
assertTrue(
"Input one was not high when relay set Value.kOn in kReverse Direction",
m_relayFixture.getInputOne().get());
assertFalse("Input two was not low when relay set Value.kOn in kReverse Direction",
assertFalse(
"Input two was not low when relay set Value.kOn in kReverse Direction",
m_relayFixture.getInputTwo().get());
assertEquals(Value.kOn, m_relayFixture.getRelay().get());
assertEquals("On", table.getEntry("Value").getString(""));
@@ -143,5 +140,4 @@ public class RelayCrossConnectTest extends AbstractComsSetup {
protected Logger getClassLogger() {
return logger;
}
}

View File

@@ -4,18 +4,16 @@
package edu.wpi.first.wpilibj;
import java.util.logging.Logger;
import static org.junit.Assert.assertTrue;
import edu.wpi.first.wpilibj.fixtures.SampleFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.wpi.first.wpilibj.fixtures.SampleFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
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
@@ -59,5 +57,4 @@ public class SampleTest extends AbstractComsSetup {
Timer.delay(0.5);
assertTrue(true);
}
}

View File

@@ -4,14 +4,11 @@
package edu.wpi.first.wpilibj;
import java.util.logging.Logger;
import org.junit.Test;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import static org.junit.Assert.assertEquals;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import java.util.logging.Logger;
import org.junit.Test;
public class TimerTest extends AbstractComsSetup {
private static final Logger logger = Logger.getLogger(TimerTest.class.getName());
@@ -35,8 +32,10 @@ public class TimerTest extends AbstractComsSetup {
// Then
long offset = difference - TIMER_RUNTIME;
assertEquals("Timer.delay ran " + offset + " microseconds too long", TIMER_RUNTIME, difference,
assertEquals(
"Timer.delay ran " + offset + " microseconds too long",
TIMER_RUNTIME,
difference,
TIMER_TOLERANCE);
}
}

View File

@@ -4,22 +4,34 @@
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.test.AbstractTestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import edu.wpi.first.wpilibj.test.AbstractTestSuite;
/**
* 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.
*/
@RunWith(Suite.class)
@SuiteClasses({AnalogCrossConnectTest.class, AnalogPotentiometerTest.class,
BuiltInAccelerometerTest.class, ConstantsPortsTest.class, CounterTest.class,
DigitalGlitchFilterTest.class, DIOCrossConnectTest.class,
DriverStationTest.class, EncoderTest.class, GyroTest.class, MotorEncoderTest.class,
MotorInvertingTest.class, PCMTest.class, PDPTest.class, PIDTest.class,
RelayCrossConnectTest.class, SampleTest.class, TimerTest.class})
public class WpiLibJTestSuite extends AbstractTestSuite {
}
@SuiteClasses({
AnalogCrossConnectTest.class,
AnalogPotentiometerTest.class,
BuiltInAccelerometerTest.class,
ConstantsPortsTest.class,
CounterTest.class,
DigitalGlitchFilterTest.class,
DIOCrossConnectTest.class,
DriverStationTest.class,
EncoderTest.class,
GyroTest.class,
MotorEncoderTest.class,
MotorInvertingTest.class,
PCMTest.class,
PDPTest.class,
PIDTest.class,
RelayCrossConnectTest.class,
SampleTest.class,
TimerTest.class
})
public class WpiLibJTestSuite extends AbstractTestSuite {}

View File

@@ -4,10 +4,9 @@
package edu.wpi.first.wpilibj.can;
import org.junit.Test;
import edu.wpi.first.hal.can.CANJNI;
import edu.wpi.first.hal.can.CANStatus;
import org.junit.Test;
public class CANStatusTest {
@Test

View File

@@ -7,9 +7,7 @@ package edu.wpi.first.wpilibj.fixtures;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.AnalogOutput;
/**
* A fixture that connects an {@link AnalogInput} and an {@link AnalogOutput}.
*/
/** A fixture that connects an {@link AnalogInput} and an {@link AnalogOutput}. */
public abstract class AnalogCrossConnectFixture implements ITestFixture {
private boolean m_initialized = false;
@@ -20,7 +18,6 @@ public abstract class AnalogCrossConnectFixture implements ITestFixture {
protected abstract AnalogOutput giveAnalogOutput();
private void initialize() {
synchronized (this) {
if (!m_initialized) {
@@ -66,9 +63,7 @@ public abstract class AnalogCrossConnectFixture implements ITestFixture {
return true;
}
/**
* Analog Output.
*/
/** Analog Output. */
public final AnalogOutput getOutput() {
initialize();
return m_output;
@@ -78,6 +73,4 @@ public abstract class AnalogCrossConnectFixture implements ITestFixture {
initialize();
return m_input;
}
}

View File

@@ -4,15 +4,12 @@
package edu.wpi.first.wpilibj.fixtures;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DigitalOutput;
import java.util.logging.Level;
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.
*/
/** Connects a digital input to a digital output. */
public class DIOCrossConnectFixture implements ITestFixture {
private static final Logger logger = Logger.getLogger(DIOCrossConnectFixture.class.getName());
@@ -23,7 +20,7 @@ public class DIOCrossConnectFixture implements ITestFixture {
/**
* Constructs using two pre-allocated digital objects.
*
* @param input The input
* @param input The input
* @param output The output.
*/
public DIOCrossConnectFixture(DigitalInput input, DigitalOutput output) {
@@ -37,7 +34,7 @@ public class DIOCrossConnectFixture implements ITestFixture {
/**
* Constructs a {@link DIOCrossConnectFixture} using the ports of the digital objects.
*
* @param input The port of the {@link DigitalInput}
* @param input The port of the {@link DigitalInput}
* @param output The port of the {@link DigitalOutput}
*/
public DIOCrossConnectFixture(Integer input, Integer output) {
@@ -83,5 +80,4 @@ public class DIOCrossConnectFixture implements ITestFixture {
}
return true;
}
}

View File

@@ -4,15 +4,12 @@
package edu.wpi.first.wpilibj.fixtures;
import edu.wpi.first.wpilibj.Counter;
import edu.wpi.first.wpilibj.mockhardware.FakeCounterSource;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.Counter;
import edu.wpi.first.wpilibj.mockhardware.FakeCounterSource;
/**
* A fixture that can test the {@link Counter} using a {@link DIOCrossConnectFixture}.
*/
/** A fixture that can test the {@link Counter} using a {@link DIOCrossConnectFixture}. */
public class FakeCounterFixture implements ITestFixture {
private static final Logger logger = Logger.getLogger(FakeEncoderFixture.class.getName());
@@ -33,11 +30,10 @@ public class FakeCounterFixture implements ITestFixture {
m_counter = new Counter(dio.getInput());
}
/**
* Constructs a FakeCounterFixture using two port numbers.
*
* @param input the input port
* @param input the input port
* @param output the output port
*/
public FakeCounterFixture(int input, int output) {
@@ -65,7 +61,6 @@ public class FakeCounterFixture implements ITestFixture {
return m_counter;
}
/*
* (non-Javadoc)
*
@@ -74,7 +69,6 @@ public class FakeCounterFixture implements ITestFixture {
@Override
public boolean setup() {
return true;
}
/*
@@ -104,6 +98,4 @@ public class FakeCounterFixture implements ITestFixture {
}
return true;
}
}

View File

@@ -4,10 +4,9 @@
package edu.wpi.first.wpilibj.fixtures;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.mockhardware.FakeEncoderSource;
import java.util.logging.Logger;
/**
* An encoder that uses two {@link DIOCrossConnectFixture DIOCrossConnectFixtures} to test the
@@ -25,9 +24,7 @@ public class FakeEncoderFixture implements ITestFixture {
private final Encoder m_encoder;
private int[] m_encoderPort = new int[2];
/**
* Constructs a FakeEncoderFixture from two DIOCrossConnectFixture.
*/
/** Constructs a FakeEncoderFixture from two DIOCrossConnectFixture. */
public FakeEncoderFixture(DIOCrossConnectFixture dio1, DIOCrossConnectFixture dio2) {
assert dio1 != null;
assert dio2 != null;
@@ -38,9 +35,7 @@ public class FakeEncoderFixture implements ITestFixture {
m_encoder = new Encoder(dio1.getInput(), dio2.getInput());
}
/**
* Construcst a FakeEncoderFixture from a set of Digital I/O ports.
*/
/** Construcst a FakeEncoderFixture from a set of Digital I/O ports. */
public FakeEncoderFixture(int inputA, int outputA, int inputB, int outputB) {
assert outputA != outputB;
assert outputA != inputA;
@@ -108,6 +103,4 @@ public class FakeEncoderFixture implements ITestFixture {
}
return true;
}
}

View File

@@ -4,9 +4,6 @@
package edu.wpi.first.wpilibj.fixtures;
import java.lang.reflect.ParameterizedType;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.Counter;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Encoder;
@@ -14,13 +11,16 @@ import edu.wpi.first.wpilibj.PWM;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.test.TestBench;
import java.lang.reflect.ParameterizedType;
import java.util.logging.Logger;
/**
* 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.
* 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 MotorEncoderFixture<T extends SpeedController> implements ITestFixture {
private static final Logger logger = Logger.getLogger(MotorEncoderFixture.class.getName());
@@ -32,11 +32,8 @@ public abstract class MotorEncoderFixture<T extends SpeedController> implements
protected DigitalInput m_alphaSource; // Stored so it can be freed at tear down
protected DigitalInput m_betaSource;
/**
* Default constructor for a MotorEncoderFixture.
*/
public MotorEncoderFixture() {
}
/** Default constructor for a MotorEncoderFixture. */
public MotorEncoderFixture() {}
public abstract int getPDPChannel();
@@ -75,7 +72,6 @@ public abstract class MotorEncoderFixture<T extends SpeedController> implements
m_alphaSource = giveDigitalInputA();
m_betaSource = giveDigitalInputB();
m_encoder = new Encoder(m_alphaSource, m_betaSource);
m_counters[0] = new Counter(m_alphaSource);
m_counters[1] = new Counter(m_betaSource);
@@ -130,7 +126,7 @@ public abstract class MotorEncoderFixture<T extends SpeedController> implements
* 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 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'.
*/
@@ -160,7 +156,6 @@ public abstract class MotorEncoderFixture<T extends SpeedController> implements
return wasReset;
}
/**
* 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
@@ -232,11 +227,10 @@ 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

@@ -7,9 +7,7 @@ package edu.wpi.first.wpilibj.fixtures;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Relay;
/**
* A connection between a {@link Relay} and two {@link DigitalInput DigitalInputs}.
*/
/** A connection between a {@link Relay} and two {@link DigitalInput DigitalInputs}. */
public abstract class RelayCrossConnectFixture implements ITestFixture {
private DigitalInput m_inputOne;
private DigitalInput m_inputTwo;
@@ -18,7 +16,6 @@ public abstract class RelayCrossConnectFixture implements ITestFixture {
private boolean m_initialized = false;
private boolean m_freed = false;
protected abstract Relay giveRelay();
protected abstract DigitalInput giveInputOne();
@@ -86,8 +83,10 @@ public abstract class RelayCrossConnectFixture implements ITestFixture {
m_inputTwo.close();
m_freed = true;
} else {
throw new RuntimeException("You attempted to free the "
+ RelayCrossConnectFixture.class.getSimpleName() + " multiple times");
throw new RuntimeException(
"You attempted to free the "
+ RelayCrossConnectFixture.class.getSimpleName()
+ " multiple times");
}
return true;
}

View File

@@ -4,7 +4,6 @@
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.

View File

@@ -4,11 +4,10 @@
package edu.wpi.first.wpilibj.fixtures;
import java.util.logging.Logger;
import edu.wpi.first.wpilibj.AnalogGyro;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.Timer;
import java.util.logging.Logger;
/**
* A class to represent the a physical Camera with two servos (tilt and pan) designed to test to see
@@ -24,7 +23,6 @@ public abstract class TiltPanCameraFixture implements ITestFixture {
private Servo m_pan;
private boolean m_initialized = false;
protected abstract AnalogGyro giveGyro();
protected abstract AnalogGyro giveGyroParam(int center, double offset);
@@ -33,11 +31,8 @@ public abstract class TiltPanCameraFixture implements ITestFixture {
protected abstract Servo givePan();
/**
* Constructs the TiltPanCamera.
*/
public TiltPanCameraFixture() {
}
/** Constructs the TiltPanCamera. */
public TiltPanCameraFixture() {}
@Override
public boolean setup() {
@@ -99,15 +94,14 @@ public abstract class TiltPanCameraFixture implements ITestFixture {
m_tilt = null;
m_pan.close();
m_pan = null;
if (m_gyro != null) { //in case not freed during gyro tests
if (m_gyro != null) { // in case not freed during gyro tests
m_gyro.close();
m_gyro = null;
}
if (m_gyroParam != null) { //in case gyro tests failed before getting to this point
if (m_gyroParam != null) { // in case gyro tests failed before getting to this point
m_gyroParam.close();
m_gyroParam = null;
}
return true;
}
}

View File

@@ -7,9 +7,7 @@ package edu.wpi.first.wpilibj.mockhardware;
import edu.wpi.first.wpilibj.DigitalOutput;
import edu.wpi.first.wpilibj.Timer;
/**
* Simulates an encoder for testing purposes.
*/
/** Simulates an encoder for testing purposes. */
public class FakeCounterSource implements AutoCloseable {
private Thread m_task;
private int m_count;
@@ -17,9 +15,7 @@ public class FakeCounterSource implements AutoCloseable {
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 {
FakeCounterSource m_encoder;
@@ -65,9 +61,7 @@ public class FakeCounterSource implements AutoCloseable {
initEncoder();
}
/**
* Destroy Object with minimum memory leak.
*/
/** Destroy Object with minimum memory leak. */
@Override
public void close() {
m_task = null;
@@ -78,25 +72,19 @@ public class FakeCounterSource implements AutoCloseable {
}
}
/**
* Common initailization code.
*/
/** Common initailization code. */
private void initEncoder() {
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();
@@ -107,9 +95,7 @@ public class FakeCounterSource implements AutoCloseable {
Timer.delay(0.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();
complete();

View File

@@ -7,9 +7,7 @@ package edu.wpi.first.wpilibj.mockhardware;
import edu.wpi.first.wpilibj.DigitalOutput;
import edu.wpi.first.wpilibj.Timer;
/**
* Emulates a quadrature encoder.
*/
/** Emulates a quadrature encoder. */
public class FakeEncoderSource implements AutoCloseable {
private Thread m_task;
private int m_count;
@@ -19,9 +17,7 @@ public class FakeEncoderSource implements AutoCloseable {
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 {
FakeEncoderSource m_encoder;
@@ -88,9 +84,7 @@ public class FakeEncoderSource implements AutoCloseable {
initQuadEncoder();
}
/**
* Frees the resource.
*/
/** Frees the resource. */
@Override
public void close() {
m_task = null;
@@ -100,9 +94,7 @@ public class FakeEncoderSource implements AutoCloseable {
}
}
/**
* Common initialization code.
*/
/** Common initialization code. */
private void initQuadEncoder() {
m_milliSec = 1;
m_forward = true;
@@ -111,16 +103,12 @@ public class FakeEncoderSource implements AutoCloseable {
m_outputB.set(false);
}
/**
* 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();
@@ -131,9 +119,7 @@ public class FakeEncoderSource implements AutoCloseable {
Timer.delay(0.01);
}
/**
* Runs and waits for thread to end before returning.
*/
/** Runs and waits for thread to end before returning. */
public void execute() {
start();
complete();

View File

@@ -6,9 +6,7 @@ package edu.wpi.first.wpilibj.mockhardware;
import edu.wpi.first.wpilibj.AnalogOutput;
/**
* A fake source to provide output to a {@link edu.wpi.first.wpilibj.interfaces.Potentiometer}.
*/
/** A fake source to provide output to a {@link edu.wpi.first.wpilibj.interfaces.Potentiometer}. */
public class FakePotentiometerSource implements AutoCloseable {
private AnalogOutput m_output;
private boolean m_initOutput;
@@ -19,7 +17,7 @@ public class FakePotentiometerSource implements AutoCloseable {
/**
* Constructs the fake source.
*
* @param output The analog port to output the signal on
* @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) {
@@ -77,9 +75,7 @@ public class FakePotentiometerSource implements AutoCloseable {
return voltage * (m_potMaxAngle / m_potMaxVoltage);
}
/**
* Frees the resouce.
*/
/** Frees the resouce. */
@Override
public void close() {
if (m_initOutput) {

View File

@@ -4,20 +4,18 @@
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 edu.wpi.first.hal.HAL;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.MockDS;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
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;
/**
* This class serves as a superclass for all tests that involve the hardware on the roboRIO. It uses
@@ -26,19 +24,16 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindow;
* to run.
*/
public abstract class AbstractComsSetup {
/**
* Stores whether network coms have been initialized.
*/
/** Stores whether network coms have been initialized. */
private static boolean initialized = false;
// We have no way to stop the MockDS, so its thread is daemon.
private static MockDS ds;
private static MockDS ds;
/**
* This sets up the network communications library to enable the driver
* 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.
* This sets up the network communications library to enable the driver 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) {
@@ -83,12 +78,9 @@ 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() {
return getOverridenTestWatcher();
@@ -121,19 +113,32 @@ public abstract class AbstractComsSetup {
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(),
(exceptionCount++) + "/" + failureCount + " " + description.getDisplayName() + " "
+ "failed " + singleThrown.getMessage() + "\n" + status, singleThrown);
getClassLogger()
.logp(
Level.SEVERE,
description.getClassName(),
description.getMethodName(),
(exceptionCount++)
+ "/"
+ failureCount
+ " "
+ description.getDisplayName()
+ " "
+ "failed "
+ singleThrown.getMessage()
+ "\n"
+ status,
singleThrown);
}
} else {
getClassLogger().logp(Level.SEVERE, description.getClassName(),
description.getMethodName(),
description.getDisplayName() + " failed " + throwable.getMessage() + "\n" + status,
throwable);
getClassLogger()
.logp(
Level.SEVERE,
description.getClassName(),
description.getMethodName(),
description.getDisplayName() + " failed " + throwable.getMessage() + "\n" + status,
throwable);
}
super.failed(throwable, description);
}
@@ -149,7 +154,6 @@ public abstract class AbstractComsSetup {
failed(exception, description, "");
}
/*
* (non-Javadoc)
*
@@ -169,8 +173,8 @@ public abstract class AbstractComsSetup {
// Prints the message on one line overwriting itself each time
TestBench.out().print("\rWaiting for enable: " + enableCounter++);
}
getClassLogger().logp(Level.INFO, description.getClassName(), description.getMethodName(),
"Starting");
getClassLogger()
.logp(Level.INFO, description.getClassName(), description.getMethodName(), "Starting");
super.starting(description);
}
@@ -179,13 +183,12 @@ public abstract class AbstractComsSetup {
simpleLog(Level.INFO, "TEST PASSED!");
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) {
@@ -199,8 +202,7 @@ public abstract class AbstractComsSetup {
* correct state is reached.
*/
public abstract class BooleanCheck {
public BooleanCheck() {
}
public BooleanCheck() {}
/**
* Runs the enclosed code and evaluates it to determine what state it should return.
@@ -213,22 +215,23 @@ public abstract class AbstractComsSetup {
/**
* 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 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
* 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) {
public double delayTillInCorrectStateWithMessage(
Level level, double timeout, String message, 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 (timeoutIndex = 0; timeoutIndex < (timeout * 100) && !correctState.getAsBoolean();
timeoutIndex++) {
for (timeoutIndex = 0;
timeoutIndex < (timeout * 100) && !correctState.getAsBoolean();
timeoutIndex++) {
Timer.delay(0.01);
}
if (correctState.getAsBoolean()) {
@@ -238,5 +241,4 @@ public abstract class AbstractComsSetup {
}
return timeoutIndex * 0.01;
}
}

View File

@@ -11,7 +11,6 @@ import java.util.List;
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;
@@ -37,8 +36,8 @@ public abstract class AbstractTestSuite {
SuiteClasses annotation = getClass().getAnnotation(SuiteClasses.class);
List<Class<?>> classes = new ArrayList<>();
if (annotation == null) {
throw new RuntimeException(String.format("class '%s' must have a SuiteClasses annotation",
getClass().getName()));
throw new RuntimeException(
String.format("class '%s' must have a SuiteClasses annotation", getClass().getName()));
}
for (Class<?> c : annotation.value()) {
classes.add(c);
@@ -81,7 +80,8 @@ public abstract class AbstractTestSuite {
for (Method m : c.getMethods()) {
// If this is a test method that is not trying to be ignored and it
// matches the regex
if (m.getAnnotation(Test.class) != null && m.getAnnotation(Ignore.class) == null
if (m.getAnnotation(Test.class) != null
&& m.getAnnotation(Ignore.class) == null
&& Pattern.matches(regex, m.getName())) {
ClassMethodPair pair = new ClassMethodPair(c, m);
classMethodPairs.add(pair);
@@ -91,7 +91,6 @@ public abstract class AbstractTestSuite {
return classMethodPairs;
}
/**
* Gets all of the test classes listed in this suite. Does not include any of the test suites. All
* of these classes contain tests.
@@ -109,16 +108,20 @@ public abstract class AbstractTestSuite {
// Add the tests from this suite that match the regex to the list of
// tests to run
runningList = suite.getAllContainedBaseTests(runningList);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException
} catch (NoSuchMethodException
| InvocationTargetException
| InstantiationException
| IllegalAccessException ex) {
// This shouldn't happen unless the constructor is changed in some
// way.
logger.log(Level.SEVERE, "Test suites can not take parameters in their constructors.",
ex);
logger.log(
Level.SEVERE, "Test suites can not take parameters 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.",
logger.log(
Level.SEVERE,
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
@@ -139,12 +142,11 @@ public abstract class AbstractTestSuite {
return getAllContainedBaseTests(runningBaseTests);
}
/**
* 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 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
*/
@@ -178,12 +180,11 @@ public abstract class AbstractTestSuite {
* @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);
// Then search any test suites not retrieved already for test classes
// matching the regex.
List<Class<?>> unCollectedSuites = getAllClasses();
@@ -205,12 +206,14 @@ public abstract class AbstractTestSuite {
runningList = suite.getSuiteOrTestMatchingRegex(regex, runningList);
}
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException
} catch (NoSuchMethodException
| InvocationTargetException
| InstantiationException
| IllegalAccessException ex) {
// This shouldn't happen unless the constructor is changed in some
// way.
logger.log(Level.SEVERE, "Test suites can not take parameters in their constructors.",
ex);
logger.log(
Level.SEVERE, "Test suites can not take parameters in their constructors.", ex);
}
}
}
@@ -230,7 +233,6 @@ public abstract class AbstractTestSuite {
return getSuiteOrTestMatchingRegex(regex, matchingClasses);
}
/**
* Retrieves all of the classes listed in the <code>@SuiteClasses</code> annotation.
*

View File

@@ -4,8 +4,13 @@
package edu.wpi.first.wpilibj.test;
import java.util.List;
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 edu.wpi.first.wpilibj.test.AbstractTestSuite.ClassMethodPair;
import java.util.List;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -13,13 +18,6 @@ import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
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;
/**
* Yes, this is the test system testing itself. Functionally, this is making sure that all tests get
* run correctly when you use parametrized arguments.
@@ -28,10 +26,16 @@ import static org.junit.Assert.assertEquals;
public class AbstractTestSuiteTest {
@Ignore("Prevents ANT from trying to run these as tests")
@RunWith(Suite.class)
@SuiteClasses({FirstSampleTest.class, SecondSampleTest.class, ThirdSampleTest.class,
FourthSampleTest.class, UnusualTest.class, ExampleSubSuite.class, EmptySuite.class})
class TestForAbstractTestSuite extends AbstractTestSuite {
}
@SuiteClasses({
FirstSampleTest.class,
SecondSampleTest.class,
ThirdSampleTest.class,
FourthSampleTest.class,
UnusualTest.class,
ExampleSubSuite.class,
EmptySuite.class
})
class TestForAbstractTestSuite extends AbstractTestSuite {}
TestForAbstractTestSuite m_testSuite;
@@ -79,10 +83,11 @@ public class AbstractTestSuiteTest {
List<Class<?>> collectedTests = m_testSuite.getSuiteOrTestMatchingRegex(".*Test.*");
// then
assertEquals(7, collectedTests.size());
assertThat(collectedTests, hasItems(FirstSubSuiteTest.class,
SecondSubSuiteTest.class, UnusualTest.class));
assertThat(collectedTests,
not(hasItems(new Class<?>[]{ExampleSubSuite.class, EmptySuite.class})));
assertThat(
collectedTests,
hasItems(FirstSubSuiteTest.class, SecondSubSuiteTest.class, UnusualTest.class));
assertThat(
collectedTests, not(hasItems(new Class<?>[] {ExampleSubSuite.class, EmptySuite.class})));
}
@Test
@@ -93,31 +98,23 @@ public class AbstractTestSuiteTest {
assertEquals(1, pairs.size());
assertEquals(FirstSubSuiteTest.class, pairs.get(0).m_methodClass);
assertEquals(FirstSubSuiteTest.METHODNAME, pairs.get(0).m_methodName);
}
}
@SuppressWarnings("OneTopLevelClass")
class FirstSampleTest {
}
class FirstSampleTest {}
@SuppressWarnings("OneTopLevelClass")
class SecondSampleTest {
}
class SecondSampleTest {}
@SuppressWarnings("OneTopLevelClass")
class ThirdSampleTest {
}
class ThirdSampleTest {}
@SuppressWarnings("OneTopLevelClass")
class FourthSampleTest {
}
class FourthSampleTest {}
@SuppressWarnings("OneTopLevelClass")
class UnusualTest {
} // This is a member of both suites
class UnusualTest {} // This is a member of both suites
@Ignore("Prevents ANT from trying to run these as tests")
@SuppressWarnings("OneTopLevelClass")
@@ -126,26 +123,20 @@ class FirstSubSuiteTest {
@Test
@SuppressWarnings("MethodName")
public void aTestMethod() {
}
public void aTestMethod() {}
}
@SuppressWarnings("OneTopLevelClass")
class SecondSubSuiteTest {
}
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 {
}
class ExampleSubSuite extends AbstractTestSuite {}
@Ignore("Prevents ANT from trying to run these as tests")
@RunWith(Suite.class)
@SuiteClasses({})
@SuppressWarnings("OneTopLevelClass")
class EmptySuite extends AbstractTestSuite {
}
class EmptySuite extends AbstractTestSuite {}

View File

@@ -5,7 +5,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;
@@ -76,13 +75,13 @@ public class AntJunitLanucher {
ex.printStackTrace();
}
} else {
TestBench.out().println(
"Run will not output XML for Jenkins because " + "tests are not being run with ANT");
TestBench.out()
.println(
"Run will not output XML for Jenkins because " + "tests are not being run with ANT");
// This should never return as it makes its own call to
// System.exit();
TestSuite.main(args);
}
System.exit(0);
}
}

View File

@@ -5,7 +5,6 @@
package edu.wpi.first.wpilibj.test;
import java.util.logging.Logger;
import org.junit.Test;
/**
@@ -27,8 +26,6 @@ public class QuickTest extends AbstractComsSetup {
return logger;
}
@Test
public void test() {
}
public void test() {}
}

View File

@@ -7,7 +7,6 @@ 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;
@@ -17,21 +16,18 @@ import org.junit.runners.model.Statement;
* is important if you have a test that fails only "sometimes" and needs to be rerun to find the
* issue.
*
* <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>
* <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>
*/
public class RepeatRule implements TestRule {
@Retention(RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.METHOD})
public @interface Repeat {
/**
* The number of times to repeat the test.
*/
/** The number of times to repeat the test. */
int times();
}
private static class RepeatStatement extends Statement {
private final int m_times;
private final Statement m_statement;

View File

@@ -4,12 +4,6 @@
package edu.wpi.first.wpilibj.test;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import edu.wpi.first.wpilibj.AnalogGyro;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.AnalogOutput;
@@ -24,6 +18,11 @@ import edu.wpi.first.wpilibj.fixtures.DIOCrossConnectFixture;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.fixtures.RelayCrossConnectFixture;
import edu.wpi.first.wpilibj.fixtures.TiltPanCameraFixture;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* This class provides access to all of the elements on the test bench, for use in fixtures. This
@@ -46,7 +45,6 @@ public final class TestBench {
public static final int kTiltServoChannel = 9;
public static final int kPanServoChannel = 8;
/* PowerDistributionPanel channels */
public static final int kJaguarPDPChannel = 6;
public static final int kVictorPDPChannel = 8;
@@ -58,17 +56,14 @@ public final class TestBench {
public static final int DIOCrossConnectA2 = 7;
public static final int DIOCrossConnectA1 = 6;
/**
* 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.
*/
protected TestBench() {
}
protected TestBench() {}
/**
* Constructs a new set of objects representing a connected set of Talon controlled Motors and an
@@ -198,21 +193,23 @@ public final class TestBench {
return new DIOCrossConnectFixture(inputPort, outputPort);
}
/**
* Gets two lists of possible DIO pairs for the two pairs.
*/
/** 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[][]{
{DIOCrossConnectA1, DIOCrossConnectA2},
{DIOCrossConnectA2, DIOCrossConnectA1}});
Arrays.asList(
new Integer[][] {
{DIOCrossConnectA1, DIOCrossConnectA2},
{DIOCrossConnectA2, DIOCrossConnectA1}
});
pairs.add(setA);
List<Integer[]> setB =
Arrays.asList(new Integer[][]{
{DIOCrossConnectB1, DIOCrossConnectB2},
{DIOCrossConnectB2, DIOCrossConnectB1}});
Arrays.asList(
new Integer[][] {
{DIOCrossConnectB1, DIOCrossConnectB2},
{DIOCrossConnectB2, DIOCrossConnectB1}
});
pairs.add(setB);
// NOTE: IF MORE DIOCROSSCONNECT PAIRS ARE ADDED ADD THEM HERE
return pairs;
@@ -273,8 +270,8 @@ public final class TestBench {
* @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) {
private Collection<Integer[]> getPairArray(
List<Integer[]> listA, List<Integer[]> listB, boolean flip) {
Collection<Integer[]> encoderPortPairs = new ArrayList<Integer[]>();
for (Integer[] portPairsA : listA) {
Integer[] inputs = new Integer[5];
@@ -310,10 +307,10 @@ public final class TestBench {
public Collection<Integer[]> getEncoderDIOCrossConnectCollection() {
Collection<Integer[]> encoderPortPairs = new ArrayList<Integer[]>();
assert getDIOCrossConnect().size() == 2;
encoderPortPairs.addAll(getPairArray(getDIOCrossConnect().get(0), getDIOCrossConnect().get(1),
false));
encoderPortPairs.addAll(getPairArray(getDIOCrossConnect().get(1), getDIOCrossConnect().get(0),
false));
encoderPortPairs.addAll(
getPairArray(getDIOCrossConnect().get(0), getDIOCrossConnect().get(1), false));
encoderPortPairs.addAll(
getPairArray(getDIOCrossConnect().get(1), getDIOCrossConnect().get(0), false));
assert encoderPortPairs.size() == 8;
return encoderPortPairs;
}

View File

@@ -4,6 +4,7 @@
package edu.wpi.first.wpilibj.test;
import edu.wpi.first.wpilibj.WpiLibJTestSuite;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
@@ -13,7 +14,8 @@ import java.util.Objects;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import junit.framework.JUnit4TestAdapter;
import junit.runner.Version;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
@@ -21,11 +23,6 @@ import org.junit.runner.notification.Failure;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import junit.framework.JUnit4TestAdapter;
import junit.runner.Version;
import edu.wpi.first.wpilibj.WpiLibJTestSuite;
/**
* 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
@@ -50,9 +47,8 @@ public class TestSuite extends AbstractTestSuite {
}
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");
private static final Logger WPILIBJ_COMMAND_ROOT_LOGGER =
Logger.getLogger("edu.wpi.first.wpilibj.command");
private static final Class<?> QUICK_TEST = QuickTest.class;
private static final String QUICK_TEST_FLAG = "--quick";
@@ -63,9 +59,7 @@ public class TestSuite extends AbstractTestSuite {
private static TestSuite instance = null;
/**
* Get the singleton instance of the test suite.
*/
/** Get the singleton instance of the test suite. */
public static TestSuite getInstance() {
if (instance == null) {
instance = new TestSuite();
@@ -73,32 +67,41 @@ public class TestSuite extends AbstractTestSuite {
return instance;
}
/**
* This has to be public so that the JUnit4.
*/
public TestSuite() {
}
/** This has to be public so that the JUnit4. */
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");
helpMessage.append("\t" + QUICK_TEST_FLAG
+ " will cause the quick test to be run. Ignores other flags except for "
+ METHOD_REPEAT_FILTER + "\n");
helpMessage.append("\t" + CLASS_NAME_FILTER
+ " will use the supplied regex text to search for suite/test class names "
+ "matching the regex and run them.\n");
helpMessage.append("\t" + METHOD_NAME_FILTER
+ " will use the supplied regex text to search for test methods (excluding methods "
+ "with the @Ignore annotation) and run only those methods. Can be paired with "
+ METHOD_REPEAT_FILTER + " to " + "repeat the selected tests multiple times.\n");
helpMessage.append("\t" + METHOD_REPEAT_FILTER + " will repeat the tests selected with either "
+ 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 "
helpMessage.append(
"\t"
+ QUICK_TEST_FLAG
+ " will cause the quick test to be run. Ignores other flags except for "
+ METHOD_REPEAT_FILTER
+ "\n");
helpMessage.append(
"\t"
+ CLASS_NAME_FILTER
+ " will use the supplied regex text to search for suite/test class names "
+ "matching the regex and run them.\n");
helpMessage.append(
"\t"
+ METHOD_NAME_FILTER
+ " will use the supplied regex text to search for test methods (excluding methods "
+ "with the @Ignore annotation) and run only those methods. Can be paired with "
+ METHOD_REPEAT_FILTER
+ " to "
+ "repeat the selected tests multiple times.\n");
helpMessage.append(
"\t"
+ METHOD_REPEAT_FILTER
+ " will repeat the tests selected with either "
+ 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 "
+ "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n");
helpMessage.append("\n");
@@ -118,12 +121,12 @@ public class TestSuite extends AbstractTestSuite {
invalidMessage.append(a + " ");
}
invalidMessage.append("\n");
invalidMessage
.append("For details on proper usage of the runtime flags please run again with the "
+ HELP_FLAG + " flag.\n\n");
invalidMessage.append(
"For details on proper usage of the runtime flags please run again with the "
+ HELP_FLAG
+ " flag.\n\n");
TestBench.out().println(invalidMessage);
}
/**
@@ -144,7 +147,6 @@ public class TestSuite extends AbstractTestSuite {
TestBench.out().println(loadedTestsMessage);
}
/**
* Parses the arguments passed at runtime and runs the appropriate tests based upon these
* arguments.
@@ -176,8 +178,8 @@ public class TestSuite extends AbstractTestSuite {
try {
repeatCount = Integer.parseInt(new String(s).replace(METHOD_REPEAT_FILTER, ""));
} catch (NumberFormatException ex) {
displayInvalidUsage("The argument passed to the repeat rule was not a valid integer.",
args);
displayInvalidUsage(
"The argument passed to the repeat rule was not a valid integer.", args);
}
}
if (Pattern.matches(CLASS_NAME_FILTER + ".*", s)) {
@@ -186,7 +188,6 @@ public class TestSuite extends AbstractTestSuite {
}
}
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
@@ -200,8 +201,8 @@ public class TestSuite extends AbstractTestSuite {
}
/**
* Stores the data from multiple {@link Result}s in one class that can be
* returned to display the results.
* Stores the data from multiple {@link Result}s in one class that can be returned to display
* the results.
*/
class MultipleResult extends Result {
private static final long serialVersionUID = 1L;
@@ -252,8 +253,8 @@ 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
@@ -268,7 +269,6 @@ public class TestSuite extends AbstractTestSuite {
TestBench.out().println("\t" + p.m_methodName);
}
// The test results will be saved here
MultipleResult results = new MultipleResult();
// Runs tests multiple times if the repeat rule is used
@@ -320,9 +320,17 @@ public class TestSuite extends AbstractTestSuite {
TestBench.out().println();
TestBench.out().println("FAILURES!!!");
// Print the test statistics
TestBench.out().println(
"Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount()
+ ", Ignored: " + result.getIgnoreCount() + ", In " + result.getRunTime() + "ms");
TestBench.out()
.println(
"Tests run: "
+ result.getRunCount()
+ ", Failures: "
+ result.getFailureCount()
+ ", Ignored: "
+ result.getIgnoreCount()
+ ", In "
+ result.getRunTime()
+ "ms");
// Prints out a list of test that failed
TestBench.out().println("Failure List (short):");
@@ -337,9 +345,15 @@ public class TestSuite extends AbstractTestSuite {
}
} else {
TestBench.out().println("SUCCESS!");
TestBench.out().println(
"Tests run: " + result.getRunCount() + ", Ignored: " + result.getIgnoreCount() + ", In "
+ result.getRunTime() + "ms");
TestBench.out()
.println(
"Tests run: "
+ result.getRunCount()
+ ", Ignored: "
+ result.getIgnoreCount()
+ ", In "
+ result.getRunTime()
+ "ms");
}
TestBench.out().println();
}
@@ -353,7 +367,6 @@ public class TestSuite extends AbstractTestSuite {
return new JUnit4TestAdapter(TestSuite.class);
}
/**
* The method called at runtime.
*

View File

@@ -5,11 +5,10 @@
/**
* 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.
* 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;