mirror of
https://github.com/wpilibsuite/allwpilib
synced 2026-06-20 00:51:42 +00:00
[cmd3] Scope scheduled commands to the running opmode, if one exists (#8492)
This prevents commands from outliving the opmodes in which they were scheduled
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
// Copyright (c) FIRST and other WPILib contributors.
|
||||
// Open Source Software; you can modify and/or share it under the terms of
|
||||
// the WPILib BSD license file in the root directory of this project.
|
||||
|
||||
package org.wpilib.command3;
|
||||
|
||||
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
public class MockHardwareExtension implements BeforeEachCallback {
|
||||
@Override
|
||||
public void beforeEach(ExtensionContext context) {
|
||||
OpModeFetcher.setFetcher(new MockOpModeFetcher());
|
||||
}
|
||||
|
||||
private static final class MockOpModeFetcher extends OpModeFetcher {
|
||||
@Override
|
||||
long getOpModeId() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
String getOpModeName() {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,6 +184,43 @@ class TriggerTest extends CommandTestBase {
|
||||
"Command should have been canceled when scope became inactive");
|
||||
}
|
||||
|
||||
@Test
|
||||
void bindingScopesToOpmodeIfAvailable() {
|
||||
var fetcher =
|
||||
new OpModeFetcher() {
|
||||
long m_id = 12345;
|
||||
|
||||
void clear() {
|
||||
m_id = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
long getOpModeId() {
|
||||
return m_id;
|
||||
}
|
||||
|
||||
@Override
|
||||
String getOpModeName() {
|
||||
return "This is an opmode!";
|
||||
}
|
||||
};
|
||||
OpModeFetcher.setFetcher(fetcher);
|
||||
|
||||
var triggerSignal = new AtomicBoolean(false);
|
||||
var trigger = new Trigger(m_scheduler, triggerSignal::get);
|
||||
|
||||
var command = Command.noRequirements().executing(Coroutine::park).named("Command");
|
||||
trigger.whileTrue(command);
|
||||
|
||||
triggerSignal.set(true);
|
||||
m_scheduler.run();
|
||||
assertTrue(m_scheduler.isRunning(command), "Command should have started when triggered");
|
||||
|
||||
fetcher.clear();
|
||||
m_scheduler.run();
|
||||
assertFalse(m_scheduler.isRunning(command), "Command should have stopped when opmode exited");
|
||||
}
|
||||
|
||||
// The scheduler lifecycle polls triggers at the start of `run()`
|
||||
// Even though the trigger condition is set, the command exits and the trigger's scope goes
|
||||
// inactive before the next `run()` call can poll the trigger
|
||||
|
||||
Reference in New Issue
Block a user