diff options
| author | Paul Buetow <paul@buetow.org> | 2025-06-22 16:45:17 +0300 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2025-06-22 16:45:17 +0300 |
| commit | 4c16cc3c4da7bbf8375d7951185db1761eb396bf (patch) | |
| tree | 19199b664ce802ed3e967e318e6d4ffeb8c9bf39 /src/test | |
| parent | 464df52901e2dcb84eb81a22f2db19cbf17e5a9f (diff) | |
Remove all Raft protocol code
Removed all Raft-related code as it was not working properly:
- Removed VSRaftProtocol.java implementation
- Removed all Raft test files
- Removed Raft example/demo files
- Removed Raft documentation
- Removed Raft simulation files (.dat)
- Removed Raft scripts
- Updated VSRegisteredEvents to remove Raft registration
- Updated SimulationBuilder to remove RAFT constant
- Updated SimulationFactory to remove Raft methods
- Updated SimulationBuilderTest to remove Raft tests
- Updated pom.xml to remove Raft test configurations
The protocol had issues with leader election not completing in GUI mode.
🤖 Generated with Claude Code
https://claude.ai/code
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat (limited to 'src/test')
5 files changed, 1 insertions, 551 deletions
diff --git a/src/test/java/protocols/implementations/VSRaftProtocolTest.java b/src/test/java/protocols/implementations/VSRaftProtocolTest.java deleted file mode 100644 index a5bff12..0000000 --- a/src/test/java/protocols/implementations/VSRaftProtocolTest.java +++ /dev/null @@ -1,308 +0,0 @@ -package protocols.implementations; - -import core.VSAbstractProcess; -import core.VSInternalProcess; -import core.VSMessage; -import core.VSTaskManager; -import core.time.VSVectorTime; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import prefs.VSPrefs; -import simulator.VSLogging; -import simulator.VSSimulatorVisualization; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -class VSRaftProtocolTest { - - private VSRaftProtocol protocol; - private VSInternalProcess mockProcess; - private VSPrefs mockPrefs; - private VSSimulatorVisualization mockCanvas; - private VSTaskManager mockTaskManager; - private VSVectorTime mockVectorTime; - - @BeforeEach - void setUp() { - protocol = new VSRaftProtocol(); - mockProcess = mock(VSInternalProcess.class); - mockPrefs = mock(VSPrefs.class); - mockCanvas = mock(VSSimulatorVisualization.class); - mockTaskManager = mock(VSTaskManager.class); - mockVectorTime = mock(VSVectorTime.class); - - // Set up process behavior - when(mockProcess.getProcessNum()).thenReturn(1); - when(mockProcess.getTime()).thenReturn(1000L); - when(mockProcess.getRandomPercentage()).thenReturn(50); - when(mockProcess.getSimulatorCanvas()).thenReturn(mockCanvas); - when(mockCanvas.getNumProcesses()).thenReturn(3); - when(mockCanvas.getTaskManager()).thenReturn(mockTaskManager); - when(mockProcess.getVectorTime()).thenReturn(mockVectorTime); - when(mockVectorTime.getCopy()).thenReturn(mockVectorTime); - when(mockProcess.getLamportTime()).thenReturn(100L); - - // Set process and prefs directly via field access (like other protocol tests) - protocol.process = mockProcess; - protocol.prefs = mockPrefs; - protocol.isServer(true); - } - - @Test - void testServerInitialization() { - // Test server initialization - protocol.onServerInit(); - protocol.onServerStart(); - - // Protocol should start as follower - verify(mockProcess).log(contains("FOLLOWER")); - } - - @Test - void testElectionTimeout() { - // Initialize protocol - protocol.onServerInit(); - - // Remove any scheduled tasks to clean state - doNothing().when(mockTaskManager).removeAllTasks(any()); - protocol.onServerReset(); - protocol.onServerInit(); - protocol.onServerStart(); - - // Simulate election timeout by calling onServerSchedule - when(mockProcess.getTime()).thenReturn(2000L); // Well past timeout - protocol.onServerSchedule(); - - // Should start election and send vote requests - ArgumentCaptor<VSMessage> messageCaptor = ArgumentCaptor.forClass(VSMessage.class); - verify(mockProcess, atLeastOnce()).sendMessage(messageCaptor.capture()); - - VSMessage sentMessage = messageCaptor.getValue(); - assertEquals("REQUEST_VOTE", sentMessage.getString("type")); - } - - @Test - void testVoteRequest() { - // Initialize protocol - protocol.onServerInit(); - - // Create vote request from another node - VSMessage voteRequest = mock(VSMessage.class); - when(voteRequest.getString("type")).thenReturn("REQUEST_VOTE"); - when(voteRequest.getInteger("term")).thenReturn(2); - when(voteRequest.getInteger("candidateId")).thenReturn(2); - when(voteRequest.getInteger("lastLogIndex")).thenReturn(0); - when(voteRequest.getInteger("lastLogTerm")).thenReturn(0); - - // Mock sender process - VSInternalProcess mockSender = mock(VSInternalProcess.class); - when(mockSender.getProcessNum()).thenReturn(2); - when(voteRequest.getSendingProcess()).thenReturn(mockSender); - - // Process vote request - protocol.onServerRecv(voteRequest); - - // Should send vote response - ArgumentCaptor<VSMessage> responseCaptor = ArgumentCaptor.forClass(VSMessage.class); - verify(mockProcess).sendMessage(responseCaptor.capture()); - - VSMessage response = responseCaptor.getValue(); - assertEquals("VOTE_RESPONSE", response.getString("type")); - assertTrue(response.getBoolean("voteGranted")); - } - - @Test - void testBecomeLeader() { - // Initialize protocol - protocol.onServerInit(); - protocol.isServer(true); - - // Start election - when(mockProcess.getTime()).thenReturn(2000L); - protocol.onServerSchedule(); - - // Should vote for itself and need one more vote (in 3-node cluster) - // Send vote response from node 0 - VSMessage voteResponse1 = mock(VSMessage.class); - when(voteResponse1.getString("type")).thenReturn("VOTE_RESPONSE"); - when(voteResponse1.getInteger("term")).thenReturn(1); - when(voteResponse1.getBoolean("voteGranted")).thenReturn(true); - - // Mock sender process - VSInternalProcess mockSender1 = mock(VSInternalProcess.class); - when(mockSender1.getProcessNum()).thenReturn(0); - when(voteResponse1.getSendingProcess()).thenReturn(mockSender1); - - protocol.onServerRecv(voteResponse1); - - // Should become leader and highlight - verify(mockProcess).highlightOn(); - verify(mockProcess, atLeastOnce()).log(contains("LEADER")); - } - - @Test - void testHeartbeats() { - // Make node a leader - protocol.onServerInit(); - protocol.isServer(true); - - // Simulate becoming leader - when(mockProcess.getTime()).thenReturn(2000L); - protocol.onServerSchedule(); // Start election - - // Get majority votes - VSMessage voteResponse = mock(VSMessage.class); - when(voteResponse.getString("type")).thenReturn("VOTE_RESPONSE"); - when(voteResponse.getInteger("term")).thenReturn(1); - when(voteResponse.getBoolean("voteGranted")).thenReturn(true); - - // Mock sender process - VSInternalProcess mockSender = mock(VSInternalProcess.class); - when(mockSender.getProcessNum()).thenReturn(0); - when(voteResponse.getSendingProcess()).thenReturn(mockSender); - protocol.onServerRecv(voteResponse); - - // Clear previous invocations - clearInvocations(mockProcess); - - // Trigger heartbeat - protocol.onServerSchedule(); - - // Should send append entries (heartbeats) to other nodes - ArgumentCaptor<VSMessage> heartbeatCaptor = ArgumentCaptor.forClass(VSMessage.class); - verify(mockProcess, atLeast(2)).sendMessage(heartbeatCaptor.capture()); - - boolean foundAppendEntries = false; - for (VSMessage msg : heartbeatCaptor.getAllValues()) { - if ("APPEND_ENTRIES".equals(msg.getString("type"))) { - foundAppendEntries = true; - assertEquals(1, msg.getInteger("term")); - assertEquals(1, msg.getInteger("leaderId")); - } - } - assertTrue(foundAppendEntries); - } - - @Test - void testLogReplication() { - // Initialize as leader - protocol.onServerInit(); - protocol.isServer(true); - - // Become leader (simplified) - when(mockProcess.getTime()).thenReturn(2000L); - protocol.onServerSchedule(); - VSMessage voteResponse = mock(VSMessage.class); - when(voteResponse.getString("type")).thenReturn("VOTE_RESPONSE"); - when(voteResponse.getInteger("term")).thenReturn(1); - when(voteResponse.getBoolean("voteGranted")).thenReturn(true); - - // Mock sender process - VSInternalProcess mockSender = mock(VSInternalProcess.class); - when(mockSender.getProcessNum()).thenReturn(0); - when(voteResponse.getSendingProcess()).thenReturn(mockSender); - protocol.onServerRecv(voteResponse); - - // Client request - VSMessage clientRequest = mock(VSMessage.class); - when(clientRequest.getString("type")).thenReturn("CLIENT_REQUEST"); - when(clientRequest.getString("command")).thenReturn("SET x=42"); - - // Mock sender process (client) - VSInternalProcess mockClient = mock(VSInternalProcess.class); - when(mockClient.getProcessNum()).thenReturn(2); - when(clientRequest.getSendingProcess()).thenReturn(mockClient); - - protocol.onServerRecv(clientRequest); - - // Should log the command - verify(mockProcess, atLeastOnce()).log(contains("SET x=42")); - } - - @Test - void testFollowerRejectsClientRequests() { - // Initialize as follower - protocol.onServerInit(); - protocol.isServer(true); - - // Client request to follower - VSMessage clientRequest = mock(VSMessage.class); - when(clientRequest.getString("type")).thenReturn("CLIENT_REQUEST"); - when(clientRequest.getString("command")).thenReturn("SET x=42"); - - // Mock sender process - VSInternalProcess mockClient = mock(VSInternalProcess.class); - when(mockClient.getProcessNum()).thenReturn(2); - when(clientRequest.getSendingProcess()).thenReturn(mockClient); - - protocol.onServerRecv(clientRequest); - - // Should send rejection response - ArgumentCaptor<VSMessage> responseCaptor = ArgumentCaptor.forClass(VSMessage.class); - verify(mockProcess).sendMessage(responseCaptor.capture()); - - VSMessage response = responseCaptor.getValue(); - assertEquals("CLIENT_RESPONSE", response.getString("type")); - assertFalse(response.getBoolean("success")); - } - - @Test - void testClientBehavior() { - // Test client side - protocol.isClient(true); - protocol.onClientInit(); - - // Mock scheduled task addition - doNothing().when(mockTaskManager).addTask(any()); - - protocol.onClientStart(); - - // onClientStart is empty for Raft protocol (clients respond to server heartbeats) - // So we shouldn't expect any interactions here - - // Simulate scheduled client request - protocol.onClientSchedule(); - - // Should send client request - ArgumentCaptor<VSMessage> requestCaptor = ArgumentCaptor.forClass(VSMessage.class); - verify(mockProcess).sendMessage(requestCaptor.capture()); - - VSMessage request = requestCaptor.getValue(); - assertEquals("CLIENT_REQUEST", request.getString("type")); - assertNotNull(request.getString("command")); - } - - @Test - void testTermUpdate() { - // Initialize protocol - protocol.onServerInit(); - protocol.isServer(true); - - // Receive message with higher term - VSMessage higherTermMsg = mock(VSMessage.class); - when(higherTermMsg.getString("type")).thenReturn("APPEND_ENTRIES"); - when(higherTermMsg.getInteger("term")).thenReturn(5); - when(higherTermMsg.getInteger("leaderId")).thenReturn(2); - when(higherTermMsg.getInteger("prevLogIndex")).thenReturn(0); - when(higherTermMsg.getInteger("prevLogTerm")).thenReturn(0); - when(higherTermMsg.getInteger("leaderCommit")).thenReturn(0); - when(higherTermMsg.getInteger("entryCount")).thenReturn(0); - - // Mock sender process - VSInternalProcess mockLeader = mock(VSInternalProcess.class); - when(mockLeader.getProcessNum()).thenReturn(2); - when(higherTermMsg.getSendingProcess()).thenReturn(mockLeader); - - protocol.onServerRecv(higherTermMsg); - - // Should become follower (no longer logs in onServerRecv) - // Just verify the message was processed correctly by checking response - ArgumentCaptor<VSMessage> responseCaptor = ArgumentCaptor.forClass(VSMessage.class); - verify(mockProcess).sendMessage(responseCaptor.capture()); - - VSMessage response = responseCaptor.getValue(); - assertEquals("APPEND_RESPONSE", response.getString("type")); - } -}
\ No newline at end of file diff --git a/src/test/java/simulator/SimpleRaftGUITest.java b/src/test/java/simulator/SimpleRaftGUITest.java deleted file mode 100644 index 3697db2..0000000 --- a/src/test/java/simulator/SimpleRaftGUITest.java +++ /dev/null @@ -1,66 +0,0 @@ -package simulator; - -import org.junit.jupiter.api.*; -import static org.junit.jupiter.api.Assertions.*; - -import core.*; -import prefs.*; -import events.*; -import serialize.VSSerialize; - -import java.io.File; -import java.lang.reflect.*; - -/** - * Simple GUI test for Raft simulation to verify it loads and runs. - */ -public class SimpleRaftGUITest { - - @Test - @DisplayName("Test loading Raft simulation file") - public void testLoadRaftSimulation() throws Exception { - // Initialize - VSDefaultPrefs prefs = new VSDefaultPrefs(); - prefs.fillWithDefaults(); - VSRegisteredEvents.init(prefs); - - // Check if simulation file exists - File simFile = new File("saved-simulations/raft-working.dat"); - assertTrue(simFile.exists(), "Raft simulation file should exist"); - - // Load simulation - VSSimulatorFrame frame = new VSSimulatorFrame(prefs, null); - VSSerialize serialize = new VSSerialize(); - VSSimulator simulator = serialize.openSimulator(simFile.getAbsolutePath(), frame); - - assertNotNull(simulator, "Simulator should be loaded"); - - // Access visualization - Field vizField = VSSimulator.class.getDeclaredField("simulatorVisualization"); - vizField.setAccessible(true); - VSSimulatorVisualization viz = (VSSimulatorVisualization) vizField.get(simulator); - - // Verify basic properties - assertTrue(viz.getNumProcesses() >= 5, "Should have at least 5 processes"); - - // Check task manager - VSTaskManager taskManager = viz.getTaskManager(); - assertNotNull(taskManager, "Task manager should exist"); - - // Get task count using reflection - Field tasksField = VSTaskManager.class.getDeclaredField("tasks"); - tasksField.setAccessible(true); - Object taskQueue = tasksField.get(taskManager); - Method sizeMethod = taskQueue.getClass().getMethod("size"); - int taskCount = (Integer) sizeMethod.invoke(taskQueue); - - assertTrue(taskCount > 0, "Should have scheduled tasks"); - - frame.dispose(); - - System.out.println("\n=== Test Results ==="); - System.out.println("✓ Raft simulation loads successfully"); - System.out.println("✓ Processes: " + viz.getNumProcesses()); - System.out.println("✓ Scheduled tasks: " + taskCount); - } -}
\ No newline at end of file diff --git a/src/test/java/simulator/builder/SimulationBuilderTest.java b/src/test/java/simulator/builder/SimulationBuilderTest.java index 82860f0..5061477 100644 --- a/src/test/java/simulator/builder/SimulationBuilderTest.java +++ b/src/test/java/simulator/builder/SimulationBuilderTest.java @@ -29,43 +29,6 @@ class SimulationBuilderTest { } } - @Test - void testCreateBasicRaftSimulation() throws Exception { - String filename = TEST_DIR + "test-raft.dat"; - - // Create a basic Raft simulation - new SimulationBuilder() - .withProcesses(3) - .withProtocol(SimulationBuilder.Protocols.RAFT) - .activateServers(0, 1, 2) - .save(filename); - - // Verify file was created - File file = new File(filename); - assertTrue(file.exists(), "Simulation file should be created"); - assertTrue(file.length() > 1000, "File should have content"); - - // Verify it contains Raft protocol - String content = Files.readString(file.toPath()); - assertTrue(content.contains("VSRaftProtocol"), "Should contain Raft protocol classname"); - } - - @Test - void testCreateRaftWithClients() throws Exception { - String filename = TEST_DIR + "test-raft-clients.dat"; - - // Use factory method - SimulationFactory.createRaftSimulation(3, 2) - .save(filename); - - // Verify file was created - File file = new File(filename); - assertTrue(file.exists(), "Simulation file should be created"); - - // Should have 5 processes (3 servers + 2 clients) - String content = Files.readString(file.toPath()); - assertTrue(content.contains("VSRaftProtocol"), "Should contain Raft protocol"); - } @Test void testCreatePingPongSimulation() throws Exception { @@ -88,7 +51,7 @@ class SimulationBuilderTest { // Create a complex simulation with events new SimulationBuilder() .withProcesses(5) - .withProtocol(SimulationBuilder.Protocols.RAFT) + .withProtocol(SimulationBuilder.Protocols.TWO_PHASE_COMMIT) .withDuration(30000) .activateServers(0, 1, 2) .activateClients(1000, 3, 4) @@ -109,7 +72,6 @@ class SimulationBuilderTest { void testAllProtocolTypes() throws Exception { // Test that all protocol constants work String[] protocols = { - SimulationBuilder.Protocols.RAFT, SimulationBuilder.Protocols.PING_PONG, SimulationBuilder.Protocols.BERKLEY_TIME, SimulationBuilder.Protocols.BROADCAST, @@ -137,10 +99,6 @@ class SimulationBuilderTest { void testInvalidConfiguration() { // Test that invalid configurations throw exceptions assertThrows(IllegalArgumentException.class, () -> { - SimulationFactory.createRaftSimulation(2, 0); // Too few servers - }); - - assertThrows(IllegalArgumentException.class, () -> { SimulationFactory.createBerkeleyTimeSimulation(1); // Too few processes }); } diff --git a/src/test/java/testing/RaftSimulationTest.java b/src/test/java/testing/RaftSimulationTest.java deleted file mode 100644 index b161668..0000000 --- a/src/test/java/testing/RaftSimulationTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package testing; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.BeforeEach; -import prefs.VSDefaultPrefs; -import events.VSRegisteredEvents; - -import static org.junit.jupiter.api.Assertions.*; - -/** - * Integration test for Raft protocol simulation. - * Tests that leader election occurs when running a Raft simulation. - */ -class RaftSimulationTest { - - private VSDefaultPrefs prefs; - - @BeforeEach - void setUp() { - prefs = new VSDefaultPrefs(); - prefs.fillWithDefaults(); - VSRegisteredEvents.init(prefs); - } - - @Test - void testRaftLeaderElection() throws Exception { - // This test verifies that the Raft protocol implementation - // properly elects a leader when running - - // For now, we verify the protocol can be instantiated and initialized - Object raftObj = new utils.VSClassLoader().newInstance("protocols.implementations.VSRaftProtocol"); - assertNotNull(raftObj, "Raft protocol should be instantiable"); - assertTrue(raftObj instanceof protocols.VSAbstractProtocol, "Should be a protocol"); - - // Verify the protocol has the correct classname set - protocols.implementations.VSRaftProtocol raftProtocol = - (protocols.implementations.VSRaftProtocol) raftObj; - assertNotNull(raftProtocol.getClassname(), - "Protocol classname should be set"); - assertTrue(raftProtocol.getClassname().contains("VSRaftProtocol"), - "Protocol classname should contain VSRaftProtocol"); - } - - @Test - void testRaftProtocolRegistration() { - // Verify Raft protocol is properly registered - assertTrue(VSRegisteredEvents.getProtocolClassnames().contains( - "protocols.implementations.VSRaftProtocol"), - "Raft protocol should be registered"); - - // Verify it has a proper display name (this is set in lang properties) - String shortName = VSRegisteredEvents.getShortnameByClassname( - "protocols.implementations.VSRaftProtocol"); - assertNotNull(shortName, "Raft protocol should have a short name"); - assertEquals("Raft Consensus", shortName); - } -}
\ No newline at end of file diff --git a/src/test/java/testing/protocols/RaftProtocolTest.java b/src/test/java/testing/protocols/RaftProtocolTest.java deleted file mode 100644 index b92606d..0000000 --- a/src/test/java/testing/protocols/RaftProtocolTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package testing.protocols; - -import testing.*; -import org.junit.jupiter.api.*; -import static org.junit.jupiter.api.Assertions.*; - -/** - * Integration test for Raft consensus protocol. - */ -public class RaftProtocolTest extends BaseProtocolTest { - - @Test - @DisplayName("Test Raft protocol activation and message sending") - public void testRaftActivation() { - SimulationResult result = runSimulation( - "saved-simulations/raft.dat", - 2000 // 2 seconds should be enough for elections - ); - - ProtocolVerifier verifier = new ProtocolVerifier() - .expectLogExactly("Raft Consensus Server activated", 3) - .expectLog("FOLLOWER.*initialized") - .expectLog("Starting election") - .expectLog("CANDIDATE") - .expectMessages() // Must have messages - .expectAtLeastNMessages(10); // Should have many election messages - - VerificationResult verification = verifier.verify(result.getAllLogs()); - - assertTrue(verification.passed(), verification.getFailureMessage()); - assertEquals(3, result.getMetrics().getNumProcesses(), - "Should have 3 processes"); - } - - @Test - @DisplayName("Test Raft election messages") - public void testRaftElectionMessages() { - SimulationResult result = runSimulation( - "saved-simulations/raft.dat", - 3000 - ); - - ProtocolVerifier verifier = new ProtocolVerifier() - .expectLog("REQUEST_VOTE") - .expectLog("Message sent.*REQUEST_VOTE") - .expectAtLeastNMessages(15); // Multiple election rounds - - VerificationResult verification = verifier.verify(result.getAllLogs()); - assertTrue(verification.passed(), verification.getFailureMessage()); - - // Verify term progression - assertTrue(result.findFirst("term=1").isPresent(), "Should have term 1"); - assertTrue(result.findFirst("term=2").isPresent(), "Should progress to term 2"); - } - - @Test - @DisplayName("Test Raft with clients") - public void testRaftWithClients() { - // Skip if file doesn't exist - if (!new java.io.File("saved-simulations/raft-with-clients.dat").exists()) { - return; - } - - SimulationResult result = runSimulation( - "saved-simulations/raft-with-clients.dat", - 5000 - ); - - ProtocolVerifier verifier = new ProtocolVerifier() - .expectLogExactly("Raft Consensus Server activated", 3) - .expectLogExactly("Raft Consensus Client activated", 2) - .expectMessages(); // Must have messages - - VerificationResult verification = verifier.verify(result.getAllLogs()); - assertTrue(verification.passed(), verification.getFailureMessage()); - } -}
\ No newline at end of file |
