file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
MPDTrackMonitorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/monitor/MPDTrackMonitorTest.java
package org.bff.javampd.monitor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.bff.javampd.player.TrackPositionChangeEvent; import org.bff.javampd.player.TrackPositionChangeListener; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class MPDTrackMonitorTest { private TrackMonitor trackMonitor; @BeforeEach void setUp() { trackMonitor = new MPDTrackMonitor(); } @Test void testAddTrackPositionChangeListener() { final TrackPositionChangeEvent[] changeEvent = new TrackPositionChangeEvent[1]; final TrackPositionChangeEvent[] changeEvent2 = new TrackPositionChangeEvent[1]; trackMonitor.addTrackPositionChangeListener(event -> changeEvent[0] = event); trackMonitor.addTrackPositionChangeListener(event -> changeEvent2[0] = event); trackMonitor.processResponseStatus("time: 1"); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); assertEquals(1, changeEvent2[0].getElapsedTime()); } @Test void testRemoveTrackPositionChangeListener() { final TrackPositionChangeEvent[] changeEvent = new TrackPositionChangeEvent[1]; TrackPositionChangeListener trackPositionChangeListener = event -> changeEvent[0] = event; trackMonitor.addTrackPositionChangeListener(trackPositionChangeListener); trackMonitor.processResponseStatus("time: 1"); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); changeEvent[0] = null; trackMonitor.removeTrackPositionChangeListener(trackPositionChangeListener); trackMonitor.processResponseStatus("time: 2"); trackMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testCheckTrackPosition() { final TrackPositionChangeEvent[] changeEvent = new TrackPositionChangeEvent[1]; trackMonitor.addTrackPositionChangeListener(event -> changeEvent[0] = event); trackMonitor.processResponseStatus("time: 1"); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); } @Test void testCheckTrackPositionNoChange() { final TrackPositionChangeEvent[] changeEvent = new TrackPositionChangeEvent[1]; trackMonitor.addTrackPositionChangeListener(event -> changeEvent[0] = event); trackMonitor.processResponseStatus("time: 1"); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); changeEvent[0] = null; trackMonitor.processResponseStatus("time: 1"); trackMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testProcessInvalidResponse() { final TrackPositionChangeEvent[] changeEvent = new TrackPositionChangeEvent[1]; trackMonitor.addTrackPositionChangeListener(event -> changeEvent[0] = event); trackMonitor.processResponseStatus("bogus: 1"); trackMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testResetElapsedTime() { final TrackPositionChangeEvent[] changeEvent = new TrackPositionChangeEvent[1]; trackMonitor.addTrackPositionChangeListener(event -> changeEvent[0] = event); trackMonitor.processResponseStatus("time: 1"); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); changeEvent[0] = null; trackMonitor.processResponseStatus("time: 1"); trackMonitor.checkStatus(); assertNull(changeEvent[0]); trackMonitor.resetElapsedTime(); trackMonitor.addTrackPositionChangeListener(event -> changeEvent[0] = event); trackMonitor.processResponseStatus("time: 1"); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); } @Test void testResetTrackPositionChange() { String line = "time: 1"; final TrackPositionChangeEvent[] changeEvent = new TrackPositionChangeEvent[1]; trackMonitor.addTrackPositionChangeListener(event -> changeEvent[0] = event); trackMonitor.processResponseStatus(line); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); trackMonitor.reset(); changeEvent[0] = null; trackMonitor.processResponseStatus(line); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); } @Test void testMonitorResetElapsedTime() { String line = "time: 1"; final TrackPositionChangeEvent[] changeEvent = new TrackPositionChangeEvent[1]; trackMonitor.addTrackPositionChangeListener(event -> changeEvent[0] = event); trackMonitor.processResponseStatus(line); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); changeEvent[0] = null; trackMonitor.processResponseStatus(line); trackMonitor.checkStatus(); assertNull(changeEvent[0]); trackMonitor.reset(); trackMonitor.addTrackPositionChangeListener(event -> changeEvent[0] = event); trackMonitor.processResponseStatus(line); trackMonitor.checkStatus(); assertEquals(1, changeEvent[0].getElapsedTime()); } }
5,033
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDErrorMonitorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/monitor/MPDErrorMonitorTest.java
package org.bff.javampd.monitor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.bff.javampd.server.ErrorEvent; import org.bff.javampd.server.ErrorListener; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class MPDErrorMonitorTest { private ErrorMonitor errorMonitor; @BeforeEach void setUp() { errorMonitor = new MPDErrorMonitor(); } @Test void testAddErrorListener() { final ErrorEvent[] errorEvent = new ErrorEvent[1]; errorMonitor.addErrorListener(event -> errorEvent[0] = event); errorMonitor.processResponseStatus("error: message"); errorMonitor.checkStatus(); assertEquals("message", errorEvent[0].getMessage()); } @Test void testRemoveErrorListener() { final ErrorEvent[] errorEvent = new ErrorEvent[1]; ErrorListener errorListener = event -> errorEvent[0] = event; errorMonitor.addErrorListener(errorListener); errorMonitor.processResponseStatus("error: message"); errorMonitor.checkStatus(); assertEquals("message", errorEvent[0].getMessage()); errorEvent[0] = null; errorMonitor.removeErrorListener(errorListener); errorMonitor.processResponseStatus("error: message2"); errorMonitor.checkStatus(); assertNull(errorEvent[0]); } @Test void testInvalidStatus() { final ErrorEvent[] errorEvent = new ErrorEvent[1]; errorMonitor.addErrorListener(event -> errorEvent[0] = event); errorMonitor.processResponseStatus("bogus: message"); errorMonitor.checkStatus(); assertNull(errorEvent[0]); } @Test void testResetError() { String line = "error: message"; final ErrorEvent[] errorEvent = new ErrorEvent[1]; errorMonitor.addErrorListener(event -> errorEvent[0] = event); errorMonitor.processResponseStatus(line); errorMonitor.checkStatus(); assertEquals("message", errorEvent[0].getMessage()); errorMonitor.reset(); errorEvent[0] = null; errorMonitor.processResponseStatus(line); errorMonitor.checkStatus(); assertEquals("message", errorEvent[0].getMessage()); } }
2,158
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ThreadedMonitorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/monitor/ThreadedMonitorTest.java
package org.bff.javampd.monitor; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class ThreadedMonitorTest { private boolean checked; private boolean processedResponse; private boolean reset; private ThreadedMonitor threadedMonitor; @Test void testCheckStatusDelayed() { Monitor testMonitor = new TestMonitor(); threadedMonitor = new ThreadedMonitor(testMonitor, 1); threadedMonitor.checkStatus(); assertFalse(checked); } @Test void testCheckStatus() { Monitor testMonitor = new TestMonitor(); threadedMonitor = new ThreadedMonitor(testMonitor, 1); threadedMonitor.checkStatus(); threadedMonitor.checkStatus(); assertTrue(checked); } @Test void testShouldntProcessResponseLine() { Monitor testMonitor = new TestMonitor(); threadedMonitor = new ThreadedMonitor(testMonitor, 1); threadedMonitor.processResponseLine(""); assertFalse(processedResponse); } @Test void testProcessResponseLine() { Monitor testMonitor = new TestStatusMonitor(); threadedMonitor = new ThreadedMonitor(testMonitor, 1); threadedMonitor.processResponseLine(""); assertTrue(processedResponse); } @Test void testReset() { Monitor testMonitor = new TestStatusMonitor(); threadedMonitor = new ThreadedMonitor(testMonitor, 1); threadedMonitor.reset(); assertTrue(reset); } private class TestMonitor implements Monitor { @Override public void checkStatus() { checked = true; } } private class TestStatusMonitor implements StatusMonitor { @Override public void checkStatus() { checked = true; } @Override public void processResponseStatus(String line) { processedResponse = true; } @Override public void reset() { reset = true; } } }
1,933
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDConnectionMonitorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/monitor/MPDConnectionMonitorTest.java
package org.bff.javampd.monitor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.when; import org.bff.javampd.server.ConnectionChangeEvent; import org.bff.javampd.server.ConnectionChangeListener; import org.bff.javampd.server.Server; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDConnectionMonitorTest { @Mock private Server server; private ConnectionMonitor connectionMonitor; @BeforeEach void setUp() { connectionMonitor = new MPDConnectionMonitor(); connectionMonitor.setServer(server); } @Test void testAddConnectionChangeListener() { final ConnectionChangeEvent[] changeEvent = new ConnectionChangeEvent[1]; connectionMonitor.addConnectionChangeListener(event -> changeEvent[0] = event); when(server.isConnected()).thenReturn(false); connectionMonitor.checkStatus(); assertEquals(false, changeEvent[0].isConnected()); } @Test void testRemoveConnectionChangeListener() { final ConnectionChangeEvent[] changeEvent = new ConnectionChangeEvent[1]; ConnectionChangeListener connectionChangeListener = event -> changeEvent[0] = event; connectionMonitor.addConnectionChangeListener(connectionChangeListener); when(server.isConnected()).thenReturn(false); connectionMonitor.checkStatus(); assertEquals(false, changeEvent[0].isConnected()); changeEvent[0] = null; connectionMonitor.removeConnectionChangeListener(connectionChangeListener); when(server.isConnected()).thenReturn(true); connectionMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testNoChange() { final ConnectionChangeEvent[] changeEvent = new ConnectionChangeEvent[1]; connectionMonitor.addConnectionChangeListener(event -> changeEvent[0] = event); when(server.isConnected()).thenReturn(true); connectionMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testIsConnected() { when(server.isConnected()).thenReturn(false); connectionMonitor.checkStatus(); assertEquals(false, connectionMonitor.isConnected()); } }
2,363
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDOutputMonitorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/monitor/MPDOutputMonitorTest.java
package org.bff.javampd.monitor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.bff.javampd.admin.Admin; import org.bff.javampd.output.MPDOutput; import org.bff.javampd.output.OutputChangeEvent; import org.bff.javampd.output.OutputChangeListener; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDOutputMonitorTest { @Mock private Admin admin; @InjectMocks private MPDOutputMonitor outputMonitor; @Test void testAddOutputChangeListener() { final OutputChangeEvent[] outputEvent = new OutputChangeEvent[1]; outputMonitor.addOutputChangeListener(event -> outputEvent[0] = event); List<MPDOutput> testOutputs = new ArrayList<>(); testOutputs.add(MPDOutput.builder(0).build()); when(admin.getOutputs()).thenReturn(testOutputs); outputMonitor.checkStatus(); assertEquals(OutputChangeEvent.OUTPUT_EVENT.OUTPUT_ADDED, outputEvent[0].getEvent()); } @Test void testRemoveOutputChangeListener() { final OutputChangeEvent[] outputEvent = new OutputChangeEvent[1]; OutputChangeListener outputChangeListener = event -> outputEvent[0] = event; outputMonitor.addOutputChangeListener(outputChangeListener); List<MPDOutput> testOutputs = new ArrayList<>(); testOutputs.add(MPDOutput.builder(0).build()); when(admin.getOutputs()).thenReturn(testOutputs); outputMonitor.checkStatus(); assertEquals(OutputChangeEvent.OUTPUT_EVENT.OUTPUT_ADDED, outputEvent[0].getEvent()); outputEvent[0] = null; outputMonitor.removeOutputChangeListener(outputChangeListener); outputMonitor.checkStatus(); assertNull(outputEvent[0]); } @Test void testOutputAdded() { final OutputChangeEvent[] outputEvent = new OutputChangeEvent[1]; outputMonitor.addOutputChangeListener(event -> outputEvent[0] = event); List<MPDOutput> testOutputs = new ArrayList<>(); testOutputs.add(MPDOutput.builder(0).build()); testOutputs.add(MPDOutput.builder(1).build()); when(admin.getOutputs()).thenReturn(testOutputs); outputMonitor.checkStatus(); assertEquals(OutputChangeEvent.OUTPUT_EVENT.OUTPUT_ADDED, outputEvent[0].getEvent()); } @Test void testOutputRemoved() { final OutputChangeEvent[] outputEvent = new OutputChangeEvent[1]; outputMonitor.addOutputChangeListener(event -> outputEvent[0] = event); List<MPDOutput> testOutputs = new ArrayList<>(); testOutputs.add(MPDOutput.builder(0).build()); when(admin.getOutputs()).thenReturn(testOutputs); outputMonitor.checkStatus(); testOutputs = new ArrayList<>(); when(admin.getOutputs()).thenReturn(testOutputs); outputMonitor.checkStatus(); assertEquals(OutputChangeEvent.OUTPUT_EVENT.OUTPUT_DELETED, outputEvent[0].getEvent()); } @Test void testOutputChanged() { final OutputChangeEvent[] outputEvent = new OutputChangeEvent[1]; outputMonitor.addOutputChangeListener(event -> outputEvent[0] = event); List<MPDOutput> testOutputs = new ArrayList<>(); testOutputs.add(MPDOutput.builder(0).build()); when(admin.getOutputs()).thenReturn(testOutputs); outputMonitor.checkStatus(); testOutputs = new ArrayList<>(); MPDOutput output = MPDOutput.builder(0).build(); output.setEnabled(true); testOutputs.add(output); when(admin.getOutputs()).thenReturn(testOutputs); outputMonitor.checkStatus(); assertEquals(OutputChangeEvent.OUTPUT_EVENT.OUTPUT_CHANGED, outputEvent[0].getEvent()); } }
3,793
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDStandAloneMonitorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/monitor/MPDStandAloneMonitorTest.java
package org.bff.javampd.monitor; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.bff.javampd.output.OutputChangeListener; import org.bff.javampd.player.*; import org.bff.javampd.playlist.PlaylistBasicChangeListener; import org.bff.javampd.server.ConnectionChangeListener; import org.bff.javampd.server.ErrorListener; import org.bff.javampd.server.ServerStatus; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDStandAloneMonitorTest { @Mock private OutputMonitor outputMonitor; @Mock private ErrorMonitor errorMonitor; @Mock private ConnectionMonitor connectionMonitor; @Mock private PlayerMonitor playerMonitor; @Mock private TrackMonitor trackMonitor; @Mock private PlaylistMonitor playlistMonitor; @Mock private ServerStatus serverStatus; @InjectMocks private MPDStandAloneMonitor standAloneMonitor; @BeforeEach void setup() { Awaitility.setDefaultPollInterval(5, TimeUnit.MILLISECONDS); standAloneMonitor.start(); } @AfterEach void tearDown() { standAloneMonitor.stop(); } @Test void testAddTrackPositionChangeListener() { TrackPositionChangeListener tpl = event -> {}; standAloneMonitor.addTrackPositionChangeListener(tpl); verify(trackMonitor, times(1)).addTrackPositionChangeListener(tpl); } @Test void testRemoveTrackPositionChangeListener() { TrackPositionChangeListener tpl = event -> {}; standAloneMonitor.removeTrackPositionChangeListener(tpl); verify(trackMonitor, times(1)).removeTrackPositionChangeListener(tpl); } @Test void testAddConnectionChangeListener() { ConnectionChangeListener ccl = event -> {}; standAloneMonitor.addConnectionChangeListener(ccl); verify(connectionMonitor, times(1)).addConnectionChangeListener(ccl); } @Test void testRemoveConnectionChangeListener() { ConnectionChangeListener ccl = event -> {}; standAloneMonitor.removeConnectionChangeListener(ccl); verify(connectionMonitor, times(1)).removeConnectionChangeListener(ccl); } @Test void testAddPlayerChangeListener() { PlayerBasicChangeListener pbcl = event -> {}; standAloneMonitor.addPlayerChangeListener(pbcl); verify(playerMonitor, times(1)).addPlayerChangeListener(pbcl); } @Test void testRemovePlayerChangeListener() { PlayerBasicChangeListener pbcl = event -> {}; standAloneMonitor.removePlayerChangeListener(pbcl); verify(playerMonitor, times(1)).removePlayerChangeListener(pbcl); } @Test void testAddVolumeChangeListener() { VolumeChangeListener vcl = event -> {}; standAloneMonitor.addVolumeChangeListener(vcl); verify(playerMonitor, times(1)).addVolumeChangeListener(vcl); } @Test void testRemoveVolumeChangeListener() { VolumeChangeListener vcl = event -> {}; standAloneMonitor.removeVolumeChangeListener(vcl); verify(playerMonitor, times(1)).removeVolumeChangeListener(vcl); } @Test void testAddBitrateChangeListener() { BitrateChangeListener bcl = event -> {}; standAloneMonitor.addBitrateChangeListener(bcl); verify(playerMonitor, times(1)).addBitrateChangeListener(bcl); } @Test void testRemoveBitrateChangeListener() { BitrateChangeListener bcl = event -> {}; standAloneMonitor.removeBitrateChangeListener(bcl); verify(playerMonitor, times(1)).removeBitrateChangeListener(bcl); } @Test void testAddOutputChangeListener() { OutputChangeListener ocl = event -> {}; standAloneMonitor.addOutputChangeListener(ocl); verify(outputMonitor, times(1)).addOutputChangeListener(ocl); } @Test void testRemoveOutputChangeListener() { OutputChangeListener ocl = event -> {}; standAloneMonitor.removeOutputChangeListener(ocl); verify(outputMonitor, times(1)).removeOutputChangeListener(ocl); } @Test void testAddPlaylistChangeListener() { PlaylistBasicChangeListener pbcl = event -> {}; standAloneMonitor.addPlaylistChangeListener(pbcl); verify(playlistMonitor, times(1)).addPlaylistChangeListener(pbcl); } @Test void testRemovePlaylistStatusChangeListener() { PlaylistBasicChangeListener pbcl = event -> {}; standAloneMonitor.removePlaylistChangeListener(pbcl); verify(playlistMonitor, times(1)).removePlaylistChangeListener(pbcl); } @Test void testAddErrorListener() { ErrorListener el = event -> {}; standAloneMonitor.addErrorListener(el); verify(errorMonitor, times(1)).addErrorListener(el); } @Test void testRemoveErrorListener() { ErrorListener el = event -> {}; standAloneMonitor.removeErrorListener(el); verify(errorMonitor, times(1)).removeErrorListener(el); } @Test void testStart() { standAloneMonitor.start(); assertFalse(standAloneMonitor.isDone()); } @Test void testLoaded() { List<String> status = new ArrayList<>(); status.add("volume: 2"); when(serverStatus.getStatus()).thenReturn(status); standAloneMonitor.start(); await().until(() -> standAloneMonitor.isLoaded()); } @Test void testStop() { standAloneMonitor.start(); await().until(() -> !standAloneMonitor.isDone()); standAloneMonitor.stop(); await().until(() -> standAloneMonitor.isDone()); } @Test void testPlayerBasicChangeStopped() { PlayerBasicChangeEvent event = new PlayerBasicChangeEvent(this, PlayerBasicChangeEvent.Status.PLAYER_STOPPED); standAloneMonitor.playerBasicChange(event); verify(trackMonitor, times(1)).resetElapsedTime(); verify(playlistMonitor, times(1)).playerStopped(); } @Test void testPlayerBasicChangeNotStopped() { PlayerBasicChangeEvent event = new PlayerBasicChangeEvent(this, PlayerBasicChangeEvent.Status.PLAYER_STARTED); standAloneMonitor.playerBasicChange(event); verify(trackMonitor, never()).resetElapsedTime(); verify(playlistMonitor, never()).playerStopped(); } }
6,348
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistMonitorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/monitor/MPDPlaylistMonitorTest.java
package org.bff.javampd.monitor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.when; import org.bff.javampd.playlist.PlaylistBasicChangeEvent; import org.bff.javampd.playlist.PlaylistBasicChangeListener; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDPlaylistMonitorTest { @Mock private PlayerMonitor playerMonitor; @InjectMocks private MPDPlaylistMonitor playlistMonitor; @Test void testAddPlaylistChangeListener() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event.SONG_ADDED); assertEquals(PlaylistBasicChangeEvent.Event.SONG_ADDED, changeEvent[0]); } @Test void testRemovePlaylistChangeListener() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; PlaylistBasicChangeListener playlistChangeListener = event -> changeEvent[0] = event.getEvent(); playlistMonitor.addPlaylistChangeListener(playlistChangeListener); playlistMonitor.firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event.SONG_ADDED); assertEquals(PlaylistBasicChangeEvent.Event.SONG_ADDED, changeEvent[0]); playlistMonitor.removePlaylistChangeListener(playlistChangeListener); playlistMonitor.firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event.SONG_DELETED); assertEquals(PlaylistBasicChangeEvent.Event.SONG_ADDED, changeEvent[0]); } @Test void testGetSongId() { playlistMonitor.processResponseStatus("songid: 1"); assertEquals(1, playlistMonitor.getSongId()); } @Test void testPlayerStopped() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus("songid: -1"); playlistMonitor.playerStopped(); assertEquals(PlaylistBasicChangeEvent.Event.PLAYLIST_ENDED, changeEvent[0]); } @Test void testPlayerNotStopped() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus("songid: 1"); playlistMonitor.playerStopped(); assertNull(changeEvent[0]); } @Test void testProcessResponseStatusPlaylistChanged() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus("playlist: 1"); playlistMonitor.checkStatus(); assertEquals(PlaylistBasicChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0]); } @Test void testProcessResponseStatusPlaylistNotChanged() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus("playlist: 1"); playlistMonitor.checkStatus(); assertEquals(PlaylistBasicChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0]); changeEvent[0] = null; playlistMonitor.processResponseStatus("playlist: 1"); playlistMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testProcessResponseStatusSongAdded() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus("playlistlength: 1"); playlistMonitor.checkStatus(); assertEquals(PlaylistBasicChangeEvent.Event.SONG_ADDED, changeEvent[0]); } @Test void testProcessResponseStatusSongDeleted() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus("playlistlength: 1"); playlistMonitor.checkStatus(); playlistMonitor.processResponseStatus("playlistlength: 0"); playlistMonitor.checkStatus(); assertEquals(PlaylistBasicChangeEvent.Event.SONG_DELETED, changeEvent[0]); } @Test void testProcessResponseStatusSongUnchanged() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus("playlistlength: 1"); playlistMonitor.checkStatus(); changeEvent[0] = null; playlistMonitor.processResponseStatus("playlistlength: 1"); playlistMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testProcessResponseStatusSongChanged() { statusSongChanged("song: 1"); } @Test void testProcessResponseStatusSongChangedById() { statusSongChanged("songid: 1"); } private void statusSongChanged(String line) { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus(line); when(playerMonitor.getStatus()).thenReturn(PlayerStatus.STATUS_PLAYING); playlistMonitor.checkStatus(); assertEquals(PlaylistBasicChangeEvent.Event.SONG_CHANGED, changeEvent[0]); } private void statusSongNoChange(String line) { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus(line); when(playerMonitor.getStatus()).thenReturn(PlayerStatus.STATUS_PLAYING); playlistMonitor.checkStatus(); changeEvent[0] = null; playlistMonitor.processResponseStatus(line); when(playerMonitor.getStatus()).thenReturn(PlayerStatus.STATUS_PLAYING); playlistMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testProcessResponseStatusSongNoChange() { statusSongNoChange("song: 1"); } @Test void testProcessResponseStatusSongNoChangeById() { statusSongNoChange("songid: 1"); } @Test void testProcessResponseStatusPlaylistNothing() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.processResponseStatus("bogus: 1"); playlistMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testSongChangeNotPlaying() { final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus("song: 1"); when(playerMonitor.getStatus()).thenReturn(PlayerStatus.STATUS_STOPPED); playlistMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testResetSongId() { String line = "songid: 1"; statusSongChanged(line); playlistMonitor.reset(); statusSongChanged(line); } @Test void testResetSong() { String line = "song: 1"; statusSongChanged(line); playlistMonitor.reset(); statusSongChanged(line); } @Test void testResetPlaylistVersion() { String line = "playlist: 1"; final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus(line); playlistMonitor.checkStatus(); assertEquals(PlaylistBasicChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0]); playlistMonitor.reset(); changeEvent[0] = null; playlistMonitor.processResponseStatus(line); playlistMonitor.checkStatus(); assertEquals(PlaylistBasicChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0]); } @Test void testResetPlaylistLength() { String line = "playlistlength: 1"; final PlaylistBasicChangeEvent.Event[] changeEvent = new PlaylistBasicChangeEvent.Event[1]; playlistMonitor.addPlaylistChangeListener(event -> changeEvent[0] = event.getEvent()); playlistMonitor.processResponseStatus(line); playlistMonitor.checkStatus(); assertEquals(PlaylistBasicChangeEvent.Event.SONG_ADDED, changeEvent[0]); playlistMonitor.reset(); changeEvent[0] = null; playlistMonitor.processResponseStatus(line); playlistMonitor.checkStatus(); assertEquals(PlaylistBasicChangeEvent.Event.SONG_ADDED, changeEvent[0]); } }
9,053
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDBitrateMonitorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/monitor/MPDBitrateMonitorTest.java
package org.bff.javampd.monitor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.bff.javampd.player.BitrateChangeEvent; import org.bff.javampd.player.BitrateChangeListener; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class MPDBitrateMonitorTest { private BitrateMonitor bitrateMonitor; @BeforeEach void setup() { bitrateMonitor = new MPDBitrateMonitor(); } @Test void testAddBitrateChangeListener() { final BitrateChangeEvent[] changeEvent = new BitrateChangeEvent[1]; bitrateMonitor.addBitrateChangeListener(event -> changeEvent[0] = event); bitrateMonitor.processResponseStatus("bitrate: 1"); bitrateMonitor.checkStatus(); assertEquals(0, changeEvent[0].getOldBitrate()); assertEquals(1, changeEvent[0].getNewBitrate()); } @Test void testRemoveBitrateChangeListener() { final BitrateChangeEvent[] changeEvent = new BitrateChangeEvent[1]; BitrateChangeListener bitrateChangeListener = event -> changeEvent[0] = event; bitrateMonitor.addBitrateChangeListener(bitrateChangeListener); bitrateMonitor.processResponseStatus("bitrate: 1"); bitrateMonitor.checkStatus(); assertEquals(0, changeEvent[0].getOldBitrate()); assertEquals(1, changeEvent[0].getNewBitrate()); changeEvent[0] = null; bitrateMonitor.removeBitrateChangeListener(bitrateChangeListener); bitrateMonitor.processResponseStatus("bitrate: 2"); bitrateMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testBitrateNoChange() { final BitrateChangeEvent[] changeEvent = new BitrateChangeEvent[1]; bitrateMonitor.addBitrateChangeListener(event -> changeEvent[0] = event); bitrateMonitor.processResponseStatus("bitrate: 1"); bitrateMonitor.checkStatus(); assertEquals(0, changeEvent[0].getOldBitrate()); assertEquals(1, changeEvent[0].getNewBitrate()); changeEvent[0] = null; bitrateMonitor.processResponseStatus("bitrate: 1"); bitrateMonitor.checkStatus(); assertNull(changeEvent[0]); } @Test void testResetBitrateChangeListener() { String line = "bitrate: 1"; final BitrateChangeEvent[] changeEvent = new BitrateChangeEvent[1]; bitrateMonitor.addBitrateChangeListener(event -> changeEvent[0] = event); bitrateMonitor.processResponseStatus(line); bitrateMonitor.checkStatus(); assertEquals(0, changeEvent[0].getOldBitrate()); assertEquals(1, changeEvent[0].getNewBitrate()); bitrateMonitor.reset(); changeEvent[0] = null; bitrateMonitor.processResponseStatus(line); bitrateMonitor.checkStatus(); assertEquals(0, changeEvent[0].getOldBitrate()); assertEquals(1, changeEvent[0].getNewBitrate()); } }
2,802
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDGenreDatabaseTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/genre/MPDGenreDatabaseTest.java
package org.bff.javampd.genre; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.bff.javampd.database.TagLister; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDGenreDatabaseTest { private static final String GENRE_PREFIX = "Genre: "; @Mock private TagLister tagLister; @InjectMocks private MPDGenreDatabase genreDatabase; @Test void testListAllGenres() { MPDGenre testGenre1 = new MPDGenre("Genre1"); MPDGenre testGenre2 = new MPDGenre("Genre2"); List<String> testGenres = new ArrayList<>(); testGenres.add(GENRE_PREFIX + testGenre1.name()); testGenres.add(GENRE_PREFIX + testGenre2.name()); when(tagLister.list(TagLister.ListType.GENRE)).thenReturn(testGenres); List<MPDGenre> genres = new ArrayList<>(genreDatabase.listAllGenres()); assertEquals(testGenres.size(), genres.size()); assertEquals(testGenre1, genres.getFirst()); assertEquals(testGenre2, genres.get(1)); } @Test void testListGenreByName() { MPDGenre genre = new MPDGenre("Genre1"); List<String> testGenres = new ArrayList<>(); testGenres.add(GENRE_PREFIX + genre.name()); List<String> list = new ArrayList<>(); list.add(TagLister.ListType.GENRE.getType()); list.add(genre.name()); when(tagLister.list(TagLister.ListType.GENRE, list)).thenReturn(testGenres); assertEquals(genre, genreDatabase.listGenreByName(genre.name())); } @Test void testListGenreByNameMultiples() { MPDGenre genre1 = new MPDGenre("Genre1"); MPDGenre genre2 = new MPDGenre("Genre2"); List<String> testGenres = new ArrayList<>(); testGenres.add(GENRE_PREFIX + genre1.name()); testGenres.add(GENRE_PREFIX + genre2.name()); List<String> list = new ArrayList<>(); list.add(TagLister.ListType.GENRE.getType()); list.add(genre1.name()); when(tagLister.list(TagLister.ListType.GENRE, list)).thenReturn(testGenres); assertEquals(genre1, genreDatabase.listGenreByName(genre1.name())); } }
2,275
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAlbumConverterTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/album/MPDAlbumConverterTest.java
package org.bff.javampd.album; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.ArrayList; import java.util.Arrays; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class MPDAlbumConverterTest { private AlbumConverter converter; @BeforeEach void before() { converter = new MPDAlbumConverter(); } @Test @DisplayName("list of one album with single tags") void simpleAlbum() { var response = Arrays.asList( "AlbumArtist: Greta Van Fleet", "Genre: Rock", "Date: 2018", "Artist: Greta Van Fleet", "Album: Anthem of the Peaceful Army"); var albums = new ArrayList<>(converter.convertResponseToAlbum(response)); var a = albums.getFirst(); assertAll( () -> assertThat(a.getName(), is(equalTo("Anthem of the Peaceful Army"))), () -> assertThat(albums.size(), is(equalTo(1))), () -> assertThat(a.getAlbumArtist(), is(equalTo("Greta Van Fleet"))), () -> assertThat(a.getArtistNames().size(), is(equalTo(1))), () -> assertThat(a.getArtistNames().getFirst(), is(equalTo("Greta Van Fleet"))), () -> assertThat(a.getGenres().size(), is(equalTo(1))), () -> assertThat(a.getGenres().getFirst(), is(equalTo("Rock"))), () -> assertThat(a.getDates().size(), is(equalTo(1))), () -> assertThat(a.getDates().getFirst(), is(equalTo("2018")))); } @Test @DisplayName("list of one album with single tags") void unknownAttribute() { var response = Arrays.asList( "AlbumArtist: Greta Van Fleet", "Genre: Rock", "Date: 2018", "Artist: Greta Van Fleet", "Unknown: something unexpected", "Album: Anthem of the Peaceful Army"); var albums = new ArrayList<>(converter.convertResponseToAlbum(response)); var a = albums.getFirst(); assertAll( () -> assertThat(a.getName(), is(equalTo("Anthem of the Peaceful Army"))), () -> assertThat(albums.size(), is(equalTo(1))), () -> assertThat(a.getAlbumArtist(), is(equalTo("Greta Van Fleet"))), () -> assertThat(a.getArtistNames().size(), is(equalTo(1))), () -> assertThat(a.getArtistNames().getFirst(), is(equalTo("Greta Van Fleet"))), () -> assertThat(a.getGenres().size(), is(equalTo(1))), () -> assertThat(a.getGenres().getFirst(), is(equalTo("Rock"))), () -> assertThat(a.getDates().size(), is(equalTo(1))), () -> assertThat(a.getDates().getFirst(), is(equalTo("2018")))); } @Test void clearAttributes() { var response = Arrays.asList( "AlbumArtist: Spiritbox", "Genre: Metal", "Date: 2021", "Artist: Spiritbox", "Album: Eternal Blue", "Artist: Tool", "Album: Lateralus"); var albums = new ArrayList<>(converter.convertResponseToAlbum(response)); var a = albums.get(1); assertAll( () -> assertThat(a.getName(), is(equalTo("Lateralus"))), () -> assertNull(a.getAlbumArtist()), () -> assertThat(a.getArtistNames().size(), is(equalTo(1))), () -> assertThat(a.getArtistNames().getFirst(), is(equalTo("Tool"))), () -> assertThat(a.getGenres().size(), is(equalTo(0))), () -> assertThat(a.getDates().size(), is(equalTo(0)))); } @Test void multipleArtists() { var response = Arrays.asList( "AlbumArtist: Spiritbox", "Genre: Metal", "Date: 2021", "Artist: Spiritbox", "Album: Eternal Blue", "Artist: Spiritbox feat. Sam Carter", "Album: Eternal Blue"); var albums = new ArrayList<>(converter.convertResponseToAlbum(response)); var a = albums.getFirst(); assertAll( () -> assertThat(albums.size(), is(equalTo(1))), () -> assertThat(a.getName(), is(equalTo("Eternal Blue"))), () -> assertThat(a.getAlbumArtist(), is(equalTo("Spiritbox"))), () -> assertThat(a.getArtistNames().size(), is(equalTo(2))), () -> assertThat(a.getArtistNames().getFirst(), is(equalTo("Spiritbox"))), () -> assertThat(a.getArtistNames().get(1), is(equalTo("Spiritbox feat. Sam Carter"))), () -> assertThat(a.getGenres().size(), is(equalTo(1))), () -> assertThat(a.getGenres().getFirst(), is(equalTo("Metal"))), () -> assertThat(a.getDates().size(), is(equalTo(1))), () -> assertThat(a.getDates().getFirst(), is(equalTo("2021")))); } }
4,829
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
AlbumProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/album/AlbumProcessorTest.java
package org.bff.javampd.album; import static org.bff.javampd.album.AlbumProcessor.ALBUM_ARTIST; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class AlbumProcessorTest { @Test @DisplayName("looks up processor for different cases") void lookupLine() { assertAll( () -> assertEquals(ALBUM_ARTIST, AlbumProcessor.lookup("albumartist: Tool")), () -> assertEquals(ALBUM_ARTIST, AlbumProcessor.lookup("ALBUMARTIST: Tool")), () -> assertEquals(ALBUM_ARTIST, AlbumProcessor.lookup("AlbumArtist: Tool"))); } }
690
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAlbumDatabaseTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/album/MPDAlbumDatabaseTest.java
package org.bff.javampd.album; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.database.TagLister; import org.bff.javampd.genre.MPDGenre; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDAlbumDatabaseTest { @Captor private ArgumentCaptor<List<String>> argumentCaptor; @Captor private ArgumentCaptor<TagLister.GroupType> groupCaptor; @Captor private ArgumentCaptor<TagLister.ListType> listCaptor; @Mock private TagLister tagLister; private MPDAlbumDatabase albumDatabase; @BeforeEach void before() { albumDatabase = new MPDAlbumDatabase(tagLister, new MPDAlbumConverter()); } @Test void albumsByAlbumArtist() { String albumArtist = "Tool"; when(tagLister.list(any(), (List<String>) any(), any(), any(), any(), any())) .thenReturn(new ArrayList<>()); albumDatabase.listAlbumsByAlbumArtist(new MPDArtist(albumArtist)); verify(tagLister) .list( listCaptor.capture(), argumentCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture()); assertAll( () -> assertEquals("albumartist", argumentCaptor.getValue().getFirst()), () -> assertEquals(albumArtist, argumentCaptor.getValue().get(1)), () -> assertEquals(TagLister.GroupType.ARTIST, groupCaptor.getAllValues().getFirst()), () -> assertEquals(TagLister.GroupType.DATE, groupCaptor.getAllValues().get(1)), () -> assertEquals(TagLister.GroupType.GENRE, groupCaptor.getAllValues().get(2)), () -> assertEquals(TagLister.GroupType.ALBUM_ARTIST, groupCaptor.getAllValues().get(3))); } @Test void albumsByArtist() { String artist = "Tool"; when(tagLister.list(any(), (List<String>) any(), any(), any(), any(), any())) .thenReturn(new ArrayList<>()); albumDatabase.listAlbumsByArtist(new MPDArtist(artist)); verify(tagLister) .list( listCaptor.capture(), argumentCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture()); assertAll( () -> assertEquals("artist", argumentCaptor.getValue().getFirst()), () -> assertEquals(artist, argumentCaptor.getValue().get(1)), () -> assertEquals(TagLister.GroupType.ARTIST, groupCaptor.getAllValues().getFirst()), () -> assertEquals(TagLister.GroupType.DATE, groupCaptor.getAllValues().get(1)), () -> assertEquals(TagLister.GroupType.GENRE, groupCaptor.getAllValues().get(2)), () -> assertEquals(TagLister.GroupType.ALBUM_ARTIST, groupCaptor.getAllValues().get(3))); } @Test void allAlbums() { when(tagLister.list(any(), (TagLister.GroupType) any(), any(), any(), any())) .thenReturn(new ArrayList<>()); albumDatabase.listAllAlbums(); verify(tagLister) .list( listCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture()); assertAll( () -> assertEquals(TagLister.ListType.ALBUM, listCaptor.getValue()), () -> assertEquals(TagLister.GroupType.ARTIST, groupCaptor.getAllValues().getFirst()), () -> assertEquals(TagLister.GroupType.DATE, groupCaptor.getAllValues().get(1)), () -> assertEquals(TagLister.GroupType.GENRE, groupCaptor.getAllValues().get(2)), () -> assertEquals(TagLister.GroupType.ALBUM_ARTIST, groupCaptor.getAllValues().get(3))); } @Test void allAlbumNames() { when(tagLister.list(any())).thenReturn(new ArrayList<>()); albumDatabase.listAllAlbumNames(); verify(tagLister).list(listCaptor.capture()); assertEquals(TagLister.ListType.ALBUM, listCaptor.getValue()); } @Test void allAlbumNamesParsing() { when(tagLister.list(any())) .thenReturn( Arrays.asList( "Album: 10,000 Days", "Album: 72826", "Album: Anthem of the Peaceful Army", "Album: Dark Before Dawn")); var albums = new ArrayList<>(albumDatabase.listAllAlbumNames()); assertAll( () -> assertEquals("10,000 Days", albums.getFirst()), () -> assertEquals("72826", albums.get(1)), () -> assertEquals("Anthem of the Peaceful Army", albums.get(2)), () -> assertEquals("Dark Before Dawn", albums.get(3))); } @Test void findAlbumsByName() { String album = "Saturate"; when(tagLister.list(any(), (List<String>) any(), any(), any(), any(), any())) .thenReturn(new ArrayList<>()); albumDatabase.findAlbum(album); verify(tagLister) .list( listCaptor.capture(), argumentCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture()); assertAll( () -> assertEquals("album", argumentCaptor.getValue().getFirst()), () -> assertEquals(album, argumentCaptor.getValue().get(1)), () -> assertEquals(TagLister.GroupType.ARTIST, groupCaptor.getAllValues().getFirst()), () -> assertEquals(TagLister.GroupType.DATE, groupCaptor.getAllValues().get(1)), () -> assertEquals(TagLister.GroupType.GENRE, groupCaptor.getAllValues().get(2)), () -> assertEquals(TagLister.GroupType.ALBUM_ARTIST, groupCaptor.getAllValues().get(3))); } @Test void albumsByGenre() { String genre = "Heavy Metal"; when(tagLister.list(any(), (List<String>) any(), any(), any(), any(), any())) .thenReturn(new ArrayList<>()); albumDatabase.listAlbumsByGenre(new MPDGenre(genre)); verify(tagLister) .list( listCaptor.capture(), argumentCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture()); assertAll( () -> assertEquals("genre", argumentCaptor.getValue().getFirst()), () -> assertEquals(genre, argumentCaptor.getValue().get(1)), () -> assertEquals(TagLister.GroupType.ARTIST, groupCaptor.getAllValues().getFirst()), () -> assertEquals(TagLister.GroupType.DATE, groupCaptor.getAllValues().get(1)), () -> assertEquals(TagLister.GroupType.GENRE, groupCaptor.getAllValues().get(2)), () -> assertEquals(TagLister.GroupType.ALBUM_ARTIST, groupCaptor.getAllValues().get(3))); } @Test void albumsByYear() { String year = "1990"; when(tagLister.list(any(), (List<String>) any(), any(), any(), any(), any())) .thenReturn(new ArrayList<>()); albumDatabase.listAlbumsByYear(year); verify(tagLister) .list( listCaptor.capture(), argumentCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture(), groupCaptor.capture()); assertAll( () -> assertEquals("date", argumentCaptor.getValue().getFirst()), () -> assertEquals(year, argumentCaptor.getValue().get(1)), () -> assertEquals(TagLister.GroupType.ARTIST, groupCaptor.getAllValues().getFirst()), () -> assertEquals(TagLister.GroupType.DATE, groupCaptor.getAllValues().get(1)), () -> assertEquals(TagLister.GroupType.GENRE, groupCaptor.getAllValues().get(2)), () -> assertEquals(TagLister.GroupType.ALBUM_ARTIST, groupCaptor.getAllValues().get(3))); } }
8,041
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAlbumTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/album/MPDAlbumTest.java
package org.bff.javampd.album; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.*; import java.util.Arrays; import java.util.Collections; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * @author Bill */ class MPDAlbumTest { @Test @DisplayName("add artist using default list") void defaultArtistList() { var artist = "Greta Van Fleet"; var album = MPDAlbum.builder("Anthem of the Peaceful Army").build(); album.addArtist(artist); assertThat(artist, is(equalTo(album.getArtistNames().getFirst()))); } @Test void addArtist() { var album = MPDAlbum.builder("album").build(); album.addArtist("Tool"); assertThat("Tool", is(equalTo(album.getArtistNames().getFirst()))); } @Test void addArtists() { var album = MPDAlbum.builder("album").build(); album.addArtists(Arrays.asList("Tool", "Breaking Benjamin")); assertAll( () -> assertThat(2, is(equalTo(album.getArtistNames().size()))), () -> assertThat("Tool", is(equalTo(album.getArtistNames().getFirst()))), () -> assertThat("Breaking Benjamin", is(equalTo(album.getArtistNames().get(1))))); } @Test void addGenre() { var album = MPDAlbum.builder("album").build(); album.addGenre("Rock"); assertThat("Rock", is(equalTo(album.getGenres().getFirst()))); } @Test void addGenres() { var album = MPDAlbum.builder("album").build(); album.addGenres(Arrays.asList("Rock", "Heavy Metal")); assertAll( () -> assertThat(2, is(equalTo(album.getGenres().size()))), () -> assertThat("Rock", is(equalTo(album.getGenres().getFirst()))), () -> assertThat("Heavy Metal", is(equalTo(album.getGenres().get(1))))); } @Test void addDate() { var album = MPDAlbum.builder("album").build(); album.addDate("1990"); assertThat("1990", is(equalTo(album.getDates().getFirst()))); } @Test void addDates() { var album = MPDAlbum.builder("album").build(); album.addDates(Arrays.asList("1990", "2006-05-24")); assertAll( () -> assertThat(2, is(equalTo(album.getDates().size()))), () -> assertThat("1990", is(equalTo(album.getDates().getFirst()))), () -> assertThat("2006-05-24", is(equalTo(album.getDates().get(1))))); } @Test void testCompareToLessThanZero() { MPDAlbum album1 = MPDAlbum.builder("Album1").artistNames(Collections.singletonList("artistName1")).build(); MPDAlbum album2 = MPDAlbum.builder("Album2").artistNames(Collections.singletonList("artistName1")).build(); assertTrue(album1.compareTo(album2) < 0); } @Test void testCompareToGreaterThanZero() { MPDAlbum album1 = MPDAlbum.builder("Album2").artistNames(Collections.singletonList("artistName1")).build(); MPDAlbum album2 = MPDAlbum.builder("Album1").artistNames(Collections.singletonList("artistName1")).build(); assertTrue(album1.compareTo(album2) > 0); } @Test void testCompareToEquals() { MPDAlbum album1 = MPDAlbum.builder("Album1").artistNames(Collections.singletonList("artistName1")).build(); MPDAlbum album2 = MPDAlbum.builder("Album1").artistNames(Collections.singletonList("artistName1")).build(); assertEquals(0, album1.compareTo(album2)); } @Test void equalsContract() { EqualsVerifier.simple().forClass(MPDAlbum.class).verify(); } }
3,581
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDCommandTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/command/MPDCommandTest.java
package org.bff.javampd.command; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class MPDCommandTest { @Test void testCommand() { MPDCommand mpdCommand = new MPDCommand("command"); assertEquals("command", mpdCommand.getCommand()); } @Test void testCommandWithOneParm() { MPDCommand mpdCommand = new MPDCommand("command", "parm"); assertEquals("command", mpdCommand.getCommand()); } @Test void testCommandWithParms() { MPDCommand mpdCommand = new MPDCommand("command", "parm1", "parm2"); assertEquals("command", mpdCommand.getCommand()); } @Test void testParmsWithNoParam() { MPDCommand mpdCommand = new MPDCommand("command"); assertEquals(0, mpdCommand.getParams().size()); } @Test void testParmsWithOneParm() { MPDCommand mpdCommand = new MPDCommand("command", "parm"); assertEquals(1, mpdCommand.getParams().size()); assertEquals("parm", mpdCommand.getParams().getFirst()); } @Test void testParmsWithMultipleParms() { MPDCommand mpdCommand = new MPDCommand("command", "parm1", "parm2"); assertEquals(2, mpdCommand.getParams().size()); assertEquals("parm1", mpdCommand.getParams().getFirst()); assertEquals("parm2", mpdCommand.getParams().get(1)); } @Test void equalsContract() { EqualsVerifier.simple().forClass(MPDCommand.class).verify(); } @Test void testNullException() { assertThrows(IllegalArgumentException.class, () -> new MPDCommand(null)); } }
1,638
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDCommandExecutorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/command/MPDCommandExecutorTest.java
package org.bff.javampd.command; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import org.bff.javampd.server.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDCommandExecutorTest { @Mock private MPDSocket mpdSocket; @Mock private MPD mpd; @Captor private ArgumentCaptor<String> paramCaptor; @Captor private ArgumentCaptor<String> commandStringCaptor; @Captor private ArgumentCaptor<MPDCommand> commandCaptor; @InjectMocks private MPDCommandExecutor commandExecutor; @Test void testGetVersion() { when(mpdSocket.getVersion()).thenReturn("version"); assertEquals("version", commandExecutor.getMPDVersion()); } @Test void testSendCommandNoMPDSet() { commandExecutor = new MPDCommandExecutor(); assertThrows(MPDConnectionException.class, () -> commandExecutor.sendCommand("command")); } @Test void testSendCommandString() { String commandString = "command"; MPDCommand command = new MPDCommand(commandString); commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); List<String> testResponse = new ArrayList<>(); testResponse.add("testResponse"); when(mpdSocket.sendCommand(command)).thenReturn(testResponse); List<String> response = commandExecutor.sendCommand(commandString); verify(mpdSocket).sendCommand(commandCaptor.capture()); assertAll( () -> assertEquals(response.getFirst(), testResponse.get(0)), () -> assertEquals("command", commandCaptor.getAllValues().get(0).getCommand())); } @Test void testSendCommand() { MPDCommand command = new MPDCommand("command"); commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); List<String> testResponse = new ArrayList<>(); testResponse.add("testResponse"); when(mpdSocket.sendCommand(command)).thenReturn(testResponse); List<String> response = commandExecutor.sendCommand(command); verify(mpdSocket).sendCommand(commandCaptor.capture()); assertAll( () -> assertEquals(response.getFirst(), testResponse.get(0)), () -> assertEquals("command", commandCaptor.getAllValues().get(0).getCommand())); } @Test void testSendCommandWithStringParams() { String commandString = "command"; String paramString = "param"; MPDCommand command = new MPDCommand(commandString, paramString); commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); List<String> testResponse = new ArrayList<>(); testResponse.add("testResponse"); when(mpdSocket.sendCommand(command)).thenReturn(testResponse); List<String> response = commandExecutor.sendCommand(commandString, paramString); verify(mpdSocket).sendCommand(commandCaptor.capture()); assertAll( () -> assertEquals(response.getFirst(), testResponse.get(0)), () -> assertEquals("command", commandCaptor.getAllValues().get(0).getCommand()), () -> assertEquals("param", commandCaptor.getAllValues().get(0).getParams().get(0))); assertEquals(response.get(0), testResponse.get(0)); } @Test @DisplayName("Escape double quote search parameter") void testSendCommandWithQuote() { String commandString = "command"; String paramString = "param\""; commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); List<String> testResponse = new ArrayList<>(); testResponse.add("testResponse"); when(mpdSocket.sendCommand(new MPDCommand(commandString, "param\\\""))) .thenReturn(testResponse); List<String> response = commandExecutor.sendCommand(commandString, paramString); verify(mpdSocket).sendCommand(commandCaptor.capture()); assertAll( () -> assertEquals(response.get(0), testResponse.get(0)), () -> assertEquals("command", commandCaptor.getAllValues().get(0).getCommand()), () -> assertEquals("param\\\"", commandCaptor.getAllValues().get(0).getParams().get(0))); } @Test @DisplayName("Escape multiple double quotes search parameter") void testSendCommandWithMultipleQuotes() { String commandString = "command"; String paramString = "pa\"ram\""; commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); List<String> testResponse = new ArrayList<>(); testResponse.add("testResponse"); when(mpdSocket.sendCommand(new MPDCommand(commandString, "pa\\\"ram\\\""))) .thenReturn(testResponse); List<String> response = commandExecutor.sendCommand(commandString, paramString); verify(mpdSocket).sendCommand(commandCaptor.capture()); assertAll( () -> assertEquals(response.get(0), testResponse.get(0)), () -> assertEquals("command", commandCaptor.getAllValues().get(0).getCommand()), () -> assertEquals("pa\\\"ram\\\"", commandCaptor.getAllValues().get(0).getParams().get(0))); } @Test @DisplayName("Escape multiple double quotes for multiple search parameters") void testSendCommandsWithMultipleQuotes() { String commandString = "command"; String paramString1 = "pa\"ram\"1"; String paramString2 = "pa\"ram\"2"; commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); List<String> testResponse = new ArrayList<>(); testResponse.add("testResponse"); when(mpdSocket.sendCommand(new MPDCommand(commandString, "pa\\\"ram\\\"1", "pa\\\"ram\\\"2"))) .thenReturn(testResponse); List<String> response = commandExecutor.sendCommand(commandString, paramString1, paramString2); verify(mpdSocket).sendCommand(commandCaptor.capture()); assertAll( () -> assertEquals(response.get(0), testResponse.get(0)), () -> assertEquals("command", commandCaptor.getAllValues().get(0).getCommand()), () -> assertEquals("pa\\\"ram\\\"1", commandCaptor.getAllValues().get(0).getParams().get(0)), () -> assertEquals("pa\\\"ram\\\"2", commandCaptor.getAllValues().get(0).getParams().get(1))); } @Test void testSendCommandWithIntegerParams() { String commandString = "command"; int paramInteger = 1; MPDCommand command = new MPDCommand(commandString, Integer.toString(paramInteger)); commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); List<String> testResponse = new ArrayList<>(); testResponse.add("testResponse"); when(mpdSocket.sendCommand(command)).thenReturn(testResponse); List<String> response = commandExecutor.sendCommand(commandString, paramInteger); verify(mpdSocket).sendCommand(commandCaptor.capture()); assertAll( () -> assertEquals(response.getFirst(), testResponse.get(0)), () -> assertEquals("command", commandCaptor.getAllValues().get(0).getCommand()), () -> assertEquals("1", commandCaptor.getAllValues().get(0).getParams().get(0))); } @Test void testSendCommandSecurityException() { commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); MPDCommand command = new MPDCommand("command"); List<String> testResponse = new ArrayList<>(); testResponse.add("testResponse"); when(mpdSocket.sendCommand(command)) .thenThrow(new MPDSecurityException("exception")) .thenReturn(testResponse); List<String> response = new ArrayList<>(commandExecutor.sendCommand(command)); assertEquals(response.getFirst(), testResponse.getFirst()); } @Test void testSendCommandsSecurityException() { commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); MPDCommand command1 = new MPDCommand("command1"); MPDCommand command2 = new MPDCommand("command2"); List<MPDCommand> commands = new ArrayList<>(); commands.add(command1); commands.add(command2); doThrow(new MPDSecurityException("exception")) .doNothing() .when(mpdSocket) .sendCommands(commands); assertDoesNotThrow(() -> commandExecutor.sendCommands(commands)); } @Test void testSendCommands() { commandExecutor = new TestMPDCommandExecutor(); commandExecutor.setMpd(mpd); MPDCommand command1 = new MPDCommand("command1"); MPDCommand command2 = new MPDCommand("command2"); List<MPDCommand> commands = new ArrayList<>(); commands.add(command1); commands.add(command2); doNothing().when(mpdSocket).sendCommands(commands); assertDoesNotThrow(() -> commandExecutor.sendCommands(commands)); } @Test void testCreateSocket() throws IOException { try (ServerSocket socket = new ServerSocket(0)) { socket.setReuseAddress(true); int port = socket.getLocalPort(); when(mpd.getAddress()).thenReturn(InetAddress.getLocalHost()); when(mpd.getPort()).thenReturn(port); when(mpd.getTimeout()).thenReturn(5000); new Thread( () -> { try (Socket clientSocket = socket.accept()) { PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(), true); pw.write("OK MPD Version\r\n"); pw.flush(); } catch (IOException e) { e.printStackTrace(); } }) .start(); commandExecutor.setMpd(mpd); assertNotNull(commandExecutor.createSocket()); } } @Test void testCommandObjectNoMPDSet() { commandExecutor = new MPDCommandExecutor(); MPDCommand command = new MPDCommand("command"); assertThrows(MPDConnectionException.class, () -> commandExecutor.sendCommand(command)); } @Test void testCommandStringParamsNoMPDSet() { commandExecutor = new MPDCommandExecutor(); assertThrows( MPDConnectionException.class, () -> commandExecutor.sendCommand("command", "param1", "param2")); } @Test void testCommandStringIntegerParamsNoMPDSet() { commandExecutor = new MPDCommandExecutor(); assertThrows( MPDConnectionException.class, () -> commandExecutor.sendCommand("command", 1, 2, 3)); } @Test void testGetVersionNoMPDSet() { commandExecutor = new MPDCommandExecutor(); assertThrows(MPDConnectionException.class, () -> commandExecutor.getMPDVersion()); } @Test void testSendCommandsNoMPDSet() { commandExecutor = new MPDCommandExecutor(); List<MPDCommand> commands = new ArrayList<>(); commands.add(new MPDCommand("command1")); commands.add(new MPDCommand("command2")); commands.add(new MPDCommand("command3")); assertThrows(MPDConnectionException.class, () -> commandExecutor.sendCommands(commands)); } @Test void testAuthenticateIllegalArgument() { assertThrows(IllegalArgumentException.class, () -> commandExecutor.usePassword(null)); } @Test void testAuthentication() { String password = "password"; ServerProperties serverProperties = new ServerProperties(); MPDCommand command = new MPDCommand(serverProperties.getPassword(), password); List<String> testResponse = new ArrayList<>(); testResponse.add("testResponse"); when(mpdSocket.sendCommand(command)).thenReturn(testResponse); commandExecutor.usePassword(password); assertDoesNotThrow(() -> commandExecutor.authenticate()); } @Test void testAuthenticateSecurityException() { String password = "password"; ServerProperties serverProperties = new ServerProperties(); MPDCommand command = new MPDCommand(serverProperties.getPassword(), password); when(mpdSocket.sendCommand(command)).thenThrow(new RuntimeException("incorrect password")); commandExecutor.usePassword(password); assertThrows(MPDSecurityException.class, () -> commandExecutor.authenticate()); } @Test void testAuthenticateGeneralException() { String password = "password"; ServerProperties serverProperties = new ServerProperties(); MPDCommand command = new MPDCommand(serverProperties.getPassword(), password); when(mpdSocket.sendCommand(command)).thenThrow(new RuntimeException()); commandExecutor.usePassword(password); assertThrows(MPDConnectionException.class, () -> commandExecutor.authenticate()); } @Test void testClose() { commandExecutor.close(); verify(mpdSocket).close(); } private class TestMPDCommandExecutor extends MPDCommandExecutor { @Override protected MPDSocket createSocket() { return mpdSocket; } } }
12,896
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDArtworkFinderTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/art/MPDArtworkFinderTest.java
package org.bff.javampd.art; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.*; import org.bff.javampd.MPDException; import org.bff.javampd.album.MPDAlbum; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.song.MPDSong; import org.bff.javampd.song.SongDatabase; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDArtworkFinderTest { private ArtworkFinder artworkFinder; @Mock private SongDatabase songDatabase; @BeforeEach void before() { artworkFinder = new MPDArtworkFinder(this.songDatabase); } @Test void findArtist() throws IOException { String[] artistImages = new String[] {"artist200x200.jpg", "artist200x200.png"}; String[] albumImages = new String[] {"album200x200.jpg", "album200x200.png"}; MPDArtist artist = new MPDArtist("artist"); String prefix = decode( new File(this.getClass().getResource("/images/artist/" + artistImages[0]).getFile()) .getParent()) + File.separator; String albumSuffix = "album" + File.separator; List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file(prefix + albumSuffix + "song1").title("song1").build()); songs.add(MPDSong.builder().file(prefix + albumSuffix + "song2").title("song2").build()); when(songDatabase.findArtist(artist)).thenReturn(songs); List<MPDArtwork> artworkList = artworkFinder.find(artist); assertEquals(artistImages.length + albumImages.length, artworkList.size()); Map<String, byte[]> btyeMap = new HashMap<>(); btyeMap.put(artistImages[0], Files.readAllBytes(new File(prefix + artistImages[0]).toPath())); btyeMap.put(artistImages[1], Files.readAllBytes(new File(prefix + artistImages[1]).toPath())); btyeMap.put( albumImages[0], Files.readAllBytes(new File(prefix + albumSuffix + albumImages[0]).toPath())); btyeMap.put( albumImages[1], Files.readAllBytes(new File(prefix + albumSuffix + albumImages[1]).toPath())); Arrays.asList(artistImages) .forEach( image -> { MPDArtwork foundArtwork = artworkList.stream() .filter(artwork -> image.equals(artwork.getName())) .findFirst() .orElse(null); assertEquals(prefix + image, foundArtwork.getPath()); assertTrue( Arrays.equals(btyeMap.get(foundArtwork.getName()), foundArtwork.getBytes())); }); Arrays.asList(albumImages) .forEach( image -> { MPDArtwork foundArtwork = artworkList.stream() .filter(artwork -> image.equals(artwork.getName())) .findFirst() .orElse(null); assertEquals(prefix + albumSuffix + image, foundArtwork.getPath()); assertArrayEquals(btyeMap.get(foundArtwork.getName()), foundArtwork.getBytes()); }); } @Test void findArtistPrefix() throws UnsupportedEncodingException { String[] artistImages = new String[] {"artist200x200.jpg", "artist200x200.png"}; String[] albumImages = new String[] {"album200x200.jpg", "album200x200.png"}; MPDArtist artist = new MPDArtist("artist"); String path = decode( new File(this.getClass().getResource("/images/artist/" + artistImages[0]).getFile()) .getParent()); List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("/album/song1").title("song1").build()); songs.add(MPDSong.builder().file("/album/song2").title("song2").build()); when(songDatabase.findArtist(artist)).thenReturn(songs); List<MPDArtwork> artworkList = artworkFinder.find(artist, path); assertEquals(artistImages.length + albumImages.length, artworkList.size()); Arrays.asList(artistImages) .forEach( image -> { MPDArtwork foundArtwork = artworkList.stream() .filter(artwork -> image.equals(artwork.getName())) .findFirst() .orElse(null); assertNotNull(foundArtwork.getPath()); assertNotNull(foundArtwork.getBytes()); }); Arrays.asList(albumImages) .forEach( image -> { MPDArtwork foundArtwork = artworkList.stream() .filter(artwork -> image.equals(artwork.getName())) .findFirst() .orElse(null); assertNotNull(foundArtwork.getPath()); assertNotNull(foundArtwork.getBytes()); }); } @Test void findArtistBadPath() throws UnsupportedEncodingException { String[] artistImages = new String[] {"artist200x200.png"}; MPDArtist artist = new MPDArtist("artist"); String path1 = decode( new File(this.getClass().getResource("/images/" + artistImages[0]).getFile()) .getParent()); List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file(path1).title("song1").build()); when(songDatabase.findArtist(artist)).thenReturn(songs); List<MPDArtwork> artworkList = artworkFinder.find(artist); assertEquals(0, artworkList.size()); } @Test void findAlbum() throws UnsupportedEncodingException { String[] albumImages = new String[] {"album200x200.jpg", "album200x200.png"}; MPDAlbum album = MPDAlbum.builder("album").artistNames(Collections.singletonList("artist")).build(); String path1 = decode( new File( this.getClass().getResource("/images/artist/album/" + albumImages[0]).getFile()) .getParent()); List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file(path1 + "/song1").title("song1").build()); when(songDatabase.findAlbum(album)).thenReturn(songs); List<MPDArtwork> artworkList = artworkFinder.find(album); assertEquals(albumImages.length, artworkList.size()); Arrays.asList(albumImages) .forEach( image -> { MPDArtwork foundArtwork = artworkList.stream() .filter(artwork -> image.equals(artwork.getName())) .findFirst() .orElse(null); assertNotNull(foundArtwork.getPath()); assertNotNull(foundArtwork.getBytes()); }); } @Test void findAlbumPrefix() throws UnsupportedEncodingException { String[] albumImages = new String[] {"album200x200.jpg", "album200x200.png"}; MPDAlbum album = MPDAlbum.builder("album").artistNames(Collections.singletonList("artist")).build(); String path = decode( new File( this.getClass().getResource("/images/artist/album/" + albumImages[0]).getFile()) .getParent()); List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("/song1").title("song1").build()); when(songDatabase.findAlbum(album)).thenReturn(songs); List<MPDArtwork> artworkList = artworkFinder.find(album, path); assertEquals(albumImages.length, artworkList.size()); Arrays.asList(albumImages) .forEach( image -> { MPDArtwork foundArtwork = artworkList.stream() .filter(artwork -> image.equals(artwork.getName())) .findFirst() .orElse(null); assertNotNull(foundArtwork.getPath()); assertNotNull(foundArtwork.getBytes()); }); } @Test void findPath() throws UnsupportedEncodingException { String[] images = new String[] {"artist200x200.jpg", "artist200x200.png"}; String testImage = decode( new File(this.getClass().getResource("/images/artist/" + images[0]).getFile()) .getParent()); List<MPDArtwork> artworkList = artworkFinder.find(testImage); assertEquals(images.length, artworkList.size()); Arrays.asList(images) .forEach( image -> { MPDArtwork foundArtwork = artworkList.stream() .filter(artwork -> image.equals(artwork.getName())) .findFirst() .orElse(null); assertNotNull(foundArtwork.getPath()); assertNotNull(foundArtwork.getBytes()); }); } @Test void findPathIOException() throws IOException { File testFile = File.createTempFile("test", ".jpg"); testFile.setReadable(false); var parent = testFile.getParent(); assertThrows(MPDException.class, () -> artworkFinder.find(parent)); } @Test void findPathDirectoryIOException() { String javaTempDir = System.getProperty("java.io.tmpdir"); File tempDir = new File( javaTempDir + (javaTempDir.endsWith(File.separator) ? "" : File.separator) + "imageTemp"); tempDir.mkdir(); tempDir.setWritable(true); File testFile = null; try { testFile = File.createTempFile("test", ".jpg", tempDir); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } tempDir.setReadable(false); var parent = testFile.getParent(); assertThrows(MPDException.class, () -> artworkFinder.find(parent)); } @Test void findBadPath() { assertThrows(MPDException.class, () -> artworkFinder.find("bad")); } private String decode(String encodedString) throws UnsupportedEncodingException { return URLDecoder.decode(encodedString, StandardCharsets.UTF_8); } }
10,232
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDArtworkTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/art/MPDArtworkTest.java
package org.bff.javampd.art; import static org.junit.jupiter.api.Assertions.assertEquals; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class MPDArtworkTest { @Test void testGetBytes() { byte[] bytes = {0}; MPDArtwork artwork = MPDArtwork.builder().name("name").path("path").build(); artwork.setBytes(bytes); assertEquals(bytes, artwork.getBytes()); } @Test void equalsContract() { EqualsVerifier.simple().forClass(MPDArtwork.class).verify(); } }
521
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDFileTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/file/MPDFileTest.java
package org.bff.javampd.file; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class MPDFileTest { @Test void testGetPath() { String path = "/path/to/Name"; MPDFile mpdFile = MPDFile.builder(path).build(); mpdFile.setPath(path); assertEquals(path, mpdFile.getPath()); } @Test void testIsDirectory() { MPDFile mpdFile = MPDFile.builder("").build(); mpdFile.setDirectory(false); assertFalse(mpdFile.isDirectory()); } @Test void testToString() { String path = "/path/to/Name"; MPDFile mpdFile = MPDFile.builder(path).build(); mpdFile.setPath(path); assertEquals( "MPDFile(directory=false, path=/path/to/Name, lastModified=null)", mpdFile.toString()); } @Test void equalsContract() { EqualsVerifier.simple().forClass(MPDFile.class).verify(); } }
982
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDFileDatabaseTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/file/MPDFileDatabaseTest.java
package org.bff.javampd.file; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import org.bff.javampd.MPDException; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.database.DatabaseProperties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDFileDatabaseTest { @Mock private DatabaseProperties databaseProperties; @Mock private CommandExecutor commandExecutor; @InjectMocks private MPDFileDatabase fileDatabase; private DatabaseProperties realDatabaseProperties; @BeforeEach void setup() { realDatabaseProperties = new DatabaseProperties(); } @Test void testListRootDirectory() { List<String> response = new ArrayList<>(); response.add("directory: Q"); response.add("Last-Modified: 2015-10-11T22:11:35Z"); prepMockedCommand("", response); List<MPDFile> mpdFiles = new ArrayList<>(fileDatabase.listRootDirectory()); assertEquals(1, mpdFiles.size()); assertEquals("Q", mpdFiles.getFirst().getPath()); assertEquals( LocalDateTime.parse("2015-10-11T22:11:35Z", DateTimeFormatter.ISO_DATE_TIME), mpdFiles.getFirst().getLastModified()); assertTrue(mpdFiles.getFirst().isDirectory()); } @Test void testListDirectory() { String dir = "test"; MPDFile file = MPDFile.builder(dir).build(); file.setDirectory(true); fileDatabase.listDirectory(file); List<String> response = new ArrayList<>(); response.add("directory: Q"); response.add("Last-Modified: 2015-10-11T22:11:35Z"); String listInfoCommand = realDatabaseProperties.getListInfo(); when(databaseProperties.getListInfo()).thenReturn(listInfoCommand); when(commandExecutor.sendCommand(listInfoCommand, dir)).thenReturn(response); List<MPDFile> mpdFiles = new ArrayList<>(fileDatabase.listDirectory(file)); assertEquals(1, mpdFiles.size()); assertEquals("Q", mpdFiles.getFirst().getPath()); assertEquals( LocalDateTime.parse("2015-10-11T22:11:35Z", DateTimeFormatter.ISO_DATE_TIME), mpdFiles.getFirst().getLastModified()); assertTrue(mpdFiles.getFirst().isDirectory()); } @Test void testListDirectoryWithFiles() { String dir = "test"; MPDFile file = MPDFile.builder(dir).build(); file.setDirectory(true); fileDatabase.listDirectory(file); List<String> response = new ArrayList<>(); response.add("file: Q"); response.add("Last-Modified: 2015-10-11T22:11:35Z"); prepMockedCommand(dir, response); List<MPDFile> mpdFiles = new ArrayList<>(fileDatabase.listDirectory(file)); assertEquals(1, mpdFiles.size()); assertEquals("Q", mpdFiles.getFirst().getPath()); assertEquals( LocalDateTime.parse("2015-10-11T22:11:35Z", DateTimeFormatter.ISO_DATE_TIME), mpdFiles.getFirst().getLastModified()); assertFalse(mpdFiles.getFirst().isDirectory()); } @Test void testListDirectoryWithMultipleFilesSize() { String dir = "test"; MPDFile file = MPDFile.builder(dir).build(); file.setDirectory(true); fileDatabase.listDirectory(file); List<String> response = createMultFileResponse(); prepMockedCommand(dir, response); assertEquals(4, new ArrayList<>(fileDatabase.listDirectory(file)).size()); } @Test void testListDirectoryWithMultipleFiles1() { String dir = "test"; MPDFile file = MPDFile.builder(dir).build(); file.setDirectory(true); fileDatabase.listDirectory(file); List<String> response = createMultFileResponse(); prepMockedCommand(dir, response); List<MPDFile> mpdFiles = new ArrayList<>(fileDatabase.listDirectory(file)); assertEquals("Q", mpdFiles.getFirst().getPath()); assertEquals( LocalDateTime.parse("2015-10-11T22:11:35Z", DateTimeFormatter.ISO_DATE_TIME), mpdFiles.getFirst().getLastModified()); assertTrue(mpdFiles.getFirst().isDirectory()); } @Test void testListDirectoryWithMultipleFiles2() { String dir = "test"; MPDFile file = MPDFile.builder(dir).build(); file.setDirectory(true); fileDatabase.listDirectory(file); List<String> response = createMultFileResponse(); prepMockedCommand(dir, response); List<MPDFile> mpdFiles = new ArrayList<>(fileDatabase.listDirectory(file)); assertEquals("R", mpdFiles.get(1).getPath()); assertEquals( LocalDateTime.parse("2015-10-11T22:11:36Z", DateTimeFormatter.ISO_DATE_TIME), mpdFiles.get(1).getLastModified()); assertFalse(mpdFiles.get(1).isDirectory()); } @Test void testListDirectoryWithMultipleFiles3() { String dir = "test"; MPDFile file = MPDFile.builder(dir).build(); file.setDirectory(true); fileDatabase.listDirectory(file); List<String> response = createMultFileResponse(); prepMockedCommand(dir, response); List<MPDFile> mpdFiles = new ArrayList<>(fileDatabase.listDirectory(file)); assertEquals("S", mpdFiles.get(2).getPath()); assertEquals( LocalDateTime.parse("2015-10-11T22:11:37Z", DateTimeFormatter.ISO_DATE_TIME), mpdFiles.get(2).getLastModified()); assertFalse(mpdFiles.get(2).isDirectory()); } @Test void testListDirectoryWithMultipleFiles4() { String dir = "test"; MPDFile file = MPDFile.builder(dir).build(); file.setDirectory(true); fileDatabase.listDirectory(file); List<String> response = createMultFileResponse(); prepMockedCommand(dir, response); List<MPDFile> mpdFiles = new ArrayList<>(fileDatabase.listDirectory(file)); assertEquals("T", mpdFiles.get(3).getPath()); assertEquals( LocalDateTime.parse("2015-10-11T22:11:38Z", DateTimeFormatter.ISO_DATE_TIME), mpdFiles.get(3).getLastModified()); assertTrue(mpdFiles.get(3).isDirectory()); } @Test void testListDirectoryException() { MPDFile file = MPDFile.builder("").build(); file.setDirectory(false); assertThrows(MPDException.class, () -> fileDatabase.listDirectory(file)); } private List<String> createMultFileResponse() { List<String> response = new ArrayList<>(); response.add("directory: Q"); response.add("Last-Modified: 2015-10-11T22:11:35Z"); response.add("file: R"); response.add("Last-Modified: 2015-10-11T22:11:36Z"); response.add("file: S"); response.add("Last-Modified: 2015-10-11T22:11:37Z"); response.add("directory: T"); response.add("Last-Modified: 2015-10-11T22:11:38Z"); return response; } private void prepMockedCommand(String file, List<String> response) { when(databaseProperties.getListInfo()).thenReturn(realDatabaseProperties.getListInfo()); when(commandExecutor.sendCommand(realDatabaseProperties.getListInfo(), file)) .thenReturn(response); } }
7,089
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDOutputTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/output/MPDOutputTest.java
package org.bff.javampd.output; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class MPDOutputTest { @Test void equalsContract() { EqualsVerifier.simple().forClass(MPDOutput.class).verify(); } }
242
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSavedPlaylistTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/MPDSavedPlaylistTest.java
package org.bff.javampd.playlist; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class MPDSavedPlaylistTest { @Test void equalsContract() { EqualsVerifier.simple().forClass(MPDSavedPlaylist.class).verify(); } }
257
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistSongTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/MPDPlaylistSongTest.java
package org.bff.javampd.playlist; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class MPDPlaylistSongTest { @Test void equalsContract() { EqualsVerifier.simple().forClass(MPDSavedPlaylist.class).verify(); } }
256
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistTestGenreAndYear.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/MPDPlaylistTestGenreAndYear.java
package org.bff.javampd.playlist; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.command.MPDCommand; import org.bff.javampd.genre.MPDGenre; import org.bff.javampd.server.ServerStatus; import org.bff.javampd.song.MPDSong; import org.bff.javampd.song.SongConverter; import org.bff.javampd.song.SongDatabase; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDPlaylistTestGenreAndYear { @Mock private SongDatabase songDatabase; @Mock private ServerStatus serverStatus; @Mock private PlaylistProperties playlistProperties; @Mock private CommandExecutor commandExecutor; @Mock private SongConverter songConverter; @Mock private PlaylistSongConverter playlistSongConverter; @InjectMocks private MPDPlaylist playlist; @Captor private ArgumentCaptor<String> stringArgumentCaptor; @Captor private ArgumentCaptor<Integer> integerArgumentCaptor; @Captor private ArgumentCaptor<List<MPDCommand>> commandArgumentCaptor; private PlaylistProperties realPlaylistProperties; @BeforeEach void setup() { realPlaylistProperties = new PlaylistProperties(); } @Test void testInsertGenre() { MPDGenre genre = new MPDGenre("testGenre"); List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("file1").title("testSong1").build()); songs.add(MPDSong.builder().file("file2").title("testSong2").build()); when(songDatabase.findGenre(genre.name())).thenReturn(songs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.insertGenre(genre); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("file1", stringArgumentCaptor.getAllValues().get(1)); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().get(2)); assertEquals("file2", stringArgumentCaptor.getAllValues().get(3)); assertEquals(PlaylistChangeEvent.Event.GENRE_ADDED, changeEvent[0].getEvent()); } @Test void testInsertGenreByName() { String genre = "testGenre"; List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("file1").title("testSong1").build()); songs.add(MPDSong.builder().file("file2").title("testSong2").build()); when(songDatabase.findGenre(genre)).thenReturn(songs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.insertGenre(genre); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("file1", stringArgumentCaptor.getAllValues().get(1)); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().get(2)); assertEquals("file2", stringArgumentCaptor.getAllValues().get(3)); assertEquals(PlaylistChangeEvent.Event.GENRE_ADDED, changeEvent[0].getEvent()); } @Test void testRemoveGenre() { MPDGenre genre = new MPDGenre("testGenre"); var mockedSongs = new ArrayList<MPDPlaylistSong>(); MPDPlaylistSong song1 = MPDPlaylistSong.builder() .file("file1") .title("testSong1") .genre(genre.name()) .id(1) .build(); MPDPlaylistSong song2 = MPDPlaylistSong.builder() .file("file2") .title("testSong1") .genre(genre.name()) .id(2) .build(); MPDPlaylistSong song3 = MPDPlaylistSong.builder().file("file3").title("testSong1").genre("bogus").build(); mockedSongs.add(song1); mockedSongs.add(song2); mockedSongs.add(song3); List<String> response = new ArrayList<>(); response.add("test"); when(commandExecutor.sendCommand(realPlaylistProperties.getInfo())).thenReturn(response); when(playlistSongConverter.convertResponseToSongs(response)).thenReturn(mockedSongs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.removeGenre(genre); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(1)); assertEquals((Integer) song1.getId(), integerArgumentCaptor.getAllValues().getFirst()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(2)); assertEquals((Integer) song2.getId(), integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } @Test void testRemoveGenreByName() { String genre = "testGenre"; var mockedSongs = new ArrayList<MPDPlaylistSong>(); MPDPlaylistSong song1 = MPDPlaylistSong.builder().file("file1").title("testSong1").genre(genre).id(1).build(); MPDPlaylistSong song2 = MPDPlaylistSong.builder().file("file2").title("testSong1").genre(genre).id(2).build(); MPDPlaylistSong song3 = MPDPlaylistSong.builder().file("file3").title("testSong1").genre("bogus").build(); mockedSongs.add(song1); mockedSongs.add(song2); mockedSongs.add(song3); List<String> response = new ArrayList<>(); response.add("test"); when(commandExecutor.sendCommand(realPlaylistProperties.getInfo())).thenReturn(response); when(playlistSongConverter.convertResponseToSongs(response)).thenReturn(mockedSongs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.removeGenre(genre); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(1)); assertEquals((Integer) song1.getId(), integerArgumentCaptor.getAllValues().getFirst()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(2)); assertEquals((Integer) song2.getId(), integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } @Test void testInsertYear() { String year = "testYear"; List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("file1").title("testSong1").build()); songs.add(MPDSong.builder().file("file2").title("testSong2").build()); when(songDatabase.findYear(year)).thenReturn(songs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.insertYear(year); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("file1", stringArgumentCaptor.getAllValues().get(1)); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().get(2)); assertEquals("file2", stringArgumentCaptor.getAllValues().get(3)); assertEquals(PlaylistChangeEvent.Event.YEAR_ADDED, changeEvent[0].getEvent()); } @Test void testRemoveYear() { String year = "testYear"; var mockedSongs = new ArrayList<MPDPlaylistSong>(); MPDPlaylistSong song1 = MPDPlaylistSong.builder().file("file1").title("testSong1").date(year).id(1).build(); MPDPlaylistSong song2 = MPDPlaylistSong.builder().file("file2").title("testSong1").date(year).id(2).build(); MPDPlaylistSong song3 = MPDPlaylistSong.builder().file("file3").title("testSong1").date("bogus").build(); mockedSongs.add(song1); mockedSongs.add(song2); mockedSongs.add(song3); List<String> response = new ArrayList<>(); response.add("test"); when(commandExecutor.sendCommand(realPlaylistProperties.getInfo())).thenReturn(response); when(playlistSongConverter.convertResponseToSongs(response)).thenReturn(mockedSongs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.removeYear(year); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(1)); assertEquals((Integer) song1.getId(), integerArgumentCaptor.getAllValues().getFirst()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(2)); assertEquals((Integer) song2.getId(), integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } }
9,943
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlaylistPropertiesTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/PlaylistPropertiesTest.java
package org.bff.javampd.playlist; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class PlaylistPropertiesTest { private PlaylistProperties playlistProperties; @BeforeEach void setUp() { playlistProperties = new PlaylistProperties(); } @Test void getAdd() { assertEquals("add", playlistProperties.getAdd()); } @Test void getClear() { assertEquals("clear", playlistProperties.getClear()); } @Test void getCurrentSong() { assertEquals("currentsong", playlistProperties.getCurrentSong()); } @Test void getDelete() { assertEquals("rm", playlistProperties.getDelete()); } @Test void getChanges() { assertEquals("plchanges", playlistProperties.getChanges()); } @Test void getId() { assertEquals("playlistid", playlistProperties.getId()); } @Test void getInfo() { assertEquals("playlistinfo", playlistProperties.getInfo()); } @Test void getLoad() { assertEquals("load", playlistProperties.getLoad()); } @Test void getMove() { assertEquals("move", playlistProperties.getMove()); } @Test void getMoveId() { assertEquals("moveid", playlistProperties.getMoveId()); } @Test void getRemove() { assertEquals("delete", playlistProperties.getRemove()); } @Test void getRemoveId() { assertEquals("deleteid", playlistProperties.getRemoveId()); } @Test void getSave() { assertEquals("save", playlistProperties.getSave()); } @Test void getShuffle() { assertEquals("shuffle", playlistProperties.getShuffle()); } @Test void getSwap() { assertEquals("swap", playlistProperties.getSwap()); } @Test void getSwapId() { assertEquals("swapid", playlistProperties.getSwapId()); } }
1,834
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistTestSong.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/MPDPlaylistTestSong.java
package org.bff.javampd.playlist; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.command.MPDCommand; import org.bff.javampd.server.ServerStatus; import org.bff.javampd.song.MPDSong; import org.bff.javampd.song.SongDatabase; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDPlaylistTestSong { @Mock private SongDatabase songDatabase; @Mock private ServerStatus serverStatus; @Mock private PlaylistProperties playlistProperties; @Mock private CommandExecutor commandExecutor; @Mock private PlaylistSongConverter songConverter; @InjectMocks private MPDPlaylist playlist; @Captor private ArgumentCaptor<String> stringArgumentCaptor; @Captor private ArgumentCaptor<Integer> integerArgumentCaptor; @Captor private ArgumentCaptor<List<MPDCommand>> commandArgumentCaptor; private PlaylistProperties realPlaylistProperties; @BeforeEach void setup() { realPlaylistProperties = new PlaylistProperties(); } @Test void testAddSong() { when(serverStatus.getPlaylistVersion()).thenReturn(1); MPDSong mpdSong = MPDSong.builder().file("test").title("test").build(); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.addSong(mpdSong); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals(mpdSong.getFile(), stringArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.SONG_ADDED, changeEvent[0].getEvent()); assertEquals(mpdSong.getFile(), changeEvent[0].getName()); } @Test void testAddSongNoEvent() { when(serverStatus.getPlaylistVersion()).thenReturn(-1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.addSong(MPDSong.builder().file("test").title("test").build(), false); assertNull(changeEvent[0]); } @Test void testAddSongFile() { when(serverStatus.getPlaylistVersion()).thenReturn(1); MPDSong mpdSong = MPDSong.builder().file("testFile").title("test").build(); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.addSong(mpdSong.getFile()); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals(mpdSong.getFile(), stringArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.SONG_ADDED, changeEvent[0].getEvent()); assertEquals(mpdSong.getFile(), changeEvent[0].getName()); } @Test void testAddSongFileNoEvent() { when(serverStatus.getPlaylistVersion()).thenReturn(-1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.addSong("testFile", false); assertNull(changeEvent[0]); } @Test void testAddSongs() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("test1").title("test1").build()); songs.add(MPDSong.builder().file("test2").title("test2").build()); playlist.addSongs(songs); verify(commandExecutor).sendCommands(commandArgumentCaptor.capture()); assertEquals( realPlaylistProperties.getAdd(), commandArgumentCaptor.getAllValues().getFirst().getFirst().getCommand()); assertEquals( "test1", commandArgumentCaptor.getAllValues().getFirst().getFirst().getParams().getFirst()); assertEquals( realPlaylistProperties.getAdd(), commandArgumentCaptor.getAllValues().getFirst().get(1).getCommand()); assertEquals( "test2", commandArgumentCaptor.getAllValues().getFirst().get(1).getParams().getFirst()); assertEquals(PlaylistChangeEvent.Event.MULTIPLE_SONGS_ADDED, changeEvent[0].getEvent()); } @Test void testAddSongsNoEvent() { when(serverStatus.getPlaylistVersion()).thenReturn(-1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.addSong(MPDSong.builder().file("test").title("test").build(), false); assertNull(changeEvent[0]); } @Test void testRemoveSong() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); var mpdSong = MPDPlaylistSong.builder().position(5).file("test").title("test").build(); playlist.removeSong(mpdSong); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemove(), stringArgumentCaptor.getValue()); assertEquals((Integer) 5, integerArgumentCaptor.getValue()); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } @Test void testRemoveSongByPosition() { when(serverStatus.getPlaylistVersion()).thenReturn(1); int position = 5; final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); MPDPlaylistSong mpdSong = MPDPlaylistSong.builder().position(position).build(); playlist.removeSong(position); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemove(), stringArgumentCaptor.getValue()); assertEquals((Integer) position, integerArgumentCaptor.getValue()); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } @Test void testRemoveSongByBadPosition() { int position = -1; final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); MPDPlaylistSong mpdSong = MPDPlaylistSong.builder().position(position).build(); playlist.removeSong(position); assertNull(changeEvent[0]); } @Test void testRemoveSongById() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); MPDPlaylistSong song = MPDPlaylistSong.builder().id(5).build(); playlist.removeSong(song); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getValue()); assertEquals((Integer) 5, integerArgumentCaptor.getValue()); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } @Test void getCurrentSongCommand() { when(commandExecutor.sendCommand(realPlaylistProperties.getCurrentSong())) .thenReturn(new ArrayList<>()); when(songConverter.convertResponseToSongs(any())).thenReturn(new ArrayList<>()); playlist.getCurrentSong(); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getCurrentSong(), stringArgumentCaptor.getValue()); } @Test void getCurrentSongConversion() { List<String> response = new ArrayList<>(); response.add("test"); when(commandExecutor.sendCommand(realPlaylistProperties.getCurrentSong())).thenReturn(response); List<MPDPlaylistSong> songs = new ArrayList<>(); songs.add(MPDPlaylistSong.builder().name("Sober").build()); when(songConverter.convertResponseToSongs(response)).thenReturn(songs); assertEquals("Sober", playlist.getCurrentSong().getName()); } @Test void testListSongs() { List<MPDPlaylistSong> mockedSongs = new ArrayList<>(); mockedSongs.add(MPDPlaylistSong.builder().file("test1").title("testSong1").build()); mockedSongs.add(MPDPlaylistSong.builder().file("test2").title("testSong2").build()); List<String> response = new ArrayList<>(); response.add("test"); when(commandExecutor.sendCommand(realPlaylistProperties.getInfo())).thenReturn(response); when(songConverter.convertResponseToSongs(response)).thenReturn(mockedSongs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); List<MPDPlaylistSong> songs = playlist.getSongList(); assertEquals(mockedSongs.size(), songs.size()); assertEquals(mockedSongs.getFirst(), songs.getFirst()); assertEquals(mockedSongs.get(1), songs.get(1)); } }
9,755
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/MPDPlaylistTest.java
package org.bff.javampd.playlist; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.List; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.command.MPDCommand; import org.bff.javampd.file.MPDFile; import org.bff.javampd.server.ServerStatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDPlaylistTest { @Mock private ServerStatus serverStatus; @Mock private PlaylistProperties playlistProperties; @Mock private CommandExecutor commandExecutor; @InjectMocks private MPDPlaylist playlist; @Captor private ArgumentCaptor<String> stringArgumentCaptor; @Captor private ArgumentCaptor<Integer> integerArgumentCaptor; @Captor private ArgumentCaptor<List<MPDCommand>> commandArgumentCaptor; private PlaylistProperties realPlaylistProperties; @BeforeEach void setup() { realPlaylistProperties = new PlaylistProperties(); } @Test void testAddPlaylistChangeListener() { final boolean[] gotEvent = {true}; playlist.addPlaylistChangeListener(event -> gotEvent[0] = true); playlist.firePlaylistChangeEvent(PlaylistChangeEvent.Event.ARTIST_ADDED); assertTrue(gotEvent[0]); } @Test void testRemovePlaylistStatusChangedListener() { final boolean[] gotEvent = {true}; PlaylistChangeListener pcl = event -> gotEvent[0] = true; playlist.addPlaylistChangeListener(pcl); playlist.firePlaylistChangeEvent(PlaylistChangeEvent.Event.ARTIST_ADDED); assertTrue(gotEvent[0]); gotEvent[0] = false; playlist.removePlaylistStatusChangedListener(pcl); playlist.firePlaylistChangeEvent(PlaylistChangeEvent.Event.ARTIST_ADDED); assertFalse(gotEvent[0]); } @Test void testFirePlaylistChangeEvent() { final boolean[] gotEvent = {true}; playlist.addPlaylistChangeListener(event -> gotEvent[0] = true); playlist.firePlaylistChangeEvent(PlaylistChangeEvent.Event.ALBUM_ADDED); assertTrue(gotEvent[0]); } @Test void testFirePlaylistChangeEventSongAdded() { final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.firePlaylistChangeEvent(PlaylistChangeEvent.Event.SONG_ADDED, "name"); assertEquals("name", changeEvent[0].getName()); } @Test void testLoadPlaylist() { String testPlaylist = "testPlaylist"; when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.loadPlaylist(testPlaylist); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getLoad(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("testPlaylist", stringArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0].getEvent()); } @Test void testLoadPlaylistM3u() { String testPlaylist = "testPlaylist.m3u"; when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.loadPlaylist(testPlaylist); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getLoad(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("testPlaylist", stringArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0].getEvent()); } @Test void testAddFileOrDirectory() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.addFileOrDirectory(MPDFile.builder("test").build()); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("test", stringArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.FILE_ADDED, changeEvent[0].getEvent()); } @Test void testClearPlaylist() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.clearPlaylist(); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getClear(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_CLEARED, changeEvent[0].getEvent()); } @Test void testDeletePlaylist() { final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); MPDSavedPlaylist savedPlaylist = MPDSavedPlaylist.builder("testPlaylist").build(); playlist.deletePlaylist(savedPlaylist); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals( realPlaylistProperties.getDelete(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("testPlaylist", stringArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_DELETED, changeEvent[0].getEvent()); } @Test void testDeletePlaylistByName() { final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.deletePlaylist("testPlaylist"); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals( realPlaylistProperties.getDelete(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("testPlaylist", stringArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_DELETED, changeEvent[0].getEvent()); } @Test void testMoveById() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); MPDPlaylistSong song = MPDPlaylistSong.builder().file("test").title("test").id(3).build(); playlist.move(song, 5); verify(commandExecutor) .sendCommand( stringArgumentCaptor.capture(), integerArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getMoveId(), stringArgumentCaptor.getValue()); assertEquals((Integer) 3, integerArgumentCaptor.getAllValues().getFirst()); assertEquals((Integer) 5, integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0].getEvent()); } @Test void testMoveByPosition() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); MPDPlaylistSong song = MPDPlaylistSong.builder().file("test").title("test").position(3).build(); playlist.move(song, 5); verify(commandExecutor) .sendCommand( stringArgumentCaptor.capture(), integerArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getMove(), stringArgumentCaptor.getValue()); assertEquals((Integer) 3, integerArgumentCaptor.getAllValues().getFirst()); assertEquals((Integer) 5, integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0].getEvent()); } @Test void testShuffle() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.shuffle(); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getShuffle(), stringArgumentCaptor.getValue()); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0].getEvent()); } @Test void testSwapByExplicitId() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); MPDPlaylistSong song1 = MPDPlaylistSong.builder().file("test").title("test").id(3).build(); playlist.swap(song1, 5); verify(commandExecutor) .sendCommand( stringArgumentCaptor.capture(), integerArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getSwapId(), stringArgumentCaptor.getValue()); assertEquals((Integer) 3, integerArgumentCaptor.getAllValues().getFirst()); assertEquals((Integer) 5, integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0].getEvent()); } @Test void testSwapById() { when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); MPDPlaylistSong song1 = MPDPlaylistSong.builder().file("test").title("test").id(3).build(); MPDPlaylistSong song2 = MPDPlaylistSong.builder().file("test").title("test").id(5).build(); playlist.swap(song1, song2); verify(commandExecutor) .sendCommand( stringArgumentCaptor.capture(), integerArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getSwapId(), stringArgumentCaptor.getValue()); assertEquals((Integer) 3, integerArgumentCaptor.getAllValues().getFirst()); assertEquals((Integer) 5, integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0].getEvent()); } @Test void testSwapByPosition() { final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); MPDPlaylistSong song1 = MPDPlaylistSong.builder().file("test").title("test").position(3).build(); MPDPlaylistSong song2 = MPDPlaylistSong.builder().file("test").title("test").position(5).build(); playlist.swap(song1, song2); verify(commandExecutor) .sendCommand( stringArgumentCaptor.capture(), integerArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getSwap(), stringArgumentCaptor.getValue()); assertEquals((Integer) 3, integerArgumentCaptor.getAllValues().getFirst()); assertEquals((Integer) 5, integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_CHANGED, changeEvent[0].getEvent()); } @Test void testPlaylistSave() { final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); boolean saved = playlist.savePlaylist("name"); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertTrue(saved); assertEquals(realPlaylistProperties.getSave(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("name", stringArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.PLAYLIST_SAVED, changeEvent[0].getEvent()); } @Test void testPlaylistSaveNull() { final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); boolean saved = playlist.savePlaylist(null); assertFalse(saved); assertNull(changeEvent[0]); } }
12,753
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistTestAlbum.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/MPDPlaylistTestAlbum.java
package org.bff.javampd.playlist; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.bff.javampd.album.MPDAlbum; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.command.MPDCommand; import org.bff.javampd.server.ServerStatus; import org.bff.javampd.song.MPDSong; import org.bff.javampd.song.SongConverter; import org.bff.javampd.song.SongDatabase; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDPlaylistTestAlbum { @Mock private SongDatabase songDatabase; @Mock private ServerStatus serverStatus; @Mock private PlaylistProperties playlistProperties; @Mock private CommandExecutor commandExecutor; @Mock private SongConverter songConverter; @Mock private PlaylistSongConverter playlistSongConverter; @InjectMocks private MPDPlaylist playlist; @Captor private ArgumentCaptor<String> stringArgumentCaptor; @Captor private ArgumentCaptor<Integer> integerArgumentCaptor; @Captor private ArgumentCaptor<List<MPDCommand>> commandArgumentCaptor; private PlaylistProperties realPlaylistProperties; @BeforeEach void setup() { realPlaylistProperties = new PlaylistProperties(); } @Test void testInsertAlbumByArtist() { MPDArtist artist = new MPDArtist("testArtist"); MPDAlbum album = MPDAlbum.builder("testAlbum").artistNames(Collections.singletonList("testArtist")).build(); List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("file1").title("testSong1").build()); songs.add(MPDSong.builder().file("file2").title("testSong2").build()); when(songDatabase.findAlbumByArtist(artist, album)).thenReturn(songs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.insertAlbum(artist, album); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("file1", stringArgumentCaptor.getAllValues().get(1)); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().get(2)); assertEquals("file2", stringArgumentCaptor.getAllValues().get(3)); assertEquals(PlaylistChangeEvent.Event.ALBUM_ADDED, changeEvent[0].getEvent()); } @Test void testInsertAlbumByNames() { String artist = "testArtist"; String album = "testAlbum"; List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("file1").title("testSong1").build()); songs.add(MPDSong.builder().file("file2").title("testSong2").build()); when(songDatabase.findAlbumByArtist(artist, album)).thenReturn(songs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.insertAlbum(artist, album); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("file1", stringArgumentCaptor.getAllValues().get(1)); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().get(2)); assertEquals("file2", stringArgumentCaptor.getAllValues().get(3)); assertEquals(PlaylistChangeEvent.Event.ALBUM_ADDED, changeEvent[0].getEvent()); } @Test void testInsertAlbumByName() { String album = "testAlbum"; List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("file1").title("testSong1").build()); songs.add(MPDSong.builder().file("file2").title("testSong2").build()); when(songDatabase.findAlbum(album)).thenReturn(songs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.insertAlbum(album); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("file1", stringArgumentCaptor.getAllValues().get(1)); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().get(2)); assertEquals("file2", stringArgumentCaptor.getAllValues().get(3)); assertEquals(PlaylistChangeEvent.Event.ALBUM_ADDED, changeEvent[0].getEvent()); } @Test void testInsertAlbumByAlbum() { MPDAlbum album = MPDAlbum.builder("testAlbum").artistNames(Collections.singletonList("testArtist")).build(); List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("file1").title("testSong1").build()); songs.add(MPDSong.builder().file("file2").title("testSong2").build()); when(songDatabase.findAlbum(album)).thenReturn(songs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.insertAlbum(album); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("file1", stringArgumentCaptor.getAllValues().get(1)); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().get(2)); assertEquals("file2", stringArgumentCaptor.getAllValues().get(3)); assertEquals(PlaylistChangeEvent.Event.ALBUM_ADDED, changeEvent[0].getEvent()); } @Test void testRemoveAlbumByArtist() { MPDArtist artist = new MPDArtist("testArtist"); MPDAlbum album = MPDAlbum.builder("testAlbum").artistNames(Collections.singletonList("testArtist")).build(); var mockedSongs = new ArrayList<MPDPlaylistSong>(); MPDPlaylistSong song1 = MPDPlaylistSong.builder() .file("file1") .title("testSong1") .artistName(artist.name()) .albumName(album.getName()) .id(1) .build(); MPDPlaylistSong song2 = MPDPlaylistSong.builder() .file("file1") .title("testSong1") .artistName(artist.name()) .albumName(album.getName()) .id(2) .build(); MPDPlaylistSong song3 = MPDPlaylistSong.builder() .file("file1") .title("testSong1") .artistName("bogus") .albumName("bogus") .id(1) .build(); mockedSongs.add(song1); mockedSongs.add(song2); mockedSongs.add(song3); List<String> response = new ArrayList<>(); response.add("test"); when(commandExecutor.sendCommand(realPlaylistProperties.getInfo())).thenReturn(response); when(playlistSongConverter.convertResponseToSongs(response)).thenReturn(mockedSongs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.removeAlbum(artist, album); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(1)); assertEquals((Integer) song1.getId(), integerArgumentCaptor.getAllValues().getFirst()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(2)); assertEquals((Integer) song2.getId(), integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } @Test void testRemoveAlbumByName() { String artist = "testArtist"; String album = "testAlbum"; var mockedSongs = new ArrayList<MPDPlaylistSong>(); MPDPlaylistSong song1 = MPDPlaylistSong.builder() .file("file1") .title("testSong1") .artistName(artist) .albumName(album) .id(1) .build(); MPDPlaylistSong song2 = MPDPlaylistSong.builder() .file("file1") .title("testSong1") .artistName(artist) .albumName(album) .id(2) .build(); MPDPlaylistSong song3 = MPDPlaylistSong.builder() .file("file1") .title("testSong1") .artistName("bogus") .albumName("bogus") .id(1) .build(); mockedSongs.add(song1); mockedSongs.add(song2); mockedSongs.add(song3); List<String> response = new ArrayList<>(); response.add("test"); when(commandExecutor.sendCommand(realPlaylistProperties.getInfo())).thenReturn(response); when(playlistSongConverter.convertResponseToSongs(response)).thenReturn(mockedSongs); when(serverStatus.getPlaylistVersion()).thenReturn(1); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.removeAlbum(artist, album); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(1)); assertEquals((Integer) song1.getId(), integerArgumentCaptor.getAllValues().getFirst()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(2)); assertEquals((Integer) song2.getId(), integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } }
10,457
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistSongConverterTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/MPDPlaylistSongConverterTest.java
package org.bff.javampd.playlist; import static org.junit.jupiter.api.Assertions.*; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class MPDPlaylistSongConverterTest { private PlaylistSongConverter playlistSongConverter; @BeforeEach void setUp() { playlistSongConverter = new MPDPlaylistSongConverter(); } @Test void defaults() { var s = playlistSongConverter .convertResponseToSongs(List.of("file: Tool/10,000 Days/01 Vicarious.flac")) .getFirst(); assertAll( () -> assertEquals(-1, s.getId()), () -> assertEquals(-1, s.getPosition()), () -> assertNull(s.getArtistName()), () -> assertNull(s.getAlbumArtist()), () -> assertNull(s.getAlbumName()), () -> assertNull(s.getTrack()), () -> assertNull(s.getName()), () -> assertNull(s.getTitle()), () -> assertNull(s.getDate()), () -> assertNull(s.getGenre()), () -> assertNull(s.getComment()), () -> assertEquals(-1, s.getLength()), () -> assertNull(s.getDiscNumber()), () -> assertEquals("Tool/10,000 Days/01 Vicarious.flac", s.getFile())); } @Test void multiple() { var s = playlistSongConverter.convertResponseToSongs(multipleResponse()); assertEquals(2, s.size()); } @Test void badId() { var s = playlistSongConverter .convertResponseToSongs( Arrays.asList("file: Tool/10,000 Days/01 Vicarious.flac", "id: unparseable")) .getFirst(); assertEquals(-1, s.getId()); } @Test void badPosition() { var s = playlistSongConverter .convertResponseToSongs( Arrays.asList("file: Tool/10,000 Days/01 Vicarious.flac", "id: unparseable")) .getFirst(); assertEquals(-1, s.getPosition()); } private List<String> multipleResponse() { return Arrays.asList( "file: Tool/Undertow/03-Sober.flac", "Last-Modified: 2022-02-19T12:52:00Z", "MUSICBRAINZ_RELEASETRACKID: a519bd9b-1301-3d15-acbe-34ef764c5de3", "MUSICBRAINZ_WORKID: e8b1d47b-2657-3e97-a706-cac4e7d2e3cb", "Album: Undertow", "AlbumArtist: Tool", "AlbumArtistSort: Tool", "Artist: Tool", "ArtistSort: Tool", "Disc: 1", "Disc: 1", "Genre: Hard Rock", "Label: Volcano Records", "MUSICBRAINZ_ALBUMARTISTID: 66fc5bf8-daa4-4241-b378-9bc9077939d2", "MUSICBRAINZ_ALBUMID: e4a9bee3-fa02-3dc3-85f6-8042062d9a5f", "MUSICBRAINZ_ARTISTID: 66fc5bf8-daa4-4241-b378-9bc9077939d2", "MUSICBRAINZ_TRACKID: 54db4149-862c-49c9-9224-be1314d57780", "OriginalDate: 1993-04-06", "Title: Sober", "Date: 1993", "Track: 3", "Time: 307", "duration: 306.733", "Pos: 0", "Id: 67", "file: Spiritbox/Eternal Blue/11-Circle With Me.mp3", "Last-Modified: 2022-02-19T12:51:00Z", "Artist: Spiritbox", "AlbumArtist: Spiritbox", "ArtistSort: Spiritbox", "AlbumArtistSort: Spiritbox", "AlbumArtistSort: Spiritbox", "Title: Circle With Me", "Album: Eternal Blue", "Track: 11", "Date: 2021", "OriginalDate: 2021-09-17", "Genre: Metal", "Composer: Daniel Braunstein, Bill Crook, Michael Stringer", "Disc: 1", "Label: Rise Records", "MUSICBRAINZ_ALBUMID: 312248cc-12a5-46f4-8f9c-893df55deccf", "MUSICBRAINZ_ARTISTID: 9c935736-7530-41e4-b776-1dbcf534c061", "MUSICBRAINZ_ALBUMARTISTID: 9c935736-7530-41e4-b776-1dbcf534c061", "MUSICBRAINZ_RELEASETRACKID: a04d27df-9213-4c53-a481-3f4eba397b93", "MUSICBRAINZ_TRACKID: 5d74244a-d193-44e6-a78c-28446abf2904", "Time: 234", "duration: 233.926", "Pos: 1", "Id: 68", "OK"); } }
3,971
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistTestArtist.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/MPDPlaylistTestArtist.java
package org.bff.javampd.playlist; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.command.MPDCommand; import org.bff.javampd.server.ServerStatus; import org.bff.javampd.song.MPDSong; import org.bff.javampd.song.SongConverter; import org.bff.javampd.song.SongDatabase; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDPlaylistTestArtist { @Mock private SongDatabase songDatabase; @Mock private ServerStatus serverStatus; @Mock private PlaylistProperties playlistProperties; @Mock private CommandExecutor commandExecutor; @Mock private SongConverter songConverter; @Mock private PlaylistSongConverter playlistSongConverter; @InjectMocks private MPDPlaylist playlist; @Captor private ArgumentCaptor<String> stringArgumentCaptor; @Captor private ArgumentCaptor<Integer> integerArgumentCaptor; @Captor private ArgumentCaptor<List<MPDCommand>> commandArgumentCaptor; private PlaylistProperties realPlaylistProperties; @BeforeEach void setup() { realPlaylistProperties = new PlaylistProperties(); } @Test void testRemoveArtist() { MPDArtist artist = new MPDArtist("testArtist"); List<MPDPlaylistSong> mockedSongs = new ArrayList<>(); MPDPlaylistSong song1 = MPDPlaylistSong.builder() .file("file1") .title("testSong1") .artistName(artist.name()) .id(1) .build(); MPDPlaylistSong song2 = MPDPlaylistSong.builder() .file("file2") .title("testSong1") .artistName(artist.name()) .id(2) .build(); MPDPlaylistSong song3 = MPDPlaylistSong.builder() .file("file3") .title("testSong1") .artistName("bogus") .albumName("bogus") .build(); mockedSongs.add(song1); mockedSongs.add(song2); mockedSongs.add(song3); List<String> response = new ArrayList<>(); response.add("test"); when(commandExecutor.sendCommand(realPlaylistProperties.getInfo())).thenReturn(response); when(playlistSongConverter.convertResponseToSongs(response)).thenReturn(mockedSongs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.removeArtist(artist); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(1)); assertEquals((Integer) song1.getId(), integerArgumentCaptor.getAllValues().getFirst()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(2)); assertEquals((Integer) song2.getId(), integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } @Test void testRemoveArtistByName() { String artist = "testArtist"; List<MPDPlaylistSong> mockedSongs = new ArrayList<>(); MPDPlaylistSong song1 = MPDPlaylistSong.builder().file("file1").title("testSong1").artistName(artist).id(1).build(); MPDPlaylistSong song2 = MPDPlaylistSong.builder().file("file2").title("testSong1").artistName(artist).id(2).build(); MPDPlaylistSong song3 = MPDPlaylistSong.builder() .file("file3") .title("testSong1") .artistName("bogus") .albumName("bogus") .build(); mockedSongs.add(song1); mockedSongs.add(song2); mockedSongs.add(song3); List<String> response = new ArrayList<>(); response.add("test"); when(commandExecutor.sendCommand(realPlaylistProperties.getInfo())).thenReturn(response); when(playlistSongConverter.convertResponseToSongs(response)).thenReturn(mockedSongs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.removeArtist(artist); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(1)); assertEquals((Integer) song1.getId(), integerArgumentCaptor.getAllValues().getFirst()); assertEquals(realPlaylistProperties.getRemoveId(), stringArgumentCaptor.getAllValues().get(2)); assertEquals((Integer) song2.getId(), integerArgumentCaptor.getAllValues().get(1)); assertEquals(PlaylistChangeEvent.Event.SONG_DELETED, changeEvent[0].getEvent()); } @Test void testInsertArtist() { MPDArtist artist = new MPDArtist("testArtist"); List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("file1").title("testSong1").build()); songs.add(MPDSong.builder().file("file2").title("testSong2").build()); when(songDatabase.findArtist(artist.name())).thenReturn(songs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.insertArtist(artist); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()); assertEquals("file1", stringArgumentCaptor.getAllValues().get(1)); assertEquals(realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().get(2)); assertEquals("file2", stringArgumentCaptor.getAllValues().get(3)); assertEquals(PlaylistChangeEvent.Event.ARTIST_ADDED, changeEvent[0].getEvent()); } @Test void testInsertArtistByName() { String artist = "testArtist"; List<MPDSong> songs = new ArrayList<>(); songs.add(MPDSong.builder().file("file1").title("testSong1").build()); songs.add(MPDSong.builder().file("file2").title("testSong2").build()); when(songDatabase.findArtist(artist)).thenReturn(songs); final PlaylistChangeEvent[] changeEvent = new PlaylistChangeEvent[1]; playlist.addPlaylistChangeListener(event -> changeEvent[0] = event); playlist.insertArtist(artist); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertAll( () -> assertEquals( realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().getFirst()), () -> assertEquals("file1", stringArgumentCaptor.getAllValues().get(1)), () -> assertEquals( realPlaylistProperties.getAdd(), stringArgumentCaptor.getAllValues().get(2)), () -> assertEquals("file2", stringArgumentCaptor.getAllValues().get(3)), () -> assertEquals(PlaylistChangeEvent.Event.ARTIST_ADDED, changeEvent[0].getEvent())); } }
7,636
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistDatabaseTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/playlist/MPDPlaylistDatabaseTest.java
package org.bff.javampd.playlist; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.database.DatabaseProperties; import org.bff.javampd.database.TagLister; import org.bff.javampd.song.MPDSong; import org.bff.javampd.song.SongConverter; import org.bff.javampd.song.SongDatabase; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDPlaylistDatabaseTest { @Mock private SongDatabase songDatabase; @Mock private CommandExecutor commandExecutor; @Mock private DatabaseProperties databaseProperties; @Mock private TagLister tagLister; @Mock private SongConverter songConverter; @InjectMocks private MPDPlaylistDatabase playlistDatabase; @Test void testListSavedPlaylists() { String testPlaylistName1 = "testName1"; String testPlaylistName2 = "testName2"; List<String> mockedResponseList = new ArrayList<>(); mockedResponseList.add(testPlaylistName1); mockedResponseList.add(testPlaylistName2); List<MPDSavedPlaylist> mockList = new ArrayList<>(); MPDSavedPlaylist mockedSavedPlaylist1 = MPDSavedPlaylist.builder(testPlaylistName1).build(); mockList.add(mockedSavedPlaylist1); MPDSavedPlaylist mockedSavedPlaylist2 = MPDSavedPlaylist.builder(testPlaylistName2).build(); mockList.add(mockedSavedPlaylist2); when(tagLister.listInfo(TagLister.ListInfoType.PLAYLIST)).thenReturn(mockedResponseList); List<MPDSavedPlaylist> playlists = new ArrayList<>(playlistDatabase.listSavedPlaylists()); assertEquals(testPlaylistName1, playlists.getFirst().getName()); assertEquals(testPlaylistName2, playlists.get(1).getName()); } @Test void testListSavedPlaylistsSongs() { String testPlaylistName1 = "testName1"; String testPlaylistName2 = "testName2"; String testSongName1 = "testSong1"; String testSongName2 = "testSong2"; List<String> mockedResponseList = new ArrayList<>(); mockedResponseList.add(testPlaylistName1); mockedResponseList.add(testPlaylistName2); when(tagLister.listInfo(TagLister.ListInfoType.PLAYLIST)).thenReturn(mockedResponseList); List<MPDSong> mockedSongs1 = new ArrayList<>(); mockedSongs1.add(MPDSong.builder().file("file1").title(testSongName1).build()); List<MPDSong> mockedSongs2 = new ArrayList<>(); mockedSongs2.add(MPDSong.builder().file("file2").title(testSongName2).build()); when(databaseProperties.getListSongs()).thenReturn("listplaylist"); when(commandExecutor.sendCommand("listplaylist", testPlaylistName1)) .thenReturn(mockedResponseList); when(commandExecutor.sendCommand("listplaylist", testPlaylistName2)) .thenReturn(mockedResponseList); when(songConverter.getSongFileNameList(mockedResponseList)).thenReturn(mockedResponseList); when(songDatabase.searchFileName(testPlaylistName1)).thenReturn(mockedSongs1); when(songDatabase.searchFileName(testPlaylistName2)).thenReturn(mockedSongs2); List<MPDSavedPlaylist> playlists = new ArrayList<>(playlistDatabase.listSavedPlaylists()); playlists.forEach( playlist -> { List<MPDSong> playlistSongs = new ArrayList<>(playlist.getSongs()); assertEquals(testSongName1, playlistSongs.getFirst().getName()); assertEquals(testSongName2, playlistSongs.get(1).getName()); }); } @Test void testListPlaylists() { String testPlaylist = "testPlaylist"; List<String> mockList = new ArrayList<>(); mockList.add(testPlaylist); when(tagLister.listInfo(TagLister.ListInfoType.PLAYLIST)).thenReturn(mockList); List<String> playlists = new ArrayList<>(playlistDatabase.listPlaylists()); assertEquals(testPlaylist, playlists.getFirst()); } @Test void testPlaylistCount() { String testPlaylist = "testPlaylist"; List<String> mockList = new ArrayList<>(); mockList.add(testPlaylist); List<String> mockedSongs = new ArrayList<>(); IntStream.range(0, 5).forEach(i -> mockedSongs.add("file" + i)); when(databaseProperties.getListSongs()).thenReturn("listplaylist"); when(commandExecutor.sendCommand("listplaylist", testPlaylist)).thenReturn(mockedSongs); assertThat(playlistDatabase.countPlaylistSongs(testPlaylist), is(5)); } }
4,678
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDStatsConverterTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/statistics/MPDStatsConverterTest.java
package org.bff.javampd.statistics; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class MPDStatsConverterTest { private StatsConverter statsConverter; @BeforeEach void setup() { this.statsConverter = new MPDStatsConverter(); } @Test void convertEmptyResponse() { MPDStatistics stats = this.statsConverter.convertResponseToStats(List.of()); assertAll( () -> assertEquals(0, stats.getAlbums()), () -> assertEquals(0, stats.getUptime()), () -> assertEquals(0, stats.getArtists()), () -> assertEquals(0, stats.getTracks()), () -> assertEquals(0, stats.getLastUpdateTime()), () -> assertEquals(0, stats.getDatabasePlaytime()), () -> assertEquals(0, stats.getPlaytime())); } @Test void convertResponse() { MPDStatistics stats = this.statsConverter.convertResponseToStats( List.of( "uptime: 11262", "playtime: 19823", "artists: 2961", "albums: 5671", "songs: 84109", "db_playtime: 20572745", "db_update: 1646880222", "OK")); assertAll( () -> assertEquals(5671, stats.getAlbums()), () -> assertEquals(11262, stats.getUptime()), () -> assertEquals(2961, stats.getArtists()), () -> assertEquals(84109, stats.getTracks()), () -> assertEquals(1646880222, stats.getLastUpdateTime()), () -> assertEquals(20572745, stats.getDatabasePlaytime()), () -> assertEquals(19823, stats.getPlaytime())); } }
1,762
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDServerStatisticsTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/statistics/MPDServerStatisticsTest.java
package org.bff.javampd.statistics; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.List; import org.bff.javampd.command.MPDCommandExecutor; import org.bff.javampd.server.ServerProperties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDServerStatisticsTest { @Mock private MPDCommandExecutor commandExecutor; @Mock private StatsConverter statsConverter; @Captor private ArgumentCaptor<String> captor; private ServerStatistics serverStatistics; @BeforeEach void setUp() { serverStatistics = new MPDServerStatistics(new ServerProperties(), commandExecutor, statsConverter); } @Test void sendCommand() { when(commandExecutor.sendCommand((String) any())).thenReturn(List.of()); serverStatistics.getStatistics(); verify(commandExecutor).sendCommand(captor.capture()); assertEquals("stats", captor.getValue()); } }
1,289
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDStatisticsTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/statistics/MPDStatisticsTest.java
package org.bff.javampd.statistics; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class MPDStatisticsTest { @Test void equalsAndHashCode() { EqualsVerifier.simple().forClass(MPDStatistics.class).verify(); } }
256
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAdminTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/admin/MPDAdminTest.java
package org.bff.javampd.admin; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.bff.javampd.command.MPDCommandExecutor; import org.bff.javampd.output.MPDOutput; import org.bff.javampd.output.OutputChangeEvent; import org.bff.javampd.output.OutputChangeListener; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDAdminTest { @Mock private MPDCommandExecutor commandExecutor; @Mock private AdminProperties adminProperties; @Captor private ArgumentCaptor<String> commandArgumentCaptor; @Captor private ArgumentCaptor<Integer> integerParamArgumentCaptor; @Captor private ArgumentCaptor<String> stringParamArgumentCaptor; @InjectMocks private MPDAdmin admin; private AdminProperties realAdminProperties; @BeforeEach void before() { realAdminProperties = new AdminProperties(); } @Test void getSingleOutput() { when(adminProperties.getOutputs()).thenReturn(realAdminProperties.getOutputs()); when(commandExecutor.sendCommand("outputs")).thenReturn(getOutputSingleResponse()); var output1 = new ArrayList<>(admin.getOutputs()).getFirst(); assertAll( () -> assertThat(output1.getName(), is(equalTo("My ALSA Device"))), () -> assertThat(output1.getId(), is(equalTo(0))), () -> assertFalse(output1.isEnabled())); } @Test void getOutputs() { when(adminProperties.getOutputs()).thenReturn(realAdminProperties.getOutputs()); when(commandExecutor.sendCommand("outputs")).thenReturn(getOutputMultipleResponse()); var outputs = admin.getOutputs(); var output1 = new ArrayList<>(outputs).getFirst(); var output2 = new ArrayList<>(outputs).get(1); assertAll( () -> assertThat(output1.getName(), is(equalTo("My ALSA Device"))), () -> assertThat(output1.getId(), is(equalTo(0))), () -> assertFalse(output1.isEnabled()), () -> assertThat(output2.getName(), is(equalTo("My ALSA Device 2"))), () -> assertThat(output2.getId(), is(equalTo(1))), () -> assertTrue(output2.isEnabled())); } @Test void disableOutput() { when(adminProperties.getOutputs()).thenReturn(realAdminProperties.getOutputs()); when(commandExecutor.sendCommand("outputs")).thenReturn(getOutputMultipleResponse()); when(adminProperties.getOutputDisable()).thenReturn(realAdminProperties.getOutputDisable()); MPDOutput output = new ArrayList<>(admin.getOutputs()).getFirst(); admin.disableOutput(output); verify(commandExecutor) .sendCommand(commandArgumentCaptor.capture(), integerParamArgumentCaptor.capture()); assertThat(adminProperties.getOutputDisable(), is(equalTo(commandArgumentCaptor.getValue()))); assertThat(0, is(equalTo(integerParamArgumentCaptor.getValue()))); } @Test void enableOutput() { when(adminProperties.getOutputs()).thenReturn(realAdminProperties.getOutputs()); when(commandExecutor.sendCommand("outputs")).thenReturn(getOutputMultipleResponse()); when(adminProperties.getOutputEnable()).thenReturn(realAdminProperties.getOutputEnable()); MPDOutput output = new ArrayList<>(admin.getOutputs()).getFirst(); admin.enableOutput(output); verify(commandExecutor) .sendCommand(commandArgumentCaptor.capture(), integerParamArgumentCaptor.capture()); assertThat(adminProperties.getOutputEnable(), is(equalTo(commandArgumentCaptor.getValue()))); assertThat(0, is(equalTo(integerParamArgumentCaptor.getValue()))); } @Test void killMPD() { when(adminProperties.getKill()).thenReturn(realAdminProperties.getKill()); admin.killMPD(); verify(commandExecutor).sendCommand(commandArgumentCaptor.capture()); assertThat(adminProperties.getKill(), is(equalTo(commandArgumentCaptor.getValue()))); } @Test void updateDatabase() { when(adminProperties.getRefresh()).thenReturn(realAdminProperties.getRefresh()); when(commandExecutor.sendCommand("update")) .thenReturn(Collections.singletonList("updating_db: 3")); var id = admin.updateDatabase(); verify(commandExecutor).sendCommand(commandArgumentCaptor.capture()); assertThat(adminProperties.getRefresh(), is(equalTo(commandArgumentCaptor.getValue()))); assertThat(id, is(equalTo(3))); } @Test @DisplayName("handle missing id in response") void updateDatabaseMissingId() { when(adminProperties.getRefresh()).thenReturn(realAdminProperties.getRefresh()); when(commandExecutor.sendCommand("update")) .thenReturn(Collections.singletonList("updating_db: foo")); var id = admin.updateDatabase(); verify(commandExecutor).sendCommand(commandArgumentCaptor.capture()); assertThat(adminProperties.getRefresh(), is(equalTo(commandArgumentCaptor.getValue()))); assertThat(id, is(equalTo(-1))); } @Test @DisplayName("handle un-parseable id in response") void updateDatabaseUnparseableId() { when(adminProperties.getRefresh()).thenReturn(realAdminProperties.getRefresh()); when(commandExecutor.sendCommand("update")).thenReturn(Collections.singletonList("")); var id = admin.updateDatabase(); verify(commandExecutor).sendCommand(commandArgumentCaptor.capture()); assertThat(adminProperties.getRefresh(), is(equalTo(commandArgumentCaptor.getValue()))); assertThat(id, is(equalTo(-1))); } @Test void updateDatabaseWithPath() { when(adminProperties.getRefresh()).thenReturn(realAdminProperties.getRefresh()); when(commandExecutor.sendCommand("update", "testPath")) .thenReturn(Collections.singletonList("updating_db: 3")); var id = admin.updateDatabase("testPath"); verify(commandExecutor) .sendCommand(commandArgumentCaptor.capture(), stringParamArgumentCaptor.capture()); assertThat(adminProperties.getRefresh(), is(equalTo(commandArgumentCaptor.getValue()))); assertThat("testPath", is(equalTo(stringParamArgumentCaptor.getValue()))); assertThat(id, is(equalTo(3))); } @Test void rescanDatabase() { when(adminProperties.getRescan()).thenReturn(realAdminProperties.getRescan()); when(commandExecutor.sendCommand("rescan")) .thenReturn(Collections.singletonList("updating_db: 3")); var id = admin.rescan(); verify(commandExecutor).sendCommand(commandArgumentCaptor.capture()); assertThat(adminProperties.getRescan(), is(equalTo(commandArgumentCaptor.getValue()))); assertThat(id, is(equalTo(3))); } @Test void testAddChangeListener() { final MPDChangeEvent[] eventReceived = new MPDChangeEvent[1]; MPDChangeEvent.Event changeEvent = MPDChangeEvent.Event.KILLED; MPDChangeListener changeListener = event -> eventReceived[0] = event; admin.addMPDChangeListener(changeListener); admin.fireMPDChangeEvent(changeEvent); assertThat(changeEvent, is(equalTo(eventReceived[0].getEvent()))); } @Test void testRemoveListener() { final MPDChangeEvent[] eventReceived = new MPDChangeEvent[1]; MPDChangeEvent.Event changeEvent = MPDChangeEvent.Event.KILLED; MPDChangeListener changeListener = event -> eventReceived[0] = event; admin.addMPDChangeListener(changeListener); admin.fireMPDChangeEvent(changeEvent); assertThat(changeEvent, is(equalTo(eventReceived[0].getEvent()))); eventReceived[0] = null; admin.removeMPDChangeListener(changeListener); admin.fireMPDChangeEvent(changeEvent); assertNull(eventReceived[0]); } @Test void testAddOutputChangeListener() { final OutputChangeEvent[] eventReceived = new OutputChangeEvent[1]; OutputChangeEvent.OUTPUT_EVENT changeEvent = OutputChangeEvent.OUTPUT_EVENT.OUTPUT_ADDED; OutputChangeListener changeListener = event -> eventReceived[0] = event; admin.addOutputChangeListener(changeListener); admin.fireOutputChangeEvent(changeEvent); assertThat(changeEvent, is(equalTo(eventReceived[0].getEvent()))); } @Test void testRemoveOutputListener() { final OutputChangeEvent[] eventReceived = new OutputChangeEvent[1]; OutputChangeEvent.OUTPUT_EVENT changeEvent = OutputChangeEvent.OUTPUT_EVENT.OUTPUT_ADDED; OutputChangeListener changeListener = event -> eventReceived[0] = event; admin.addOutputChangeListener(changeListener); admin.fireOutputChangeEvent(changeEvent); assertThat(changeEvent, is(equalTo(eventReceived[0].getEvent()))); eventReceived[0] = null; admin.removeOutputChangeListener(changeListener); admin.fireOutputChangeEvent(changeEvent); assertNull(eventReceived[0]); } private List<String> getOutputSingleResponse() { List<String> responseList = new ArrayList<>(); responseList.add("outputid: 0"); responseList.add("outputname: My ALSA Device"); responseList.add("outputenabled: 0"); return responseList; } private List<String> getOutputMultipleResponse() { List<String> responseList = new ArrayList<>(); responseList.add("outputid: 0"); responseList.add("outputname: My ALSA Device"); responseList.add("outputenabled: 0"); responseList.add("outputid: 1"); responseList.add("outputname: My ALSA Device 2"); responseList.add("outputenabled: 1"); return responseList; } }
9,726
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDChangeEventTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/admin/MPDChangeEventTest.java
package org.bff.javampd.admin; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class MPDChangeEventTest { @Test void testConstructor2Params() { Object source = new Object(); MPDChangeEvent.Event event = MPDChangeEvent.Event.KILLED; MPDChangeEvent changeEvent = new MPDChangeEvent(source, event); assertEquals(source, changeEvent.getSource()); assertEquals(event, changeEvent.getEvent()); } }
471
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ArtistTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/ArtistTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class ArtistTagProcessorTest { @Test void testProcess() { var testArtist = "testArtist"; var line = "Artist:" + testArtist; assertEquals(testArtist, new ArtistTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new ArtistTagProcessor().processTag("BadArtist: test")); } }
525
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
FileTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/FileTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class FileTagProcessorTest { @Test void testProcess() { String testFile = "testFile"; String line = "file:" + testFile; assertEquals(testFile, new FileTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new FileTagProcessor().processTag("BadFile: test")); } }
513
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
AlbumTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/AlbumTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class AlbumTagProcessorTest { @Test void testProcess() { String testAlbum = "testAlbum"; String line = "Album:" + testAlbum; assertEquals(testAlbum, new AlbumTagProcessor().processTag(line)); } @Test void testProcessSongBadLine() { assertNull(new AlbumTagProcessor().processTag("BadAlbum: test")); } }
526
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TimeTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/TimeTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class TimeTagProcessorTest { @Test void testProcess() { var testLength = "1"; var line = "Time:" + testLength; assertEquals(testLength, new TimeTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new TimeTagProcessor().processTag("BadTime: test")); } }
506
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
IdTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/IdTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class IdTagProcessorTest { @Test void testProcess() { var testId = "1"; var line = "Id:" + testId; assertEquals(testId, new IdTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new IdTagProcessor().processTag("BadId: test")); } }
484
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TrackTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/TrackTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class TrackTagProcessorTest { @Test void testProcess() { var testTrack = "2/10"; var line = "Track:" + testTrack; assertEquals(testTrack, new TrackTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new TrackTagProcessor().processTag("BadTrack: 2/10")); } }
511
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
NameTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/NameTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class NameTagProcessorTest { @Test void testProcess() { var testName = "testName"; var line = "Name:" + testName; assertEquals(testName, new NameTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new NameTagProcessor().processTag("BadName: test")); } }
507
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
CommentTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/CommentTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class CommentTagProcessorTest { @Test void testProcess() { var testComment = "testComment"; var line = "Comment:" + testComment; assertEquals(testComment, new CommentTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new CommentTagProcessor().processTag("BadComment: test")); } }
534
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
GenreTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/GenreTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class GenreTagProcessorTest { @Test void testProcess() { String testGenre = "testGenre"; String line = "Genre:" + testGenre; assertEquals(testGenre, new GenreTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new GenreTagProcessor().processTag("BadGenre: test")); } }
522
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
DiscTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/DiscTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class DiscTagProcessorTest { @Test void testProcess() { var testDisc = "testDisc"; var line = "Disc:" + testDisc; assertEquals(testDisc, new DiscTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new DiscTagProcessor().processTag("BadDisc: test")); } }
507
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PositionTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/PositionTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class PositionTagProcessorTest { @Test void testProcess() { var testPosition = "1"; var line = "Pos:" + testPosition; assertEquals(testPosition, new PositionTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new PositionTagProcessor().processTag("BadPos: test")); } }
522
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TitleTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/TitleTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class TitleTagProcessorTest { @Test void testProcess() { var testTitle = "testTitle"; var line = "Title:" + testTitle; assertEquals(testTitle, new TitleTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new TitleTagProcessor().processTag("BadTitle: test")); } }
516
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
AlbumArtistTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/AlbumArtistTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class AlbumArtistTagProcessorTest { @Test void testProcess() { var testArtist = "testArtist"; var line = "AlbumArtist:" + testArtist; assertEquals(testArtist, new AlbumArtistTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new AlbumArtistTagProcessor().processTag("BadArtist: testArtist")); } }
551
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
DateTagProcessorTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/processor/DateTagProcessorTest.java
package org.bff.javampd.processor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class DateTagProcessorTest { @Test void testProcess() { var testDate = "1990"; var line = "Date:" + testDate; assertEquals(testDate, new DateTagProcessor().processTag(line)); } @Test void testProcessBadLine() { assertNull(new DateTagProcessor().processTag("BadDate: 1990")); } }
503
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPropertiesOverrideTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/server/MPDPropertiesOverrideTest.java
package org.bff.javampd.server; import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Properties; import org.bff.javampd.monitor.MonitorProperties; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class MPDPropertiesOverrideTest { private static final Logger LOGGER = LoggerFactory.getLogger(MPDPropertiesOverrideTest.class); private static File propertiesFile; private MPDProperties properties; @BeforeAll static void beforeAll() throws IOException, URISyntaxException { InputStream is = MPDPropertiesOverrideTest.class.getResourceAsStream("/overrides/javampd.properties"); Properties properties = new Properties(); properties.load(is); URI propPath = MPDPropertiesOverrideTest.class.getResource("/").toURI(); propertiesFile = new File(new File(propPath).getPath() + "/javampd.properties"); try { propertiesFile.createNewFile(); } catch (IOException e) { LOGGER.error("unable to create file in {}", propPath, e); throw e; } properties.store(new FileWriter(propertiesFile), ""); } @AfterAll static void afterAll() { propertiesFile.delete(); } @BeforeEach void before() { properties = new MonitorProperties(); } @Test void testAllMonitorOverrides() throws IOException { Properties originalProperties = new Properties(); InputStream is = MPDProperties.class.getResourceAsStream("/mpd.properties"); originalProperties.load(is); originalProperties.keySet().stream() .filter(key -> ((String) key).startsWith("monitor")) .forEach( key -> assertNotEquals( originalProperties.getProperty((String) key), properties.getPropertyString((String) key))); } }
2,108
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSocketTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/server/MPDSocketTest.java
package org.bff.javampd.server; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import java.io.*; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import org.bff.javampd.command.MPDCommand; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; class MPDSocketTest { private MPDSocket socket; private Socket mockSocket; private InputStream mockedInputStream; private OutputStream mockedOutputStream; private BufferedReader mockedBufferedReader; private static final String VERSION_RESPONSE = "OK MPD 0.18.0"; private ArgumentCaptor<byte[]> byteArgumentCaptor; @Test void testSocketCreationWithError() throws IOException { mockSocket = mock(Socket.class); mockedInputStream = mock(InputStream.class); when(mockSocket.getInputStream()).thenReturn(mockedInputStream); InetAddress inetAddress = InetAddress.getByName("localhost"); assertThrows(MPDConnectionException.class, () -> new TestSocket(inetAddress, 9999, 10)); } @Test void testSocketCreationWithConnectError() throws IOException { mockSocket = mock(Socket.class); mockedInputStream = mock(InputStream.class); InetAddress inetAddress = InetAddress.getByName("localhost"); int timeout = 10; int port = 9999; doThrow(new RuntimeException()) .when(mockSocket) .connect(new InetSocketAddress(inetAddress, port), timeout); assertThrows(MPDConnectionException.class, () -> new TestSocket(inetAddress, port, timeout)); } @Test void testSocketCreationWithBadResponse() throws IOException { mockSocket = mock(Socket.class); mockedBufferedReader = mock(BufferedReader.class); mockedInputStream = new ByteArrayInputStream("NOTOK MPD 0.18.0".getBytes()); when(mockSocket.getInputStream()).thenReturn(mockedInputStream); when(mockedBufferedReader.readLine()).thenReturn("Bad"); InetAddress inetAddress = InetAddress.getByName("localhost"); assertThrows(MPDConnectionException.class, () -> new TestSocket(inetAddress, 9999, 10)); } @Test void testSendCommand() throws IOException { String testResponse = "testResponse"; createValidSocket(); List<String> responseList = new ArrayList<>(); responseList.add(testResponse); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenReturn(testResponse) .thenReturn(null); MPDCommand command = new MPDCommand("command"); List<String> response = new ArrayList<>(socket.sendCommand(command)); assertEquals(testResponse, response.getFirst()); } @Test void testSendCommandOKButNoResponse() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()) .thenReturn(null) .thenReturn("OK") .thenReturn(null) .thenReturn("OK") .thenReturn(null); MPDCommand command = new MPDCommand("command"); List<String> response = new ArrayList<>(socket.sendCommand(command)); assertEquals(0, response.size()); } @Test void testSendCommandSocketException() throws IOException { String testResponse = "testResponse"; createValidSocket(); mockedInputStream = new ByteArrayInputStream(VERSION_RESPONSE.getBytes()); when(mockSocket.getInputStream()).thenReturn(mockedInputStream); when(mockedBufferedReader.readLine()) .thenReturn(VERSION_RESPONSE) .thenThrow(new SocketException()) .thenReturn(VERSION_RESPONSE) .thenReturn(testResponse) .thenReturn(null); MPDCommand command = new MPDCommand("command"); List<String> response = new ArrayList<>(socket.sendCommand(command)); assertEquals(testResponse, response.getFirst()); } @Test void testSendCommandNoPermissionResponse() throws IOException { String testResponse = "ACK: you don't have permission"; createValidSocket(); List<String> responseList = new ArrayList<>(); responseList.add(testResponse); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenReturn(testResponse) .thenReturn(null); MPDCommand command = new MPDCommand("command", "params"); assertThrows(MPDSecurityException.class, () -> socket.sendCommand(command)); } @Test void testSendCommandsSecurityException() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenThrow(new MPDSecurityException("security exception")); List<MPDCommand> commands = new ArrayList<>(); commands.add(new MPDCommand("command", "params")); assertThrows(MPDSecurityException.class, () -> socket.sendCommands(commands)); } @Test void testSendCommandsException() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenThrow(new RuntimeException("exception")); List<MPDCommand> commands = new ArrayList<>(); commands.add(new MPDCommand("command", "params")); assertThrows(MPDConnectionException.class, () -> socket.sendCommands(commands)); } @Test void testSendCommandError() throws IOException { String testResponse = "ACK: error"; createValidSocket(); List<String> responseList = new ArrayList<>(); responseList.add(testResponse); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenReturn(testResponse) .thenReturn(null); MPDCommand command = new MPDCommand("command", "params"); assertThrows(MPDConnectionException.class, () -> socket.sendCommand(command)); } @Test void testSendCommandAfterClose() throws IOException { String testResponse = "test response"; createValidSocket(); socket.close(); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenReturn(testResponse) .thenReturn(null); MPDCommand command = new MPDCommand("command", "params"); assertThrows(MPDConnectionException.class, () -> socket.sendCommand(command)); } @Test void testSendCommandClosedAfterConnected() throws IOException { String testResponse = "testResponse"; createValidSocket(); List<String> responseList = new ArrayList<>(); responseList.add(testResponse); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenReturn(testResponse) .thenReturn(null); when(mockSocket.isClosed()).thenReturn(true); MPDCommand command = new MPDCommand("command"); List<String> response = new ArrayList<>(socket.sendCommand(command)); assertEquals(testResponse, response.getFirst()); } @Test void testSendCommandNeverConnected() throws IOException { String testResponse = "test response"; createValidSocket(false); when(mockSocket.isConnected()).thenReturn(false).thenReturn(true); List<String> responseList = new ArrayList<>(); responseList.add(testResponse); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenReturn(testResponse) .thenReturn(null); assertDoesNotThrow(() -> socket.sendCommand(new MPDCommand("command", "params"))); } @Test void testSendCommandEmptyError() throws IOException { String testResponse = "ACK"; createValidSocket(); List<String> responseList = new ArrayList<>(); responseList.add(testResponse); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenReturn(testResponse) .thenReturn(null); MPDCommand command = new MPDCommand("command", "params"); assertThrows(MPDConnectionException.class, () -> socket.sendCommand(command)); } @Test void testSendCommandGeneralException() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()).thenThrow(new RuntimeException()); MPDCommand command = new MPDCommand("command", "params"); assertThrows(MPDConnectionException.class, () -> socket.sendCommand(command)); } @Test void testSendCommandException() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()).thenReturn("OK").thenThrow(new RuntimeException()); assertThrows(Exception.class, () -> socket.sendCommand(new MPDCommand("command", "param"))); } @Test void testSendCommandExceptionWithConnectException() throws IOException { createValidSocket(); mockedInputStream = new ByteArrayInputStream(VERSION_RESPONSE.getBytes()); when(mockSocket.getInputStream()) .thenThrow(new SocketException()) .thenReturn(mockedInputStream); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenThrow(new SocketException()) .thenReturn("OK"); assertDoesNotThrow(() -> socket.sendCommand(new MPDCommand("command"))); } @Test void testSendCommandExceptionWithMaxConnectExceptions() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenThrow(new SocketException()) .thenThrow(new SocketException()) .thenThrow(new SocketException()) .thenThrow(new SocketException()) .thenThrow(new SocketException()) .thenReturn("OK"); MPDCommand command = new MPDCommand("command"); assertThrows(MPDConnectionException.class, () -> socket.sendCommand(command)); } @Test void testSendCommands() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()).thenReturn(null).thenReturn("OK").thenReturn(null); List<MPDCommand> commands = new ArrayList<>(); MPDCommand command1 = new MPDCommand("command1"); MPDCommand command2 = new MPDCommand("command2", "param2"); MPDCommand command3 = new MPDCommand("command3"); commands.add(command1); commands.add(command2); commands.add(command3); mockedOutputStream = mock(OutputStream.class); when(mockSocket.getOutputStream()).thenReturn(mockedOutputStream); socket.sendCommands(commands); ServerProperties serverProperties = new ServerProperties(); StringBuilder sb = new StringBuilder(); sb.append(convertCommand(new MPDCommand(serverProperties.getStartBulk()))); commands.forEach(command -> sb.append(convertCommand(command))); sb.append(convertCommand(new MPDCommand(serverProperties.getEndBulk()))); verify(mockedOutputStream, times(2)).write(byteArgumentCaptor.capture()); assertArrayEquals(sb.toString().getBytes(), byteArgumentCaptor.getAllValues().get(1)); } @Test void ping() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()).thenReturn("OK"); MPDCommand command = new MPDCommand("status"); mockedOutputStream = mock(OutputStream.class); when(mockSocket.getOutputStream()).thenReturn(mockedOutputStream); socket.sendCommand(command); verify(mockedOutputStream, times(2)).write(byteArgumentCaptor.capture()); assertArrayEquals("ping\n".getBytes(), byteArgumentCaptor.getAllValues().getFirst()); } @Test void testSendCommandsExtraResponses() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()) .thenReturn("OK") .thenReturn("OK") .thenReturn("unexpected"); when(mockedBufferedReader.ready()).thenReturn(true).thenReturn(false); List<MPDCommand> commands = new ArrayList<>(); MPDCommand command1 = new MPDCommand("command1"); MPDCommand command2 = new MPDCommand("command2", "param2"); MPDCommand command3 = new MPDCommand("command3"); commands.add(command1); commands.add(command2); commands.add(command3); mockedOutputStream = mock(OutputStream.class); when(mockSocket.getOutputStream()).thenReturn(mockedOutputStream); socket.sendCommands(commands); ServerProperties serverProperties = new ServerProperties(); StringBuilder sb = new StringBuilder(); sb.append(convertCommand(new MPDCommand(serverProperties.getStartBulk()))); commands.forEach(command -> sb.append(convertCommand(command))); sb.append(convertCommand(new MPDCommand(serverProperties.getEndBulk()))); verify(mockedOutputStream, times(2)).write(byteArgumentCaptor.capture()); assertArrayEquals(sb.toString().getBytes(), byteArgumentCaptor.getAllValues().get(1)); } @Test void testSendCommandsWithError() throws IOException { createValidSocket(); when(mockedBufferedReader.readLine()) .thenReturn(null) .thenReturn("OK") .thenReturn(null) .thenReturn("Error") .thenReturn(null); List<MPDCommand> commands = new ArrayList<>(); MPDCommand command1 = new MPDCommand("command1"); MPDCommand command2 = new MPDCommand("command2", "param2"); MPDCommand command3 = new MPDCommand("command3"); commands.add(command1); commands.add(command2); commands.add(command3); mockedOutputStream = mock(OutputStream.class); when(mockSocket.getOutputStream()).thenReturn(mockedOutputStream); socket.sendCommands(commands); ServerProperties serverProperties = new ServerProperties(); StringBuilder sb = new StringBuilder(); sb.append(convertCommand(new MPDCommand(serverProperties.getStartBulk()))); commands.forEach(command -> sb.append(convertCommand(command))); sb.append(convertCommand(new MPDCommand(serverProperties.getEndBulk()))); verify(mockedOutputStream, times(2)).write(byteArgumentCaptor.capture()); assertArrayEquals(sb.toString().getBytes(), byteArgumentCaptor.getAllValues().get(1)); } @Test void testCreateSocket() throws IOException { createValidSocket(); assertNotNull(((TestSocket) socket).createParentSocket()); } @Test void testGetVersion() throws IOException { createValidSocket(); assertEquals("MPD 0.18.0", socket.getVersion()); } @Test void testCloseException() throws IOException { createValidSocket(); doThrow(new IOException()).when(mockSocket).close(); assertThrows(MPDConnectionException.class, () -> socket.close()); } @Test void testCloseReaderException() throws IOException { createValidSocket(); doThrow(new IOException()).when(mockedBufferedReader).close(); assertThrows(MPDConnectionException.class, () -> socket.close()); } @Test void testClose() throws IOException { createValidSocket(); assertDoesNotThrow(() -> socket.close()); } private String convertCommand(MPDCommand command) { StringBuilder sb = new StringBuilder(command.getCommand()); for (String param : command.getParams()) { param = param.replaceAll("\"", "\\\\\""); sb.append(" \"").append(param).append("\""); } return sb.append("\n").toString(); } private void createValidSocket() throws IOException { createValidSocket(true); } private void createValidSocket(boolean connected) throws IOException { mockSocket = mock(Socket.class); mockedInputStream = new ByteArrayInputStream(VERSION_RESPONSE.getBytes()); mockedOutputStream = new ByteArrayOutputStream(); mockedBufferedReader = mock(BufferedReader.class); byteArgumentCaptor = ArgumentCaptor.forClass(byte[].class); when(mockSocket.getInputStream()).thenReturn(mockedInputStream); when(mockSocket.getOutputStream()).thenReturn(mockedOutputStream); InetAddress inetAddress = InetAddress.getByName("localhost"); try { when(mockedBufferedReader.readLine()).thenReturn(VERSION_RESPONSE); } catch (IOException e) { e.printStackTrace(); } socket = new TestSocket(inetAddress, 9999, 10); socket.setReader(mockedBufferedReader); if (connected) { when(mockSocket.isConnected()).thenReturn(true); } } private class TestSocket extends MPDSocket { TestSocket(InetAddress server, int port, int timeout) { super(server, port, timeout); } @Override protected Socket createSocket() { return mockSocket; } public void setReader(BufferedReader reader) { super.setReader(mockedBufferedReader); } Socket createParentSocket() { return super.createSocket(); } } }
16,221
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ErrorEventTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/server/ErrorEventTest.java
package org.bff.javampd.server; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class ErrorEventTest { @Test void getMessage() { String message = "message"; ErrorEvent errorEvent = new ErrorEvent(this, message); assertEquals(errorEvent.getMessage(), message); } @Test void getSource() { Object source = new Object(); ErrorEvent errorEvent = new ErrorEvent(source); assertEquals(errorEvent.getSource(), source); } @Test void getSourceAndMessage() { Object source = new Object(); String message = "message"; ErrorEvent errorEvent = new ErrorEvent(source, message); assertEquals(errorEvent.getSource(), source); assertEquals(errorEvent.getMessage(), message); } }
779
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPropertiesTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/server/MPDPropertiesTest.java
package org.bff.javampd.server; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.io.InputStream; import org.bff.javampd.MPDException; import org.junit.jupiter.api.Test; class MPDPropertiesTest { @Test void testGetPropertyString() { TestProperties testProperties = new TestProperties(); assertEquals("OK", testProperties.getOk()); } @Test void testBadProperties() { assertThrows(MPDException.class, TestBadProperties::new); } @Test void testBadPropertiesLoad() { assertThrows(MPDException.class, TestBadPropertiesLoad::new); } private static class TestProperties extends MPDProperties { String getOk() { return getPropertyString("cmd.response.ok"); } } private static class TestBadProperties extends MPDProperties { @Override protected void loadValues(String propertiesResourceLocation) { super.loadValues("badLocation"); } } private static class TestBadPropertiesLoad extends MPDProperties { @Override protected void loadProperties(InputStream inputStream) throws IOException { throw new IOException(); } } }
1,227
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDServerStatusTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/server/MPDServerStatusTest.java
package org.bff.javampd.server; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.bff.javampd.Clock; import org.bff.javampd.command.MPDCommandExecutor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDServerStatusTest { @Mock private MPDCommandExecutor commandExecutor; @Mock private ServerProperties properties; @Mock private Clock clock; private MPDServerStatus serverStatus; private List<String> statusList; @BeforeEach void setUp() { statusList = new ArrayList<>(); when(clock.min()).thenReturn(LocalDateTime.MIN); serverStatus = new MPDServerStatus(properties, commandExecutor, clock); } @Test void testLookupStatus() { assertEquals(Status.VOLUME, Status.lookup("volume:")); } @Test void testLookupUnknownStatus() { assertEquals(Status.UNKNOWN, Status.lookup("bogus:")); } @Test void testGetPlaylistVersion() { String version = "5"; statusList.add("playlist: " + version); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(Integer.parseInt(version), serverStatus.getPlaylistVersion()); } @Test void testInvalidPlaylistVersion() { statusList.add("playlist: junk"); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getPlaylistVersion()); } @Test void testEmptyPlaylistVersion() { statusList.add("junk: 0"); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getPlaylistVersion()); } @Test void testGetState() { String state = "state"; statusList.add("state: " + state); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(state, serverStatus.getState()); } @Test void testGetXFade() { String xfade = "5"; statusList.add("xfade: " + xfade); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(Integer.parseInt(xfade), serverStatus.getXFade()); } @Test void testInvalidXFade() { statusList.add("xfade: junk"); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getXFade()); } @Test void testEmptyXFade() { statusList.add("junk: 0"); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getXFade()); } @Test void testGetAudio() { String audio = "audio"; statusList.add("audio: " + audio); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(audio, serverStatus.getAudio()); } @Test void testIsError() { String error = "true"; statusList.add("error: " + error); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertTrue(serverStatus.isError()); } @Test void testGetError() { String error = "true"; statusList.add("error: " + error); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(error, serverStatus.getError()); } @Test void getErrorWithQuotes() { when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(createStatusList()); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals( """ Failed to enable output "default detected output" (jack); Failed to connect to\ JACK server, status=17\ """, serverStatus.getError()); } @Test void caseInsensitive() { String error = "true"; statusList.add("Error: " + error); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(error, serverStatus.getError()); } @Test void testGetElapsedTime() { String time = "5:6"; statusList.add("time: " + time); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(Integer.parseInt(time.split(":")[0]), serverStatus.getElapsedTime()); } @ParameterizedTest @ValueSource(strings = {"time: junk", "junk: 0", "time: junk:junk"}) void testElapsedTimes(String input) { statusList.add(input); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getElapsedTime()); } @ParameterizedTest @ValueSource(strings = {"time: junk:junk", "time: junk", "junk: 0"}) void testTotalTimeParseException(String input) { statusList.add(input); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getTotalTime()); } @Test void getTotalTime() { String time = "5:6"; statusList.add("time: " + time); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(Integer.parseInt(time.split(":")[1]), serverStatus.getTotalTime()); } @Test void testGetBitrate() { String bitrate = "5"; statusList.add("bitrate: " + bitrate); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(Integer.parseInt(bitrate), serverStatus.getBitrate()); } @Test void testInvalidBitrate() { statusList.add("bitrate: junk"); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getBitrate()); } @Test void testEmptyBitrate() { statusList.add("junk: 0"); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getBitrate()); } @Test void testGetVolume() { String volume = "5"; statusList.add("volume: " + volume); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(Integer.parseInt(volume), serverStatus.getVolume()); } @Test void testInvalidVolume() { statusList.add("volume: junk"); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getVolume()); } @Test void testEmptyVolume() { statusList.add("junk: 0"); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertEquals(0, serverStatus.getVolume()); } @ParameterizedTest @ValueSource(strings = {"0", "1"}) void testIsRepeat(String repeat) { statusList.add("repeat: " + repeat); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.isRepeat(), is("1".equals(repeat))); } @ParameterizedTest @ValueSource(strings = {"anything", ""}) void testIsDatabaseUpdating(String updating) { statusList.add("updating_db: " + updating); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.isDatabaseUpdating(), is(not("".equals(updating)))); } @ParameterizedTest @ValueSource(strings = {"0", "1"}) void testRandom(String random) { statusList.add("random: " + random); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.isRandom(), is("1".equals(random))); } @Test void testInsideDefaultExpiry() { String random = "1"; statusList.add("random: " + random); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus.isRandom(); serverStatus.isRandom(); Mockito.verify(commandExecutor, times(1)).sendCommand(properties.getStatus()); } @Test void testOutsideDefaultExpiry() { String random = "1"; statusList.add("random: " + random); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus.isRandom(); when(clock.now()).thenReturn(LocalDateTime.now().plusMinutes(5)); serverStatus.isRandom(); Mockito.verify(commandExecutor, times(2)).sendCommand(properties.getStatus()); } @Test void testSetExpiry() { long interval = 1; serverStatus.setExpiryInterval(interval); String random = "1"; statusList.add("random: " + random); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus.isRandom(); when(clock.now()).thenReturn(LocalDateTime.now().plusMinutes(interval * 2)); serverStatus.isRandom(); Mockito.verify(commandExecutor, times(2)).sendCommand(properties.getStatus()); } @Test void testForceUpdate() { String random = "1"; statusList.add("random: " + random); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus.isRandom(); serverStatus.forceUpdate(); serverStatus.isRandom(); Mockito.verify(commandExecutor, times(2)).sendCommand(properties.getStatus()); } @Test void testGetStatus() { String random = "1"; String volume = "5"; statusList.add("volume: " + volume); statusList.add("random: " + random); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus.isRandom(); serverStatus.forceUpdate(); serverStatus.isRandom(); assertEquals(serverStatus.getStatus().size(), statusList.size()); } @ParameterizedTest @ValueSource(strings = {"0", "1"}) void testSingle(String single) { statusList.add("single: " + single); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.isSingle(), is("1".equals(single))); } @ParameterizedTest @ValueSource(strings = {"0", "1"}) void testConsume(String consume) { statusList.add("consume: " + consume); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.isConsume(), is("1".equals(consume))); } @Test void testPlaylistSongNumber() { var id = 464; statusList.add("song: %s".formatted(id)); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus .playlistSongNumber() .ifPresentOrElse(s -> assertThat(s, is(id)), () -> fail("song was empty")); } @Test void testPlaylistSongNumberEmpty() { when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.playlistSongNumber(), is(Optional.empty())); } @Test void testPlaylistSongId() { var id = "464"; statusList.add("songid: %s".formatted(id)); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus .playlistSongId() .ifPresentOrElse(s -> assertThat(s, is(id)), () -> fail("id was empty")); } @Test void testPlaylistSongIdEmpty() { when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.playlistSongId(), is(Optional.empty())); } @Test void testPlaylistNextSongNumber() { var id = 464; statusList.add("nextsong: %s".formatted(id)); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus .playlistNextSongNumber() .ifPresentOrElse(s -> assertThat(s, is(id)), () -> fail("number was empty")); } @Test void testPlaylistNextSongNumberEmpty() { when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.playlistNextSongNumber(), is(Optional.empty())); } @Test void testPlaylistNextSongId() { var id = "464"; statusList.add("nextsongid: %s".formatted(id)); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus .playlistNextSongId() .ifPresentOrElse(s -> assertThat(s, is(id)), () -> fail("id was empty")); } @Test void testPlaylistNextSongIdEmpty() { when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.playlistNextSongId(), is(Optional.empty())); } @Test void testDurationCurrentSong() { var duration = 235; statusList.add("duration: %s".formatted(duration)); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus .durationCurrentSong() .ifPresentOrElse(s -> assertThat(s, is(duration)), () -> fail("duration was empty")); } @Test void testDurationCurrentSongEmpty() { when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.durationCurrentSong(), is(Optional.empty())); } @Test void testElapsedCurrentSong() { var duration = 235; statusList.add("elapsed: %s".formatted(duration)); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus .elapsedCurrentSong() .ifPresentOrElse(s -> assertThat(s, is(duration)), () -> fail("duration was empty")); } @Test void testElapsedCurrentSongEmpty() { when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.elapsedCurrentSong(), is(Optional.empty())); } @ParameterizedTest @ValueSource(ints = {-5, 0, 5}) void testMixRampDb(int db) { statusList.add("mixrampdb: %s".formatted(db)); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus .getMixRampDb() .ifPresentOrElse(s -> assertThat(s, is(db)), () -> fail("db was empty")); } @Test void mixRampDbFloat() { var db = "0.000000"; statusList.add("mixrampdb: %s".formatted(db)); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus .getMixRampDb() .ifPresentOrElse(s -> assertThat(s, is(0)), () -> fail("db was empty")); } @Test void testMixRampDbEmpty() { when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.getMixRampDb(), is(Optional.empty())); } @ParameterizedTest @ValueSource(ints = {-5, 0, 5}) void testMixRampDelay(int delay) { statusList.add("mixrampdelay: %s".formatted(delay)); when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); serverStatus .getMixRampDelay() .ifPresentOrElse(s -> assertThat(s, is(delay)), () -> fail("delay was empty")); } @Test void testMixRampDelayEmpty() { when(commandExecutor.sendCommand(properties.getStatus())).thenReturn(statusList); when(clock.now()).thenReturn(LocalDateTime.now()); assertThat(serverStatus.getMixRampDelay(), is(Optional.empty())); } private List<String> createStatusList() { return Arrays.asList( "volume: 100", "repeat: 0", "random: 0", "single: 0", "consume: 0", "playlist: 67", "playlistlength: 66", "mixrampdb: 0.000000", "state: pause", "song: 0", "songid: 1", "time: 0:427", "elapsed: 0.000", "bitrate: 0", "duration: 426.680", "audio: 44100:16:2", """ error: Failed to enable output "default detected output" (jack); Failed to\ connect to JACK server, status=17\ """, "nextsong: 1", "nextsongid: 2", "OK"); } }
18,658
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ServerPropertiesTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/server/ServerPropertiesTest.java
package org.bff.javampd.server; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ServerPropertiesTest { private ServerProperties serverProperties; @BeforeEach void setUp() { serverProperties = new ServerProperties(); } @Test void getClearError() { assertEquals("clearerror", serverProperties.getClearError()); } @Test void getStatus() { assertEquals("status", serverProperties.getStatus()); } @Test void getStats() { assertEquals("stats", serverProperties.getStats()); } @Test void getPing() { assertEquals("ping", serverProperties.getPing()); } @Test void getPassword() { assertEquals("password", serverProperties.getPassword()); } @Test void getClose() { assertEquals("close", serverProperties.getClose()); } @Test void getStartBulk() { assertEquals("command_list_ok_begin", serverProperties.getStartBulk()); } @Test void getEndBulk() { assertEquals("command_list_end", serverProperties.getEndBulk()); } @Test void getEncoding() { assertEquals("UTF-8", serverProperties.getEncoding()); } }
1,201
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/server/MPDTest.java
package org.bff.javampd.server; import static org.junit.jupiter.api.Assertions.*; import java.net.InetAddress; import java.net.UnknownHostException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDTest { @Test void testGetPort() { int port = 666; assertEquals(666, MPD.builder().port(port).build().getPort()); } @Test void testGetDefaultPort() { assertEquals(6600, MPD.builder().build().getPort()); } @Test void testGetAddress() throws UnknownHostException { String address = "localhost"; assertEquals( InetAddress.getByName(address), MPD.builder().server(address).build().getAddress()); } @Test void testGetDefaultAddress() throws UnknownHostException { assertEquals(InetAddress.getByName("localhost"), MPD.builder().build().getAddress()); } @Test void testGetTimeout() { int timeOut = 666; assertEquals(timeOut, MPD.builder().timeout(timeOut).build().getTimeout()); } @Test void testGetDefaultTimeout() { assertEquals(0, MPD.builder().build().getTimeout()); } @Test void testGetPlayer() { assertNotNull(MPD.builder().build().getPlayer()); } @Test void testGetPlaylist() { assertNotNull(MPD.builder().build().getPlaylist()); } @Test void testGetAdmin() { assertNotNull(MPD.builder().build().getAdmin()); } @Test void testGetMusicDatabase() { assertNotNull(MPD.builder().build().getMusicDatabase()); } @Test void testGetServerStatistics() { assertNotNull(MPD.builder().build().getServerStatistics()); } @Test void testGetServerStatus() { assertNotNull(MPD.builder().build().getServerStatus()); } @Test void testGetMonitor() { assertNotNull(MPD.builder().build().getStandAloneMonitor()); } @Test void testGetSongSearcher() { assertNotNull(MPD.builder().build().getSongSearcher()); } @Test void testGetArtworkFinder() { assertNotNull(MPD.builder().build().getArtworkFinder()); } @Test void testDefaultPassword() { assertNull(MPD.builder().build().getPassword()); } }
2,198
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDServerTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/server/MPDServerTest.java
package org.bff.javampd.server; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import org.bff.javampd.command.MPDCommandExecutor; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDServerTest { @Mock private MPDCommandExecutor mockCommandExecutor; @Mock private ServerProperties mockServerProperties; @Captor private ArgumentCaptor<String> commandArgumentCaptor; private static final int DEFAULT_PORT = 6600; private static final int DEFAULT_TIMEOUT = 0; private static final String DEFAULT_SERVER = "localhost"; @Test void testClearError() { when(mockServerProperties.getClearError()).thenReturn(new ServerProperties().getClearError()); TestMPD mpd = new TestMPD(); mpd.clearError(); verify(mockCommandExecutor).sendCommand(commandArgumentCaptor.capture()); assertEquals( mockServerProperties.getClearError(), commandArgumentCaptor.getAllValues().getFirst()); } @Test void testClose() { new TestMPD().close(); verify(mockCommandExecutor).sendCommand(commandArgumentCaptor.capture()); assertEquals(mockServerProperties.getClose(), commandArgumentCaptor.getAllValues().getFirst()); } @Test void testServer() throws UnknownHostException { MPD mpd = MPD.builder().server("localhost").build(); assertEquals(InetAddress.getByName("localhost"), mpd.getAddress()); } @Test void testBuilderException() { var mpd = MPD.builder().server("bogusServer"); assertThrows(MPDConnectionException.class, mpd::build); } @Test void testPort() { MPD mpd = MPD.builder().port(8080).build(); assertEquals(8080, mpd.getPort()); } @Test void testTimeout() { MPD mpd = MPD.builder().timeout(0).build(); assertEquals(0, mpd.getTimeout()); } @Test void testPassword() { String password = "thepassword"; TestMPD mpd = new TestMPD(password); verify(mockCommandExecutor).usePassword(commandArgumentCaptor.capture()); assertNotNull(mpd); assertEquals(password, commandArgumentCaptor.getAllValues().getFirst()); } @Test void testNullPassword() { String password = null; MPD mpd = MPD.builder().password(password).build(); verify(mockCommandExecutor, never()).usePassword(password); assertNotNull(mpd); } @Test void testBlankPassword() { String password = ""; TestMPD mpd = new TestMPD(password); verify(mockCommandExecutor, never()).usePassword(password); assertNotNull(mpd); } @Test void testBuild() { TestMPD mpd = new TestMPD(); assertNotNull(mpd); } @Test void testDefaultServer() throws UnknownHostException { TestMPD mpd = new TestMPD(); assertEquals(InetAddress.getByName(DEFAULT_SERVER), mpd.getAddress()); } @Test void testDefaultPort() { TestMPD mpd = new TestMPD(); assertEquals(DEFAULT_PORT, mpd.getPort()); } @Test void testDefaultTimeout() { TestMPD mpd = new TestMPD(); assertEquals(DEFAULT_TIMEOUT, mpd.getTimeout()); } @Test void testIsClosed() { TestMPD mpd = new TestMPD(); assertFalse(mpd.isClosed()); } @Test void testIsNotClosed() { TestMPD mpd = new TestMPD(); mpd.close(); assertTrue(mpd.isClosed()); } @Test void testGetVersion() { String theVersion = "testVersion"; when(mockCommandExecutor.getMPDVersion()).thenReturn(theVersion); TestMPD mpd = new TestMPD(); assertEquals(theVersion, mpd.getVersion()); } @Test void testIsConnected() { when(mockServerProperties.getPing()).thenReturn(new ServerProperties().getPing()); when(mockCommandExecutor.sendCommand(mockServerProperties.getPing())) .thenReturn(new ArrayList<>()); TestMPD mpd = new TestMPD(); assertTrue(mpd.isConnected()); } @Test void testIsNotConnected() { when(mockServerProperties.getPing()).thenReturn(new ServerProperties().getPing()); when(mockCommandExecutor.sendCommand(mockServerProperties.getPing())) .thenThrow(new MPDConnectionException()); TestMPD mpd = new TestMPD(); assertFalse(mpd.isConnected()); } @Test void testAuthenticate() { assertDoesNotThrow(() -> MPD.builder().build()); } @Test void testFailedAuthenticate() { String password = "password"; doThrow(new MPDSecurityException("incorrect password")) .when(mockCommandExecutor) .authenticate(); assertThrows(MPDConnectionException.class, () -> new TestMPD(password)); } private class TestMPD extends MPD { public TestMPD() { super("localhost", 6600, 0, ""); } public TestMPD(String password) { super("localhost", 6600, 0, password); } @Override void init() { commandExecutor = mockCommandExecutor; serverProperties = mockServerProperties; } } }
5,124
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
StatusTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/server/StatusTest.java
package org.bff.javampd.server; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class StatusTest { @Test void lookupUnknownStatus() { assertEquals(Status.UNKNOWN, Status.lookup("junk")); } }
252
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDMusicDatabaseTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/database/MPDMusicDatabaseTest.java
package org.bff.javampd.database; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.bff.javampd.server.MPD; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class MPDMusicDatabaseTest { private MPD mpd; @BeforeEach void before() { mpd = MPD.builder().build(); } @Test void testGetArtistDatabase() { assertNotNull(mpd.getMusicDatabase().getArtistDatabase()); } @Test void testGetAlbumDatabase() { assertNotNull(mpd.getMusicDatabase().getAlbumDatabase()); } @Test void testGetGenreDatabase() { assertNotNull(mpd.getMusicDatabase().getGenreDatabase()); } @Test void testGetPlaylistDatabase() { assertNotNull(mpd.getMusicDatabase().getPlaylistDatabase()); } @Test void testGetFileDatabase() { assertNotNull(mpd.getMusicDatabase().getFileDatabase()); } @Test void testGetDateDatabase() { assertNotNull(mpd.getMusicDatabase().getDateDatabase()); } @Test void testGetSongDatabase() { assertNotNull(mpd.getMusicDatabase().getSongDatabase()); } }
1,082
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDTagListerTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/database/MPDTagListerTest.java
package org.bff.javampd.database; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.bff.javampd.command.MPDCommandExecutor; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDTagListerTest { @Mock private MPDCommandExecutor commandExecutor; @Mock private DatabaseProperties databaseProperties; @Captor private ArgumentCaptor<String> argumentCaptor; @InjectMocks private MPDTagLister tagLister; @Test void testListInfoSingle() { List<String> retList = new ArrayList<>(); retList.add("playlist: 5"); when(commandExecutor.sendCommand("lsinfo")).thenReturn(retList); when(databaseProperties.getListInfo()).thenReturn("lsinfo"); List<String> infoList = new ArrayList<>(tagLister.listInfo(TagLister.ListInfoType.PLAYLIST)); assertEquals(1, infoList.size()); assertEquals("5", infoList.getFirst()); } @Test void testListInfoDouble() { List<String> retList = new ArrayList<>(); retList.add("playlist: 5"); retList.add("directory: 6"); when(databaseProperties.getListInfo()).thenReturn("lsinfo"); when(commandExecutor.sendCommand("lsinfo")).thenReturn(retList); List<String> infoList = new ArrayList<>( tagLister.listInfo(TagLister.ListInfoType.PLAYLIST, TagLister.ListInfoType.DIRECTORY)); assertEquals(2, infoList.size()); assertEquals("5", infoList.getFirst()); assertEquals("6", infoList.get(1)); } @Test void testListInfoNone() { List<String> retList = new ArrayList<>(); retList.add("bogus: 5"); when(databaseProperties.getListInfo()).thenReturn("lsinfo"); when(commandExecutor.sendCommand("lsinfo")).thenReturn(retList); List<String> infoList = new ArrayList<>(tagLister.listInfo(TagLister.ListInfoType.PLAYLIST)); assertEquals(0, infoList.size()); } @Test void testList() { String testAlbumResponse = "album: 5"; List<String> retList = new ArrayList<>(); retList.add(testAlbumResponse); when(commandExecutor.sendCommand("list", "album")).thenReturn(retList); when(databaseProperties.getList()).thenReturn("list"); List<String> infoList = new ArrayList<>(tagLister.list(TagLister.ListType.ALBUM)); assertEquals(1, infoList.size()); assertEquals(testAlbumResponse, infoList.getFirst()); } @Test void testListGroupArtist() { List<String> retList = new ArrayList<>(); retList.add("album: testAlbum"); retList.add("artist: testArtist"); when(commandExecutor.sendCommand("list", "album", "group", "artist")).thenReturn(retList); when(databaseProperties.getList()).thenReturn("list"); when(databaseProperties.getGroup()).thenReturn("group"); List<String> infoList = new ArrayList<>(tagLister.list(TagLister.ListType.ALBUM, TagLister.GroupType.ARTIST)); assertEquals(2, infoList.size()); assertEquals("album: testAlbum", infoList.getFirst()); assertEquals("artist: testArtist", infoList.get(1)); } @Test void testListGroupDate() { List<String> retList = new ArrayList<>(); retList.add("album: testAlbum"); retList.add("date: testDate"); when(commandExecutor.sendCommand("list", "album", "group", "date")).thenReturn(retList); when(databaseProperties.getList()).thenReturn("list"); when(databaseProperties.getGroup()).thenReturn("group"); List<String> infoList = new ArrayList<>(tagLister.list(TagLister.ListType.ALBUM, TagLister.GroupType.DATE)); assertEquals(2, infoList.size()); assertEquals("album: testAlbum", infoList.getFirst()); assertEquals("date: testDate", infoList.get(1)); } @Test void testListGroupGenre() { List<String> retList = new ArrayList<>(); retList.add("album: testAlbum"); retList.add("genre: testGenre"); when(commandExecutor.sendCommand("list", "album", "group", "genre")).thenReturn(retList); when(databaseProperties.getList()).thenReturn("list"); when(databaseProperties.getGroup()).thenReturn("group"); List<String> infoList = new ArrayList<>(tagLister.list(TagLister.ListType.ALBUM, TagLister.GroupType.GENRE)); assertEquals(2, infoList.size()); assertEquals("album: testAlbum", infoList.getFirst()); assertEquals("genre: testGenre", infoList.get(1)); } @Test void testListError() { List<String> retList = new ArrayList<>(); retList.add(""); when(commandExecutor.sendCommand("list", "artist")).thenReturn(retList); when(databaseProperties.getList()).thenReturn("list"); List<String> infoList = new ArrayList<>(tagLister.list(TagLister.ListType.ARTIST)); assertEquals(1, infoList.size()); assertEquals("", infoList.getFirst()); } @Test void testListWithParam() { String testResponse = "album: artist"; List<String> retList = new ArrayList<>(); retList.add(testResponse); List<String> params = new ArrayList<>(); params.add("artist"); when(commandExecutor.sendCommand("list", "album", "artist")).thenReturn(retList); when(databaseProperties.getList()).thenReturn("list"); List<String> infoList = new ArrayList<>(tagLister.list(TagLister.ListType.ALBUM, params)); assertEquals(1, infoList.size()); assertEquals(testResponse, infoList.getFirst()); } @Test void testListWithParamAndGroups() { String testResponse = "album: artist"; List<String> retList = new ArrayList<>(); retList.add(testResponse); List<String> params = new ArrayList<>(); params.add("artist"); when(commandExecutor.sendCommand( "list", "album", "artist", "group", TagLister.GroupType.ARTIST.getType())) .thenReturn(retList); when(databaseProperties.getList()).thenReturn("list"); when(databaseProperties.getGroup()).thenReturn("group"); List<String> infoList = new ArrayList<>( tagLister.list(TagLister.ListType.ALBUM, params, TagLister.GroupType.ARTIST)); assertEquals(1, infoList.size()); assertEquals(testResponse, infoList.getFirst()); } @Test @DisplayName("verify order of group params") void groupOrder() { List<String> list = new ArrayList<>(); list.add(TagLister.ListType.ARTIST.getType()); list.add("Tool"); when(databaseProperties.getList()).thenReturn("list"); when(databaseProperties.getGroup()).thenReturn("group"); tagLister.list( TagLister.ListType.ALBUM, list, TagLister.GroupType.ARTIST, TagLister.GroupType.DATE, TagLister.GroupType.GENRE, TagLister.GroupType.ALBUM_ARTIST); verify(commandExecutor) .sendCommand( argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture()); assertAll( () -> assertThat(argumentCaptor.getAllValues().getFirst(), is(equalTo("list"))), () -> assertThat(argumentCaptor.getAllValues().get(1), is(equalTo("album"))), () -> assertThat(argumentCaptor.getAllValues().get(2), is(equalTo("artist"))), () -> assertThat(argumentCaptor.getAllValues().get(3), is(equalTo("Tool"))), () -> assertThat(argumentCaptor.getAllValues().get(4), is(equalTo("group"))), () -> assertThat(argumentCaptor.getAllValues().get(5), is(equalTo("artist"))), () -> assertThat(argumentCaptor.getAllValues().get(6), is(equalTo("group"))), () -> assertThat(argumentCaptor.getAllValues().get(7), is(equalTo("date"))), () -> assertThat(argumentCaptor.getAllValues().get(8), is(equalTo("group"))), () -> assertThat(argumentCaptor.getAllValues().get(9), is(equalTo("genre"))), () -> assertThat(argumentCaptor.getAllValues().get(10), is(equalTo("group"))), () -> assertThat(argumentCaptor.getAllValues().get(11), is(equalTo("albumartist")))); } }
8,715
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
DatabasePropertiesTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/database/DatabasePropertiesTest.java
package org.bff.javampd.database; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class DatabasePropertiesTest { private DatabaseProperties databaseProperties; @BeforeEach void before() { databaseProperties = new DatabaseProperties(); } @Test void getFind() { assertEquals("find", databaseProperties.getFind()); } @Test void getList() { assertEquals("list", databaseProperties.getList()); } @Test void getGroup() { assertEquals("group", databaseProperties.getGroup()); } @Test void getListInfo() { assertEquals("lsinfo", databaseProperties.getListInfo()); } @Test void getSearch() { assertEquals("search", databaseProperties.getSearch()); } @Test void getListSongs() { assertEquals("listplaylist", databaseProperties.getListSongs()); } }
909
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDDateDatabaseTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/year/MPDDateDatabaseTest.java
package org.bff.javampd.year; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.bff.javampd.database.TagLister; import org.bff.javampd.processor.DateTagProcessor; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDDateDatabaseTest { private static final String DATE_PREFIX = new DateTagProcessor().getPrefix(); @Mock private TagLister tagLister; @InjectMocks private MPDDateDatabase yearDatabase; @Test void testListAllYears() { String year1 = "1990"; String year2 = "1990-mar-24"; List<String> yearList = new ArrayList<>(); yearList.add(DATE_PREFIX + year1); yearList.add(DATE_PREFIX + year2); when(tagLister.list(TagLister.ListType.DATE)).thenReturn(yearList); List<String> years = new ArrayList<>(yearDatabase.listAllDates()); assertEquals(2, years.size()); assertEquals(year1, years.getFirst()); assertEquals(year2, years.get(1)); } }
1,201
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDArtistDatabaseTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/artist/MPDArtistDatabaseTest.java
package org.bff.javampd.artist; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.bff.javampd.database.TagLister; import org.bff.javampd.genre.MPDGenre; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDArtistDatabaseTest { private static final String ARTIST_RESPONSE_PREFIX = "Artist: "; @Captor private ArgumentCaptor<TagLister.ListType> captor; @Mock private TagLister tagLister; private MPDArtistDatabase artistDatabase; @BeforeEach void before() { artistDatabase = new MPDArtistDatabase(tagLister); } @Test void testListAllArtists() { MPDArtist testArtist = new MPDArtist("testName"); List<String> mockReturn = new ArrayList<>(); mockReturn.add(ARTIST_RESPONSE_PREFIX + testArtist.name()); when(tagLister.list(TagLister.ListType.ARTIST)).thenReturn(mockReturn); List<MPDArtist> artists = new ArrayList<>(artistDatabase.listAllArtists()); assertEquals(1, artists.size()); assertEquals(testArtist, artists.getFirst()); } @Test void listAllAlbumArtistsCommand() { MPDArtist testArtist = new MPDArtist("Tool"); List<String> mockReturn = new ArrayList<>(); mockReturn.add(ARTIST_RESPONSE_PREFIX + testArtist.name()); when(tagLister.list(TagLister.ListType.ALBUM_ARTIST)).thenReturn(mockReturn); artistDatabase.listAllAlbumArtists(); verify(tagLister).list(captor.capture()); assertEquals(TagLister.ListType.ALBUM_ARTIST, captor.getValue()); } @Test void listAllAlbumArtists() { MPDArtist testArtist = new MPDArtist("Spiritbox"); List<String> mockReturn = new ArrayList<>(); mockReturn.add(ARTIST_RESPONSE_PREFIX + testArtist.name()); when(tagLister.list(TagLister.ListType.ARTIST)).thenReturn(mockReturn); List<MPDArtist> artists = new ArrayList<>(artistDatabase.listAllArtists()); assertEquals(1, artists.size()); assertEquals(testArtist, artists.getFirst()); } @Test void testListArtistsByGenre() { MPDGenre testGenre = new MPDGenre("testGenreName"); String testArtistName = "testArtist"; List<String> mockGenreList = new ArrayList<>(); mockGenreList.add(TagLister.ListType.GENRE.getType()); mockGenreList.add(testGenre.name()); List<String> mockReturnGenreList = new ArrayList<>(); mockReturnGenreList.add(testArtistName); List<String> mockReturnArtist = new ArrayList<>(); mockReturnArtist.add(ARTIST_RESPONSE_PREFIX + testArtistName); when(tagLister.list(TagLister.ListType.ARTIST, mockGenreList)).thenReturn(mockReturnArtist); MPDArtist testArtist = new MPDArtist(testArtistName); List<MPDArtist> artists = new ArrayList<>(artistDatabase.listArtistsByGenre(testGenre)); assertEquals(1, artists.size()); assertEquals(testArtist, artists.getFirst()); } @Test void testListArtistByName() { String testArtistName = "testArtist"; List<String> mockReturnName = new ArrayList<>(); mockReturnName.add(TagLister.ListType.ARTIST.getType()); mockReturnName.add(testArtistName); List<String> mockReturnArtist = new ArrayList<>(); mockReturnArtist.add(ARTIST_RESPONSE_PREFIX + testArtistName); when(tagLister.list(TagLister.ListType.ARTIST, mockReturnName)).thenReturn(mockReturnArtist); MPDArtist testArtist = new MPDArtist(testArtistName); List<MPDArtist> artists = new ArrayList<>(); artists.add(artistDatabase.listArtistByName(testArtistName)); assertEquals(1, artists.size()); assertEquals(testArtist, artists.getFirst()); } @Test void testListMultipleArtistByName() { String testArtistName = "testArtist"; String testArtistName2 = "testArtist"; List<String> mockReturnName = new ArrayList<>(); mockReturnName.add(TagLister.ListType.ARTIST.getType()); mockReturnName.add(testArtistName); List<String> mockReturnArtist = new ArrayList<>(); mockReturnArtist.add(ARTIST_RESPONSE_PREFIX + testArtistName); mockReturnArtist.add(ARTIST_RESPONSE_PREFIX + testArtistName2); when(tagLister.list(TagLister.ListType.ARTIST, mockReturnName)).thenReturn(mockReturnArtist); MPDArtist testArtist = new MPDArtist(testArtistName); List<MPDArtist> artists = new ArrayList<>(); artists.add(artistDatabase.listArtistByName(testArtistName)); assertEquals(1, artists.size()); assertEquals(testArtist, artists.getFirst()); } }
4,757
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDArtistTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/artist/MPDArtistTest.java
package org.bff.javampd.artist; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class MPDArtistTest { @Test void equalsContract() { EqualsVerifier.simple().forClass(MPDArtist.class).verify(); } }
241
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDAudioInfoTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/audioinfo/MPDAudioInfoTest.java
package org.bff.javampd.audioinfo; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class MPDAudioInfoTest { @Test void equalsContract() { EqualsVerifier.simple().forClass(MPDAudioInfo.class).verify(); } }
250
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlayerTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/player/MPDPlayerTest.java
package org.bff.javampd.player; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.playlist.MPDPlaylistSong; import org.bff.javampd.playlist.PlaylistSongConverter; import org.bff.javampd.server.ServerStatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MPDPlayerTest { @Mock private ServerStatus serverStatus; private PlayerProperties playerProperties; @Mock private CommandExecutor commandExecutor; @Mock private PlaylistSongConverter playlistSongConverter; private MPDPlayer mpdPlayer; @Captor private ArgumentCaptor<String> stringArgumentCaptor; @Captor private ArgumentCaptor<Integer> integerArgumentCaptor; @Captor private ArgumentCaptor<String> paramArgumentCaptor; @BeforeEach void setUp() { this.playerProperties = new PlayerProperties(); this.mpdPlayer = new MPDPlayer(serverStatus, playerProperties, commandExecutor, playlistSongConverter); } @Test void testGetCurrentSong() { List<String> responseList = new ArrayList<>(); String testFile = "testFile"; String testTitle = "testTitle"; MPDPlaylistSong testSong = MPDPlaylistSong.builder().file(testFile).title(testTitle).build(); List<MPDPlaylistSong> testSongResponse = new ArrayList<>(); testSongResponse.add(testSong); when(commandExecutor.sendCommand(playerProperties.getCurrentSong())).thenReturn(responseList); when(playlistSongConverter.convertResponseToSongs(responseList)).thenReturn(testSongResponse); mpdPlayer .getCurrentSong() .ifPresentOrElse( song -> { assertThat(song.getFile(), is(equalTo((testSong.getFile())))); assertThat(song.getTitle(), is(equalTo((testSong.getTitle())))); }, () -> fail("No song found")); } @Test void testGetCurrentSongEmpty() { var responseList = new ArrayList<String>(); var testSongResponse = new ArrayList<MPDPlaylistSong>(); when(commandExecutor.sendCommand(playerProperties.getCurrentSong())).thenReturn(responseList); when(playlistSongConverter.convertResponseToSongs(responseList)).thenReturn(testSongResponse); assertThat(mpdPlayer.getCurrentSong(), is(Optional.empty())); } @Test void testPlay() { mpdPlayer.play(); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getPlay())))); } @Test void testPlaySong() { int id = 1; String testFile = "testFile"; String testTitle = "testTitle"; MPDPlaylistSong testSong = MPDPlaylistSong.builder().file(testFile).title(testTitle).id(id).build(); mpdPlayer.playSong(testSong); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getPlayId())))); assertThat(id, is(equalTo(integerArgumentCaptor.getValue()))); } @Test void testSeek() { int seconds = 100; List<String> responseList = new ArrayList<>(); String testFile = "testFile"; String testTitle = "testTitle"; int id = 5; MPDPlaylistSong testSong = MPDPlaylistSong.builder() .file(testFile) .title(testTitle) .id(id) .length(seconds + 1) .build(); List<MPDPlaylistSong> testSongResponse = new ArrayList<>(); testSongResponse.add(testSong); when(commandExecutor.sendCommand(playerProperties.getCurrentSong())).thenReturn(responseList); when(playlistSongConverter.convertResponseToSongs(responseList)).thenReturn(testSongResponse); mpdPlayer.seek(seconds); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); verify(commandExecutor) .sendCommand( stringArgumentCaptor.capture(), paramArgumentCaptor.capture(), paramArgumentCaptor.capture()); assertAll( () -> assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getCurrentSong())))), () -> assertThat( stringArgumentCaptor.getAllValues().get(1), is(equalTo((playerProperties.getSeekId())))), () -> assertThat( paramArgumentCaptor.getAllValues().getFirst(), is(equalTo((Integer.toString(testSong.getId()))))), () -> assertThat( paramArgumentCaptor.getAllValues().get(1), is(equalTo((Integer.toString(seconds)))))); } @Test void testSeekSongLengthLessThanRequest() { int seconds = 100; List<String> responseList = new ArrayList<>(); String testFile = "testFile"; String testTitle = "testTitle"; int id = 5; MPDPlaylistSong testSong = MPDPlaylistSong.builder() .file(testFile) .title(testTitle) .id(id) .length(seconds - 1) .build(); List<MPDPlaylistSong> testSongResponse = new ArrayList<>(); testSongResponse.add(testSong); when(commandExecutor.sendCommand(playerProperties.getCurrentSong())).thenReturn(responseList); when(playlistSongConverter.convertResponseToSongs(responseList)).thenReturn(testSongResponse); mpdPlayer.seek(seconds); verify(commandExecutor, only()).sendCommand(playerProperties.getCurrentSong()); verifyNoMoreInteractions(commandExecutor); } @Test void testSeekSong() { int seconds = 100; String testFile = "testFile"; String testTitle = "testTitle"; int id = 5; MPDPlaylistSong testSong = MPDPlaylistSong.builder() .file(testFile) .title(testTitle) .id(id) .length(seconds + 1) .build(); mpdPlayer.seekSong(testSong, seconds); verify(commandExecutor) .sendCommand( stringArgumentCaptor.capture(), paramArgumentCaptor.capture(), paramArgumentCaptor.capture()); assertAll( () -> assertThat( stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getSeekId())))), () -> assertThat( paramArgumentCaptor.getAllValues().getFirst(), is(equalTo((Integer.toString(testSong.getId()))))), () -> assertThat( paramArgumentCaptor.getAllValues().get(1), is(equalTo((Integer.toString(seconds)))))); } @Test void testPlayerChangeEventStarted() { final PlayerChangeEvent.Event[] playerChangeEvent = {null}; mpdPlayer.addPlayerChangeListener(event -> playerChangeEvent[0] = event.getEvent()); mpdPlayer.play(); assertThat(playerChangeEvent[0], is(equalTo((PlayerChangeEvent.Event.PLAYER_STARTED)))); } @Test void testPlayerChangeEventSongSet() { final PlayerChangeEvent.Event[] playerChangeEvent = {null}; mpdPlayer.addPlayerChangeListener(event -> playerChangeEvent[0] = event.getEvent()); MPDPlaylistSong testSong = MPDPlaylistSong.builder().file("").title("").build(); mpdPlayer.play(); mpdPlayer.playSong(testSong); assertThat(playerChangeEvent[0], is(equalTo((PlayerChangeEvent.Event.PLAYER_SONG_SET)))); } @Test void testRemovePlayerChangedListener() { final PlayerChangeEvent.Event[] playerChangeEvent = {null}; PlayerChangeListener playerChangeListener = event -> playerChangeEvent[0] = event.getEvent(); mpdPlayer.addPlayerChangeListener(playerChangeListener); mpdPlayer.play(); assertThat(playerChangeEvent[0], is(equalTo((PlayerChangeEvent.Event.PLAYER_STARTED)))); mpdPlayer.stop(); assertThat(playerChangeEvent[0], is(equalTo((PlayerChangeEvent.Event.PLAYER_STOPPED)))); mpdPlayer.removePlayerChangedListener(playerChangeListener); mpdPlayer.play(); assertThat(playerChangeEvent[0], is(equalTo((PlayerChangeEvent.Event.PLAYER_STOPPED)))); } @Test void testStop() { mpdPlayer.stop(); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getStop())))); } @Test void testPause() { mpdPlayer.pause(); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getPause())))); } @Test void testPlayNext() { mpdPlayer.playNext(); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getNext())))); } @Test void testPlayPrevious() { mpdPlayer.playPrevious(); verify(commandExecutor).sendCommand(stringArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getPrevious())))); } @Test void testMute() { mpdPlayer.mute(); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getSetVolume())))); assertThat(integerArgumentCaptor.getValue(), is(equalTo(0))); } @Test void testUnMute() { mpdPlayer.setVolume(1); mpdPlayer.unMute(); verify(commandExecutor, times(2)) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getSetVolume())))); assertThat(integerArgumentCaptor.getAllValues().getFirst(), is(equalTo(1))); assertThat(integerArgumentCaptor.getAllValues().get(1), is(equalTo(0))); } @Test void testAddVolumeChangeListener() { final VolumeChangeEvent[] volumeChangeEvent = {null}; mpdPlayer.addVolumeChangeListener(event -> volumeChangeEvent[0] = event); mpdPlayer.setVolume(5); assertThat(volumeChangeEvent[0].getVolume(), is(equalTo((5)))); } @Test void testAddVolumeChangeListenerOutOfRange() { final VolumeChangeEvent[] volumeChangeEvent = {null}; mpdPlayer.addVolumeChangeListener(event -> volumeChangeEvent[0] = event); mpdPlayer.setVolume(0); mpdPlayer.setVolume(101); assertThat(volumeChangeEvent[0].getVolume(), is(equalTo((0)))); } @Test void testRemoveVolumeChangedListener() { final VolumeChangeEvent[] volumeChangeEvent = {null}; VolumeChangeListener volumeChangeListener = event -> volumeChangeEvent[0] = event; mpdPlayer.addVolumeChangeListener(volumeChangeListener); mpdPlayer.setVolume(5); assertThat(volumeChangeEvent[0].getVolume(), (is(equalTo((5))))); mpdPlayer.removeVolumeChangedListener(volumeChangeListener); mpdPlayer.setVolume(0); assertThat(volumeChangeEvent[0].getVolume(), (is(equalTo((5))))); } @Test void testRandomizePlay() { mpdPlayer.randomizePlay(); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getRandom())))); assertThat(stringArgumentCaptor.getAllValues().get(1), is(equalTo(("1")))); } @Test void testUnrandomizePlay() { mpdPlayer.unRandomizePlay(); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo(playerProperties.getRandom()))); assertThat(stringArgumentCaptor.getAllValues().get(1), is(equalTo(("0")))); } @Test void testSetRandomTrue() { mpdPlayer.setRandom(true); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getRandom())))); assertThat(stringArgumentCaptor.getAllValues().get(1), is(equalTo("1"))); } @Test void testSetRandomFalse() { mpdPlayer.setRandom(false); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getRandom())))); assertThat(stringArgumentCaptor.getAllValues().get(1), is(equalTo(("0")))); } @Test void testIsRandom() { when(serverStatus.isRandom()).thenReturn(true); assertThat(mpdPlayer.isRandom(), is(true)); } @Test void testSetRepeatTrue() { mpdPlayer.setRepeat(true); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getRepeat())))); assertThat(stringArgumentCaptor.getAllValues().get(1), is(equalTo(("1")))); } @Test void testSetRepeatFalse() { mpdPlayer.setRepeat(false); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getRepeat())))); assertThat(stringArgumentCaptor.getAllValues().get(1), is(equalTo(("0")))); } @Test void testIsRepeat() { when(serverStatus.isRepeat()).thenReturn(true); assertThat(mpdPlayer.isRepeat(), is(true)); } @Test void testGetBitrate() { when(serverStatus.getBitrate()).thenReturn(1); assertThat(mpdPlayer.getBitrate(), is(equalTo(1))); } @Test void testGetVolume() { when(serverStatus.getVolume()).thenReturn(1); assertThat(mpdPlayer.getVolume(), is(equalTo(1))); } @Test void testSetVolume() { mpdPlayer.setVolume(0); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getSetVolume())))); assertThat(integerArgumentCaptor.getValue(), is(equalTo(0))); } @Test void testSetVolumeOutOfRangeHigh() { mpdPlayer.setVolume(101); verify(commandExecutor, never()) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); } @Test void testSetVolumeOutOfRangeLow() { mpdPlayer.setVolume(-1); verify(commandExecutor, never()) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); } @Test void testGetXFade() { when(serverStatus.getXFade()).thenReturn(1); assertThat(mpdPlayer.getXFade(), is(equalTo(1))); } @Test void testSetXFade() { mpdPlayer.setXFade(5); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getValue(), is(equalTo((playerProperties.getXFade())))); assertThat(integerArgumentCaptor.getValue(), is(equalTo(5))); } @ParameterizedTest @ValueSource(booleans = {true, false}) void testSetSingle(boolean single) { mpdPlayer.setSingle(single); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getSingle())))); assertThat(stringArgumentCaptor.getAllValues().get(1), is(equalTo(single ? "1" : "0"))); } @ParameterizedTest @ValueSource(booleans = {true, false}) void testSetConsume(boolean consume) { mpdPlayer.setConsume(consume); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getConsume())))); assertThat(stringArgumentCaptor.getAllValues().get(1), is(equalTo(consume ? "1" : "0"))); } @ParameterizedTest @ValueSource(ints = {5, -5}) void testSetMixRampDb(int db) { mpdPlayer.setMixRampDb(db); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getMixRampDb())))); assertThat(integerArgumentCaptor.getValue(), is(equalTo(db))); } @ParameterizedTest @ValueSource(ints = {5, 0, -5}) void testSetMixRampDelay(int delay) { mpdPlayer.setMixRampDelay(delay); verify(commandExecutor) .sendCommand(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); assertThat( stringArgumentCaptor.getAllValues().getFirst(), is(equalTo((playerProperties.getMixRampDelay())))); assertThat( stringArgumentCaptor.getAllValues().get(1), is(equalTo(delay < 0 ? "nan" : Integer.toString(delay)))); } @Test void testGetElapsedTime() { when(serverStatus.getElapsedTime()).thenReturn(1L); assertThat(mpdPlayer.getElapsedTime(), is(equalTo(1L))); } @Test void testGetTotalTime() { when(serverStatus.getTotalTime()).thenReturn(1L); assertThat(mpdPlayer.getTotalTime(), is(equalTo(1L))); } @Test void testGetStatusPlaying() { when(serverStatus.getState()).thenReturn(Player.Status.STATUS_PLAYING.getPrefix()); assertThat(mpdPlayer.getStatus(), is(equalTo((Player.Status.STATUS_PLAYING)))); } @Test void testGetStatusPaused() { when(serverStatus.getState()).thenReturn(Player.Status.STATUS_PAUSED.getPrefix()); assertThat(mpdPlayer.getStatus(), is(equalTo((Player.Status.STATUS_PAUSED)))); } @Test void testGetStatusStopped() { when(serverStatus.getState()).thenReturn(Player.Status.STATUS_STOPPED.getPrefix()); assertThat(mpdPlayer.getStatus(), is(equalTo((Player.Status.STATUS_STOPPED)))); } @Test void testGetAudioDetailsBitrate() { when(serverStatus.getAudio()).thenReturn("4:5:6"); assertThat(mpdPlayer.getAudioDetails().getBits(), is(equalTo(5))); } @Test void testGetAudioDetailsBadBitrate() { when(serverStatus.getAudio()).thenReturn("4:bad:6"); assertThat(mpdPlayer.getAudioDetails().getBits(), is(equalTo(-1))); } @Test void testGetAudioDetailsChannels() { when(serverStatus.getAudio()).thenReturn("4:5:6"); assertThat(mpdPlayer.getAudioDetails().getChannels(), is(equalTo(6))); } @Test void testGetAudioDetailsBadChannels() { when(serverStatus.getAudio()).thenReturn("4:5:bad"); assertThat(mpdPlayer.getAudioDetails().getChannels(), is(equalTo(-1))); } @Test void testGetAudioDetailsSampleRate() { when(serverStatus.getAudio()).thenReturn("4:5:6"); assertThat(mpdPlayer.getAudioDetails().getSampleRate(), is(equalTo(4))); } @Test void testGetAudioDetailsBadSampleRate() { when(serverStatus.getAudio()).thenReturn("bad:5:6"); assertThat(mpdPlayer.getAudioDetails().getSampleRate(), is(equalTo(-1))); } @Test void testGetMixRampDb() { when(serverStatus.getMixRampDb()).thenReturn(Optional.of(1)); mpdPlayer .getMixRampDb() .ifPresentOrElse(d -> assertThat(d, is(equalTo(1))), () -> fail("Ramp db is empty")); } @Test void testGetMixRampDbEmpty() { when(serverStatus.getMixRampDb()).thenReturn(Optional.empty()); assertThat(mpdPlayer.getMixRampDb(), is(equalTo(Optional.empty()))); } @Test void testGetMixRampDelay() { when(serverStatus.getMixRampDelay()).thenReturn(Optional.of(1)); mpdPlayer .getMixRampDelay() .ifPresentOrElse(d -> assertThat(d, is(equalTo(1))), () -> fail("No delay")); } @Test void testGetMixRampDelayEmpty() { when(serverStatus.getMixRampDelay()).thenReturn(Optional.empty()); assertThat(mpdPlayer.getMixRampDelay(), is(equalTo(Optional.empty()))); } }
20,581
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlayerPropertiesTest.java
/FileExtraction/Java_unseen/finnyb_javampd/src/test/java/org/bff/javampd/player/PlayerPropertiesTest.java
package org.bff.javampd.player; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class PlayerPropertiesTest { private PlayerProperties playerProperties; @BeforeEach void setUp() { playerProperties = new PlayerProperties(); } @Test void getXFade() { assertEquals("crossfade", playerProperties.getXFade()); } @Test void getCurrentSong() { assertEquals("currentsong", playerProperties.getCurrentSong()); } @Test void getNext() { assertEquals("next", playerProperties.getNext()); } @Test void getPause() { assertEquals("pause", playerProperties.getPause()); } @Test void getPlay() { assertEquals("play", playerProperties.getPlay()); } @Test void getPlayId() { assertEquals("playid", playerProperties.getPlayId()); } @Test void getPrevious() { assertEquals("previous", playerProperties.getPrevious()); } @Test void getRepeat() { assertEquals("repeat", playerProperties.getRepeat()); } @Test void getRandom() { assertEquals("random", playerProperties.getRandom()); } @Test void getSeek() { assertEquals("seek", playerProperties.getSeek()); } @Test void getSeekId() { assertEquals("seekid", playerProperties.getSeekId()); } @Test void getStop() { assertEquals("stop", playerProperties.getStop()); } @Test void getMixRampDb() { assertThat(playerProperties.getMixRampDb(), is(equalTo("mixrampdb"))); } @Test void getMixRampDelay() { assertThat(playerProperties.getMixRampDelay(), is(equalTo("mixrampdelay"))); } @Test void getSetVolume() { assertEquals("setvol", playerProperties.getSetVolume()); } }
1,899
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDMonitorModule.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/MPDMonitorModule.java
package org.bff.javampd; import com.google.inject.AbstractModule; import org.bff.javampd.monitor.*; /** * Initializes the DI bindings * * @author bill */ public class MPDMonitorModule extends AbstractModule { @Override protected void configure() { bind(StandAloneMonitor.class).to(MPDStandAloneMonitor.class); bind(OutputMonitor.class).to(MPDOutputMonitor.class); bind(TrackMonitor.class).to(MPDTrackMonitor.class); bind(ConnectionMonitor.class).to(MPDConnectionMonitor.class); bind(VolumeMonitor.class).to(MPDVolumeMonitor.class); bind(PlayerMonitor.class).to(MPDPlayerMonitor.class); bind(BitrateMonitor.class).to(MPDBitrateMonitor.class); bind(PlaylistMonitor.class).to(MPDPlaylistMonitor.class); bind(ErrorMonitor.class).to(MPDErrorMonitor.class); } }
804
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDModule.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/MPDModule.java
package org.bff.javampd; import com.google.inject.AbstractModule; import org.bff.javampd.admin.Admin; import org.bff.javampd.admin.MPDAdmin; import org.bff.javampd.album.AlbumConverter; import org.bff.javampd.album.MPDAlbumConverter; import org.bff.javampd.art.ArtworkFinder; import org.bff.javampd.art.MPDArtworkFinder; import org.bff.javampd.command.CommandExecutor; import org.bff.javampd.command.MPDCommandExecutor; import org.bff.javampd.database.MPDTagLister; import org.bff.javampd.database.TagLister; import org.bff.javampd.player.MPDPlayer; import org.bff.javampd.player.Player; import org.bff.javampd.playlist.MPDPlaylist; import org.bff.javampd.playlist.MPDPlaylistSongConverter; import org.bff.javampd.playlist.Playlist; import org.bff.javampd.playlist.PlaylistSongConverter; import org.bff.javampd.server.MPDServerStatus; import org.bff.javampd.server.ServerStatus; import org.bff.javampd.song.MPDSongConverter; import org.bff.javampd.song.SongConverter; import org.bff.javampd.statistics.MPDServerStatistics; import org.bff.javampd.statistics.MPDStatsConverter; import org.bff.javampd.statistics.ServerStatistics; import org.bff.javampd.statistics.StatsConverter; /** * Initializes the DI bindings * * @author bill */ public class MPDModule extends AbstractModule { @Override protected void configure() { bind(Admin.class).to(MPDAdmin.class); bind(Player.class).to(MPDPlayer.class); bind(Playlist.class).to(MPDPlaylist.class); bind(ServerStatus.class).to(MPDServerStatus.class); bind(ServerStatistics.class).to(MPDServerStatistics.class); bind(Player.class).to(MPDPlayer.class); bind(CommandExecutor.class).to(MPDCommandExecutor.class); bind(TagLister.class).to(MPDTagLister.class); bind(SongConverter.class).to(MPDSongConverter.class); bind(PlaylistSongConverter.class).to(MPDPlaylistSongConverter.class); bind(AlbumConverter.class).to(MPDAlbumConverter.class); bind(ArtworkFinder.class).to(MPDArtworkFinder.class); bind(ServerStatistics.class).to(MPDServerStatistics.class); bind(StatsConverter.class).to(MPDStatsConverter.class); bind(Clock.class).to(MPDSystemClock.class); } }
2,167
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDDatabaseModule.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/MPDDatabaseModule.java
package org.bff.javampd; import com.google.inject.AbstractModule; import org.bff.javampd.album.AlbumDatabase; import org.bff.javampd.album.MPDAlbumDatabase; import org.bff.javampd.artist.ArtistDatabase; import org.bff.javampd.artist.MPDArtistDatabase; import org.bff.javampd.database.MPDMusicDatabase; import org.bff.javampd.database.MusicDatabase; import org.bff.javampd.file.FileDatabase; import org.bff.javampd.file.MPDFileDatabase; import org.bff.javampd.genre.GenreDatabase; import org.bff.javampd.genre.MPDGenreDatabase; import org.bff.javampd.playlist.MPDPlaylistDatabase; import org.bff.javampd.playlist.PlaylistDatabase; import org.bff.javampd.song.MPDSongDatabase; import org.bff.javampd.song.MPDSongSearcher; import org.bff.javampd.song.SongDatabase; import org.bff.javampd.song.SongSearcher; import org.bff.javampd.year.DateDatabase; import org.bff.javampd.year.MPDDateDatabase; /** * Initializes the DI bindings * * @author bill */ public class MPDDatabaseModule extends AbstractModule { @Override protected void configure() { bind(ArtistDatabase.class).to(MPDArtistDatabase.class); bind(AlbumDatabase.class).to(MPDAlbumDatabase.class); bind(SongDatabase.class).to(MPDSongDatabase.class); bind(GenreDatabase.class).to(MPDGenreDatabase.class); bind(PlaylistDatabase.class).to(MPDPlaylistDatabase.class); bind(FileDatabase.class).to(MPDFileDatabase.class); bind(DateDatabase.class).to(MPDDateDatabase.class); bind(MusicDatabase.class).to(MPDMusicDatabase.class); bind(SongSearcher.class).to(MPDSongSearcher.class); } }
1,578
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSystemClock.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/MPDSystemClock.java
package org.bff.javampd; import java.time.LocalDateTime; public class MPDSystemClock implements Clock { @Override public LocalDateTime now() { return LocalDateTime.now(); } @Override public LocalDateTime min() { return LocalDateTime.MIN; } }
265
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
Clock.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/Clock.java
package org.bff.javampd; import java.time.LocalDateTime; public interface Clock { LocalDateTime now(); LocalDateTime min(); }
133
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDException.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/MPDException.java
package org.bff.javampd; import lombok.Getter; /** * Base class for MPD Exceptions. * * @author Bill * @version 1.0 */ @Getter public class MPDException extends RuntimeException { private final String command; /** Constructor. */ public MPDException() { super(); this.command = null; } /** * Class constructor specifying the message. * * @param message the exception message */ public MPDException(String message) { super(message); this.command = null; } /** * Class constructor specifying the cause. * * @param cause the cause of this exception */ public MPDException(Throwable cause) { super(cause); this.command = null; } /** * Class constructor specifying the message and cause. * * @param message the exception message * @param cause the cause of this exception */ public MPDException(String message, Throwable cause) { super(message, cause); this.command = null; } /** * Class constructor specifying the message and command generating the error. * * @param message the exception message * @param command the command generating the exception */ public MPDException(String message, String command) { super(message); this.command = command; } /** * Class constructor specifying the message and command generating the error. * * @param message the exception message * @param command the command generating the exception * @param cause the cause of the exception */ public MPDException(String message, String command, Throwable cause) { super(message, cause); this.command = command; } }
1,660
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
SongConverter.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/SongConverter.java
package org.bff.javampd.song; import java.util.List; /** * @author bill */ public interface SongConverter { /** * Converts the response from the MPD server into {@link MPDSong}s. * * @param list the response from the MPD server * @return a MPDSong object */ List<MPDSong> convertResponseToSongs(List<String> list); List<String> getSongFileNameList(List<String> fileList); }
400
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSongConverter.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/MPDSongConverter.java
package org.bff.javampd.song; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; @Slf4j public class MPDSongConverter extends MPDTagConverter<MPDSong> implements SongConverter { @Override public List<MPDSong> convertResponseToSongs(List<String> list) { return super.convertResponse(list); } @Override protected MPDSong createSong(Map<String, String> props, Map<String, List<String>> tags) { return MPDSong.builder() .file(props.get(SongProcessor.FILE.name())) .name( props.get(SongProcessor.NAME.name()) == null ? props.get(SongProcessor.TITLE.name()) : props.get(SongProcessor.NAME.name())) .title(props.get(SongProcessor.TITLE.name())) .albumArtist(props.get(SongProcessor.ALBUM_ARTIST.name())) .artistName(props.get(SongProcessor.ARTIST.name())) .genre(props.get(SongProcessor.GENRE.name())) .date(props.get(SongProcessor.DATE.name())) .comment(props.get(SongProcessor.COMMENT.name())) .discNumber(props.get(SongProcessor.DISC.name())) .albumName(props.get(SongProcessor.ALBUM.name())) .track(props.get(SongProcessor.TRACK.name())) .length(parseInt(props.get(SongProcessor.TIME.name()))) .tagMap(tags) .build(); } @Override public List<String> getSongFileNameList(List<String> fileList) { var delimiter = SongProcessor.FILE.getProcessor().getPrefix().toLowerCase(); return fileList.stream() .filter(s -> s.toLowerCase().startsWith(delimiter)) .map(s -> (s.substring(delimiter.length())).trim()) .toList(); } }
1,660
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
SongSearcher.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/SongSearcher.java
package org.bff.javampd.song; import java.util.Collection; import lombok.Getter; /** * Provides search and list functionality for {@link MPDSong}s * * @author Bill */ public interface SongSearcher { /** Defines the scope of items such as find, search. */ @Getter enum ScopeType { ALBUM("album"), ALBUM_ARTIST("albumartist"), ARTIST("artist"), TITLE("title"), TRACK("track"), NAME("name"), GENRE("genre"), DATE("date"), COMPOSER("composer"), PERFORMER("performer"), COMMENT("comment"), DISC("disc"), FILENAME("filename"), ANY("any"); private final String type; ScopeType(String type) { this.type = type; } } /** * Returns a {@link java.util.Collection} of {@link MPDSong}s for searches matching all tags. * Please note this returns a partial match of a title. To find an exact match use {@link * #findAny(String)}. * * @param criteria the search criteria * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> searchAny(String criteria); /** * Returns a {@link java.util.Collection} of {@link MPDSong}s for searches matching the provided * scope type. Please note this returns a partial match of a title. To find an exact match use * {@link #find(ScopeType, String)}. * * @param searchType the {@link ScopeType} * @param criteria the search criteria * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> search(ScopeType searchType, String criteria); /** * Returns a {@link java.util.Collection} of {@link MPDSong}s for searches matching all provided * scope types. Please note this returns a partial match of a title. To find an exact match use * {@link #find(ScopeType, String)}. * * @param criteria the search {@link SearchCriteria} * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> search(SearchCriteria... criteria); /** * Returns a {@link java.util.Collection} of {@link MPDSong}s for searches matching all scope * types. Please note this only returns an exact match of artist. To find a partial match use * {@link #search(ScopeType, String)}. * * @param criteria the search criteria * @return a {@link java.util.Collection} of {@link MPDSong}s */ Collection<MPDSong> findAny(String criteria); /** * Returns a {@link java.util.Collection} of {@link MPDSong}s for searches matching the provided * scope type. Please note this only returns an exact match of artist. To find a partial match use * {@link #search(ScopeType, String)}. * * @param scopeType the {@link ScopeType} * @param criteria the search criteria * @return a {@link java.util.Collection} of {@link MPDSong}s */ Collection<MPDSong> find(ScopeType scopeType, String criteria); /** * Returns a {@link java.util.Collection} of {@link MPDSong}s for searches matching all the * provided scope types. Please note this only returns an exact match of artist. To find a partial * match use {@link #search(ScopeType, String)}. * * @param criteria the search {@link SearchCriteria} * @return a {@link java.util.Collection} of {@link MPDSong}s */ Collection<MPDSong> find(SearchCriteria... criteria); }
3,366
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSongSearcher.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/MPDSongSearcher.java
package org.bff.javampd.song; import com.google.inject.Inject; import java.util.Arrays; import java.util.Collection; import org.bff.javampd.command.CommandExecutor; /** * Implementation of {@link SongSearcher} for MPD * * @author Bill */ public class MPDSongSearcher implements SongSearcher { private final SearchProperties searchProperties; private final CommandExecutor commandExecutor; private final SongConverter songConverter; @Inject public MPDSongSearcher( SearchProperties searchProperties, CommandExecutor commandExecutor, SongConverter songConverter) { this.searchProperties = searchProperties; this.commandExecutor = commandExecutor; this.songConverter = songConverter; } @Override public Collection<MPDSong> searchAny(String criteria) { return search(new SearchCriteria(ScopeType.ANY, criteria)); } @Override public Collection<MPDSong> search(ScopeType searchType, String criteria) { return search(new SearchCriteria(searchType, criteria)); } @Override public Collection<MPDSong> search(SearchCriteria... criteria) { var command = String.join( " AND ", Arrays.stream(criteria) .map(c -> generateSearchParams(c.searchType(), c.criteria())) .toArray(String[]::new)); return criteria.length == 1 ? search(command) : search("(" + command + ")"); } @Override public Collection<MPDSong> findAny(String criteria) { return find(new SearchCriteria(ScopeType.ANY, criteria)); } @Override public Collection<MPDSong> find(ScopeType scopeType, String criteria) { return find(new SearchCriteria(scopeType, criteria)); } @Override public Collection<MPDSong> find(SearchCriteria... criteria) { var command = String.join( " AND ", Arrays.stream(criteria) .map(c -> generateFindParams(c.searchType(), c.criteria())) .toArray(String[]::new)); return criteria.length == 1 ? find(command) : find("(" + command + ")"); } private Collection<MPDSong> find(String params) { return songConverter.convertResponseToSongs( commandExecutor.sendCommand(searchProperties.getFind(), params)); } private Collection<MPDSong> search(String params) { return songConverter.convertResponseToSongs( commandExecutor.sendCommand(searchProperties.getSearch(), params)); } private static String generateFindParams(ScopeType scopeType, String criteria) { return String.format("(%s == '%s')", scopeType.getType(), escape(criteria)); } private static String generateSearchParams(ScopeType scopeType, String criteria) { return String.format("(%s contains '%s')", scopeType.getType(), escape(criteria)); } private static String escape(String s) { return s.replace("'", "\\\\'"); } }
2,861
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
SongDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/SongDatabase.java
package org.bff.javampd.song; import java.util.Collection; import java.util.Optional; import org.bff.javampd.album.MPDAlbum; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.genre.MPDGenre; /** * Database for song related items * * @author bill */ public interface SongDatabase { /** * Returns a <code>Collection</code> of {@link org.bff.javampd.song.MPDSong}s for an album. Please * note this only returns an exact match of album. To find a partial match use {@link * #searchAlbum(org.bff.javampd.album.MPDAlbum album)}. * * @param album the album to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findAlbum(MPDAlbum album); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an album. * Please note this only returns an exact match of album. To find a partial match use {@link * #searchAlbum(String)}. * * @param album the album to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findAlbum(String album); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an album by * a particular artist. Please note this only returns an exact match of album and artist. * * @param artist the artist album belongs to * @param album the album to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findAlbumByArtist(MPDArtist artist, MPDAlbum album); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an album by * a particular artist. Please note this only returns an exact match of album and artist. * * @param artistName the artist album belongs to * @param albumName the album to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findAlbumByArtist(String artistName, String albumName); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an album by * a particular artist. Please note this only returns an exact match of album and artist. * * @param album the album to find * @param genre the genre to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findAlbumByGenre(MPDGenre genre, MPDAlbum album); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an album by * a particular artist. Please note this only returns an exact match of album and artist. * * @param album the album to find * @param year the year to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findAlbumByYear(String year, MPDAlbum album); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an any * album containing the parameter album. Please note this returns a partial match of an album. To * find an exact match use {@link #findAlbum(org.bff.javampd.album.MPDAlbum album)}. * * @param album the album to match * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> searchAlbum(MPDAlbum album); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an any * album containing the parameter album. Please note this returns a partial match of an album. To * find an exact match use {@link #findAlbum(String)}. * * @param album the album to match * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> searchAlbum(String album); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an artist. * Please note this only returns an exact match of artist. To find a partial match use {@link * #searchArtist(org.bff.javampd.artist.MPDArtist artist)}. * * @param artist the artist to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findArtist(MPDArtist artist); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an artist. * Please note this only returns an exact match of artist. To find a partial match use {@link * #searchArtist(String)}. * * @param artist the artist to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findArtist(String artist); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an any * artist containing the parameter artist. Please note this returns a partial match of an artist. * To find an exact match use {@link #findArtist(org.bff.javampd.artist.MPDArtist)}. * * @param artist the artist to match * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> searchArtist(MPDArtist artist); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an any * artist containing the parameter artist. Please note this returns a partial match of an artist. * To find an exact match use {@link #findArtist(String)}. * * @param artist the artist to match * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> searchArtist(String artist); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for a year. * * @param year the year to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findYear(String year); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for a title. * Please note this only returns an exact match of title. To find a partial match use {@link * #searchTitle(String title)}. * * @param title the title to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findTitle(String title); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for any * criteria. Please note this only returns an exact match of title. To find a partial match use * {@link #searchAny(String criteria)}. * * @param criteria the criteria to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findAny(String criteria); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an any * title containing the parameter title. Please note this returns a partial match of a title. To * find an exact match use {@link #findTitle(String title)}. * * @param title the title to match * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> searchTitle(String title); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an any * title containing the parameter title. Please note this returns a partial match of a title. To * find an exact match use {@link #searchTitle(String title)}. * * @param title the title to match * @param startYear the starting year * @param endYear the ending year * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> searchTitle(String title, int startYear, int endYear); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an any * criteria. Please note this returns a partial match of a title. To find an exact match use * {@link #findAny(String)} * * @param criteria the criteria to match * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> searchAny(String criteria); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for an any file * name containing the parameter filename. * * @param fileName the file name to match * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> searchFileName(String fileName); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for a genre. * * @param genre the genre to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findGenre(MPDGenre genre); /** * Returns a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s for a genre. * * @param genre the genre to find * @return a {@link java.util.Collection} of {@link org.bff.javampd.song.MPDSong}s */ Collection<MPDSong> findGenre(String genre); /** * Returns a {@link org.bff.javampd.song.MPDSong} for the given album and artist * * @param name name of the {@link MPDSong} * @param album name of the album * @param artist name of the artist * @return the {@link MPDSong} */ Optional<MPDSong> findSong(String name, String album, String artist); }
9,428
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
SongProcessor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/SongProcessor.java
package org.bff.javampd.song; import static org.bff.javampd.command.CommandExecutor.COMMAND_TERMINATION; import java.util.HashMap; import java.util.Map; import org.bff.javampd.processor.*; public enum SongProcessor { FILE(new FileTagProcessor()), ARTIST(new ArtistTagProcessor()), ALBUM_ARTIST(new AlbumArtistTagProcessor()), ALBUM(new AlbumTagProcessor()), TRACK(new TrackTagProcessor()), TITLE(new TitleTagProcessor()), NAME(new NameTagProcessor()), DATE(new DateTagProcessor()), GENRE(new GenreTagProcessor()), COMMENT(new CommentTagProcessor()), TIME(new TimeTagProcessor()), POS(new PositionTagProcessor()), ID(new IdTagProcessor()), DISC(new DiscTagProcessor()); private final transient ResponseProcessor responseProcessor; private static final Map<String, SongProcessor> lookup = new HashMap<>(); static { for (SongProcessor s : SongProcessor.values()) { lookup.put(s.getProcessor().getPrefix().toLowerCase(), s); } } SongProcessor(ResponseProcessor responseProcessor) { this.responseProcessor = responseProcessor; } public static SongProcessor lookup(String line) { return lookup.get(line.substring(0, line.indexOf(":") + 1).toLowerCase()); } public ResponseProcessor getProcessor() { return responseProcessor; } /** * Returns the line prefix that delimits songs in the response list * * @return the prefix that breaks songs in the list */ public static String getDelimitingPrefix() { return FILE.getProcessor().getPrefix(); } public static String getTermination() { return COMMAND_TERMINATION; } }
1,622
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSongDatabase.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/MPDSongDatabase.java
package org.bff.javampd.song; import com.google.inject.Inject; import java.nio.file.FileSystems; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import org.bff.javampd.album.MPDAlbum; import org.bff.javampd.artist.MPDArtist; import org.bff.javampd.genre.MPDGenre; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MPDSongDatabase represents a song database controller to a {@link org.bff.javampd.server.MPD}. To * obtain an instance of the class you must use the {@link * org.bff.javampd.database.MusicDatabase#getSongDatabase()} method from the {@link * org.bff.javampd.server.MPD} connection class. * * @author Bill */ public class MPDSongDatabase implements SongDatabase { private static final Logger LOGGER = LoggerFactory.getLogger(MPDSongDatabase.class); private final SongSearcher songSearcher; @Inject public MPDSongDatabase(SongSearcher songSearcher) { this.songSearcher = songSearcher; } @Override public Collection<MPDSong> findAlbum(MPDAlbum album) { return findAlbum(album.getName()); } @Override public Collection<MPDSong> findAlbum(String album) { return songSearcher.find(SongSearcher.ScopeType.ALBUM, album); } @Override public Collection<MPDSong> findAlbumByArtist(MPDArtist artist, MPDAlbum album) { return findAlbumByArtist(artist.name(), album.getName()); } @Override public Collection<MPDSong> findAlbumByArtist(String artistName, String albumName) { List<MPDSong> songList = new ArrayList<>(songSearcher.find(SongSearcher.ScopeType.ALBUM, albumName)); return songList.stream() .filter(song -> song.getArtistName() != null && song.getArtistName().equals(artistName)) .toList(); } @Override public Collection<MPDSong> findAlbumByGenre(MPDGenre genre, MPDAlbum album) { List<MPDSong> songList = new ArrayList<>(songSearcher.find(SongSearcher.ScopeType.ALBUM, album.getName())); return songList.stream() .filter(song -> song.getGenre() != null && song.getGenre().equals(genre.name())) .toList(); } @Override public Collection<MPDSong> findAlbumByYear(String year, MPDAlbum album) { List<MPDSong> songList = new ArrayList<>(songSearcher.find(SongSearcher.ScopeType.ALBUM, album.getName())); return songList.stream() .filter(song -> song.getDate() != null && song.getDate().equals(year)) .toList(); } @Override public Collection<MPDSong> searchAlbum(MPDAlbum album) { return searchAlbum(album.getName()); } @Override public Collection<MPDSong> searchAlbum(String album) { return songSearcher.search(SongSearcher.ScopeType.ALBUM, album); } @Override public Collection<MPDSong> findArtist(MPDArtist artist) { return findArtist(artist.name()); } @Override public Collection<MPDSong> findArtist(String artist) { return songSearcher.find(SongSearcher.ScopeType.ARTIST, artist); } @Override public Collection<MPDSong> searchArtist(MPDArtist artist) { return searchArtist(artist.name()); } @Override public Collection<MPDSong> searchArtist(String artist) { return songSearcher.search(SongSearcher.ScopeType.ARTIST, artist); } @Override public Collection<MPDSong> findYear(String year) { return songSearcher.find(SongSearcher.ScopeType.DATE, year); } @Override public Collection<MPDSong> findTitle(String title) { return songSearcher.find(SongSearcher.ScopeType.TITLE, title); } @Override public Collection<MPDSong> findAny(String criteria) { return songSearcher.find(SongSearcher.ScopeType.ANY, criteria); } @Override public Collection<MPDSong> searchTitle(String title) { return songSearcher.search(SongSearcher.ScopeType.TITLE, title); } @Override public Collection<MPDSong> searchAny(String criteria) { return songSearcher.search(SongSearcher.ScopeType.ANY, criteria); } @Override public Collection<MPDSong> searchTitle(String title, int startYear, int endYear) { List<MPDSong> retList = new ArrayList<>(); for (MPDSong song : songSearcher.search(SongSearcher.ScopeType.TITLE, title)) { int year; // Ignore songs that miss the year tag. if (song.getDate() == null) { continue; } try { if (song.getDate().contains("-")) { year = Integer.parseInt(song.getDate().split("-")[0]); } else { year = Integer.parseInt(song.getDate()); } if (year >= startYear && year <= endYear) { retList.add(song); } } catch (Exception e) { LOGGER.error("Problem searching for title", e); } } return retList; } @Override public Collection<MPDSong> searchFileName(String fileName) { return songSearcher.search(SongSearcher.ScopeType.FILENAME, removeSlashes(fileName)); } @Override public Collection<MPDSong> findGenre(MPDGenre genre) { return findGenre(genre.name()); } @Override public Collection<MPDSong> findGenre(String genre) { return songSearcher.find(SongSearcher.ScopeType.GENRE, genre); } @Override public Optional<MPDSong> findSong(String name, String album, String artist) { List<MPDSong> songs = new ArrayList<>(songSearcher.find(SongSearcher.ScopeType.ALBUM, album)); for (MPDSong song : songs) { if (artist.equals(song.getArtistName())) { return Optional.of(song); } } LOGGER.info("Song not found title --> {}, artist --> {}, album --> {}", name, artist, album); return Optional.empty(); } /** * Removes leading or trailing slashes from a string. * * @param path the string to remove leading or trailing slashes * @return the string without leading or trailing slashes */ private static String removeSlashes(String path) { var retString = path; var slash = FileSystems.getDefault().getSeparator(); // if non-Unix slashes replace retString = retString.replace(slash, "/"); retString = retString.replaceFirst("^/", ""); retString = retString.replaceFirst("/$", ""); return retString; } }
6,149
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
SearchProperties.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/SearchProperties.java
package org.bff.javampd.song; import lombok.Getter; import org.bff.javampd.server.MPDProperties; /** * @author bill */ public class SearchProperties extends MPDProperties { @Getter private enum Command { FIND("db.find"), SEARCH("db.search"), WINDOW("db.window"); private final String key; Command(String key) { this.key = key; } } public String getFind() { return getPropertyString(Command.FIND.getKey()); } public String getWindow() { return getPropertyString(Command.WINDOW.getKey()); } public String getSearch() { return getPropertyString(Command.SEARCH.getKey()); } }
641
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDSong.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/MPDSong.java
package org.bff.javampd.song; import java.util.List; import java.util.Map; import lombok.Data; import lombok.experimental.SuperBuilder; /** * MPDSong represents a song in the MPD database that can be inserted into a playlist. * * @author Bill * @version 1.0 */ @SuperBuilder @Data public class MPDSong implements Comparable<MPDSong> { private final String name; private final String title; private final String albumArtist; private final String artistName; private final String albumName; /** Returns the path of the song without a leading or trailing slash. */ private final String file; private final String genre; private final String comment; private final String date; private final String discNumber; private final String track; /** Returns the length of the song in seconds. */ private final int length; /** Returns a map of all tags for this song. */ private final Map<String, List<String>> tagMap; /** * Returns the name of the song which can be different than the title if for example listening to * streaming radio. If no name has been set then {@link #getTitle()} is used * * @return the name of the song if set, otherwise the title */ public String getName() { if (this.name == null || this.name.isEmpty()) { return getTitle(); } else { return this.name; } } public int compareTo(MPDSong song) { StringBuilder sb; sb = new StringBuilder(getName()); sb.append(getAlbumName() == null ? "" : getAlbumName()); sb.append(getTrack()); var thisSong = sb.toString(); sb = new StringBuilder(song.getName()); sb.append(song.getAlbumName() == null ? "" : song.getAlbumName()); sb.append(getTrack()); var songToCompare = sb.toString(); return thisSong.compareTo(songToCompare); } }
1,821
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDTagConverter.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/song/MPDTagConverter.java
package org.bff.javampd.song; import java.util.*; import lombok.extern.slf4j.Slf4j; @Slf4j public abstract class MPDTagConverter<T extends MPDSong> { protected static final String DELIMITING_PREFIX = SongProcessor.getDelimitingPrefix(); private static final String TERMINATION = SongProcessor.getTermination(); private static final String LINE_DELIMITER = ":"; public List<T> convertResponse(List<String> list) { var songList = new ArrayList<T>(); var iterator = list.iterator(); String line = null; while (iterator.hasNext()) { if ((!isLineDelimiter(line))) { line = iterator.next(); } if (line != null && isLineDelimiter(line)) { var props = new HashMap<String, String>(); var tags = new HashMap<String, List<String>>(); line = processSong(line.substring(DELIMITING_PREFIX.length()).trim(), iterator, props, tags); songList.add(createSong(props, tags)); } } return songList; } protected String processSong( String fileName, Iterator<String> iterator, Map<String, String> props, Map<String, List<String>> tags) { props.put(SongProcessor.FILE.name(), fileName); String line = null; if (iterator.hasNext()) { line = iterator.next(); } while (!isStreamTerminated(line) && !isLineDelimiter(line)) { addTag(line, tags); var processor = SongProcessor.lookup(line); if (processor != null) { var tag = processor.getProcessor().processTag(line); props.put(processor.name(), tag); } else { log.warn("Processor not found - {}", line); } if (iterator.hasNext()) { line = iterator.next(); } else { break; } } return line; } protected abstract T createSong(Map<String, String> props, Map<String, List<String>> tags); protected boolean isLineDelimiter(String line) { return line != null && line.toLowerCase().startsWith(DELIMITING_PREFIX.toLowerCase()); } protected int parseInt(String tag) { try { return Integer.parseInt(tag); } catch (NumberFormatException e) { log.warn(String.format("Unable to convert tag to Integer: %s", tag)); return -1; } } private boolean isStreamTerminated(String line) { return line == null || TERMINATION.equalsIgnoreCase(line) || isLineDelimiter(line); } private void addTag(String line, Map<String, List<String>> tags) { var tag = line.split(LINE_DELIMITER); if (tag.length > 1) { addToTagMap(tag, tags); log.debug("added tag to song: {} -> {}", tag[0], tag[1]); } else { log.debug("Not adding to tag map, line is not a tag {}", line); } } private void addToTagMap(String[] tag, Map<String, List<String>> tags) { var l = tags.get(tag[0]); if (l == null) { l = new ArrayList<>(); } l.add(tag[1].trim()); tags.put(tag[0], l); } }
2,944
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDErrorMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MPDErrorMonitor.java
package org.bff.javampd.monitor; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.List; import org.bff.javampd.server.ErrorEvent; import org.bff.javampd.server.ErrorListener; import org.bff.javampd.server.Status; @Singleton public class MPDErrorMonitor implements ErrorMonitor { private String error; private final List<ErrorListener> errorListeners; MPDErrorMonitor() { this.errorListeners = new ArrayList<>(); } @Override public synchronized void addErrorListener(ErrorListener el) { errorListeners.add(el); } @Override public synchronized void removeErrorListener(ErrorListener el) { errorListeners.remove(el); } /** * Sends the appropriate {@link ErrorListener} to all registered {@link ErrorListener}s. * * @param message the event message */ protected void fireMPDErrorEvent(String message) { var ee = new ErrorEvent(this, message); for (ErrorListener el : errorListeners) { el.errorEventReceived(ee); } } @Override public void processResponseStatus(String line) { var status = Status.lookup(line); if (status == Status.ERROR) { error = line.substring(Status.ERROR.getStatusPrefix().length()).trim(); } } @Override public void reset() { error = null; } @Override public void checkStatus() { if (error != null) { fireMPDErrorEvent(error); error = null; } } }
1,434
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlayerMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/PlayerMonitor.java
package org.bff.javampd.monitor; import org.bff.javampd.player.BitrateChangeListener; import org.bff.javampd.player.PlayerBasicChangeListener; import org.bff.javampd.player.VolumeChangeListener; public interface PlayerMonitor extends StatusMonitor { void addPlayerChangeListener(PlayerBasicChangeListener pcl); void removePlayerChangeListener(PlayerBasicChangeListener pcl); void addBitrateChangeListener(BitrateChangeListener bcl); void removeBitrateChangeListener(BitrateChangeListener bcl); void addVolumeChangeListener(VolumeChangeListener vcl); void removeVolumeChangeListener(VolumeChangeListener vcl); PlayerStatus getStatus(); }
659
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
Monitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/Monitor.java
package org.bff.javampd.monitor; @FunctionalInterface public interface Monitor { /** Check the status */ void checkStatus(); }
132
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ConnectionMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/ConnectionMonitor.java
package org.bff.javampd.monitor; import org.bff.javampd.server.ConnectionChangeListener; import org.bff.javampd.server.Server; public interface ConnectionMonitor extends Monitor { /** * Adds a {@link org.bff.javampd.server.ConnectionChangeListener} to this object to receive {@link * org.bff.javampd.server.ConnectionChangeEvent}s. * * @param ccl the ConnectionChangeListener to add */ void addConnectionChangeListener(ConnectionChangeListener ccl); /** * Removes a {@link ConnectionChangeListener} from this object. * * @param ccl the ConnectionChangeListener to remove */ void removeConnectionChangeListener(ConnectionChangeListener ccl); /** * Set the server to monitor connectivity on * * @param server server for monitoring */ void setServer(Server server); /** * Returns whether the server is connected * * @return true if the server is connected */ boolean isConnected(); }
954
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlayerMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MPDPlayerMonitor.java
package org.bff.javampd.monitor; import static org.bff.javampd.monitor.PlayerStatus.*; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.List; import org.bff.javampd.player.PlayerBasicChangeEvent; import org.bff.javampd.player.PlayerBasicChangeListener; import org.bff.javampd.server.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class MPDPlayerMonitor extends MPDBitrateMonitor implements PlayerMonitor { private static final Logger LOGGER = LoggerFactory.getLogger(MPDPlayerMonitor.class); private PlayerStatus status = PlayerStatus.STATUS_STOPPED; private final List<PlayerBasicChangeListener> playerListeners; private String state; MPDPlayerMonitor() { this.playerListeners = new ArrayList<>(); state = ""; } @Override public void processResponseStatus(String line) { super.processResponseStatus(line); if (Status.lookup(line) == Status.STATE) { state = line.substring(Status.STATE.getStatusPrefix().length()).trim(); } } @Override public void checkStatus() { super.checkStatus(); PlayerStatus newStatus = null; if (state.startsWith(StandAloneMonitor.PlayerResponse.PLAY.getPrefix())) { newStatus = STATUS_PLAYING; } else if (state.startsWith(StandAloneMonitor.PlayerResponse.PAUSE.getPrefix())) { newStatus = STATUS_PAUSED; } else if (state.startsWith(StandAloneMonitor.PlayerResponse.STOP.getPrefix())) { newStatus = PlayerStatus.STATUS_STOPPED; } if (!status.equals(newStatus)) { processNewStatus(newStatus); status = newStatus; } } private void processNewStatus(PlayerStatus newStatus) { LOGGER.debug("status change from {} to {}", status, newStatus); if (newStatus == STATUS_PLAYING) { processPlayingStatus(status); } else if (newStatus == STATUS_STOPPED) { firePlayerChangeEvent(PlayerBasicChangeEvent.Status.PLAYER_STOPPED); } else if (newStatus == STATUS_PAUSED) { processPausedStatus(status); } } @Override public synchronized void addPlayerChangeListener(PlayerBasicChangeListener pcl) { playerListeners.add(pcl); } @Override public synchronized void removePlayerChangeListener(PlayerBasicChangeListener pcl) { playerListeners.remove(pcl); } @Override public PlayerStatus getStatus() { return this.status; } @Override public void reset() { state = ""; status = PlayerStatus.STATUS_STOPPED; } /** * Sends the appropriate {@link org.bff.javampd.player.PlayerBasicChangeEvent.Status} to all * registered {@link PlayerBasicChangeListener}s. * * @param status the {@link org.bff.javampd.player.PlayerBasicChangeEvent.Status} */ protected synchronized void firePlayerChangeEvent(PlayerBasicChangeEvent.Status status) { var pce = new PlayerBasicChangeEvent(this, status); for (PlayerBasicChangeListener pcl : playerListeners) { pcl.playerBasicChange(pce); } } private void processPlayingStatus(PlayerStatus oldStatus) { if (oldStatus == STATUS_PAUSED) { firePlayerChangeEvent(PlayerBasicChangeEvent.Status.PLAYER_UNPAUSED); } else if (oldStatus == STATUS_STOPPED) { firePlayerChangeEvent(PlayerBasicChangeEvent.Status.PLAYER_STARTED); } } private void processPausedStatus(PlayerStatus oldStatus) { if (oldStatus == STATUS_PLAYING) { firePlayerChangeEvent(PlayerBasicChangeEvent.Status.PLAYER_PAUSED); } else if (oldStatus == STATUS_STOPPED) { firePlayerChangeEvent(PlayerBasicChangeEvent.Status.PLAYER_STOPPED); } } }
3,603
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDTrackMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MPDTrackMonitor.java
package org.bff.javampd.monitor; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.List; import org.bff.javampd.player.TrackPositionChangeEvent; import org.bff.javampd.player.TrackPositionChangeListener; import org.bff.javampd.server.Status; @Singleton public class MPDTrackMonitor implements TrackMonitor { private final List<TrackPositionChangeListener> trackListeners; private long oldPos; private long elapsedTime; MPDTrackMonitor() { this.trackListeners = new ArrayList<>(); } @Override public void checkStatus() { checkTrackPosition(elapsedTime); } @Override public void processResponseStatus(String line) { if (Status.lookup(line) == Status.TIME) { elapsedTime = Long.parseLong( line.substring(Status.TIME.getStatusPrefix().length()).trim().split(":")[0]); } } @Override public void reset() { oldPos = 0; elapsedTime = 0; } /** * Checks the track position and fires a {@link TrackPositionChangeEvent} if there has been a * change in track position. * * @param newPos the new elapsed time to check */ protected final void checkTrackPosition(long newPos) { if (oldPos != newPos) { oldPos = newPos; fireTrackPositionChangeEvent(newPos); } } /** * Adds a {@link TrackPositionChangeListener} to this object to receive {@link * org.bff.javampd.player.TrackPositionChangeEvent}s. * * @param tpcl the TrackPositionChangeListener to add */ @Override public synchronized void addTrackPositionChangeListener(TrackPositionChangeListener tpcl) { trackListeners.add(tpcl); } /** * Removes a {@link TrackPositionChangeListener} from this object. * * @param tpcl the TrackPositionChangeListener to remove */ @Override public synchronized void removeTrackPositionChangeListener(TrackPositionChangeListener tpcl) { trackListeners.remove(tpcl); } @Override public void resetElapsedTime() { elapsedTime = 0; oldPos = 0; } /** * Sends the appropriate {@link org.bff.javampd.player.TrackPositionChangeEvent} to all registered * {@link TrackPositionChangeListener}s. * * @param newTime the new elapsed time */ protected synchronized void fireTrackPositionChangeEvent(long newTime) { var tpce = new TrackPositionChangeEvent(this, newTime); for (TrackPositionChangeListener tpcl : trackListeners) { tpcl.trackPositionChanged(tpce); } } }
2,490
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDPlaylistMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MPDPlaylistMonitor.java
package org.bff.javampd.monitor; import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.List; import org.bff.javampd.playlist.PlaylistBasicChangeEvent; import org.bff.javampd.playlist.PlaylistBasicChangeListener; import org.bff.javampd.server.Status; @Singleton public class MPDPlaylistMonitor implements PlaylistMonitor { private final List<PlaylistBasicChangeListener> playlistListeners; private int newPlaylistVersion; private int oldPlaylistVersion; private int newPlaylistLength; private int oldPlaylistLength; private int oldSong; private int newSong; private int oldSongId; private int newSongId; private final PlayerMonitor playerMonitor; @Inject MPDPlaylistMonitor(PlayerMonitor playerMonitor) { this.playerMonitor = playerMonitor; this.playlistListeners = new ArrayList<>(); } @Override public synchronized void addPlaylistChangeListener(PlaylistBasicChangeListener pcl) { playlistListeners.add(pcl); } @Override public synchronized void removePlaylistChangeListener(PlaylistBasicChangeListener pcl) { playlistListeners.remove(pcl); } @Override public int getSongId() { return this.newSongId; } @Override public void playerStopped() { if (getSongId() == -1) { firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event.PLAYLIST_ENDED); } } /** * Sends the appropriate {@link org.bff.javampd.playlist.PlaylistChangeEvent} to all registered * {@link org.bff.javampd.playlist.PlaylistChangeListener}. * * @param event the {@link org.bff.javampd.playlist.PlaylistBasicChangeEvent.Event} */ public synchronized void firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event event) { var pce = new PlaylistBasicChangeEvent(this, event); for (PlaylistBasicChangeListener pcl : playlistListeners) { pcl.playlistBasicChange(pce); } } @Override public void processResponseStatus(String line) { var status = Status.lookup(line); switch (status) { case PLAYLIST: newPlaylistVersion = Integer.parseInt(line.substring(Status.PLAYLIST.getStatusPrefix().length()).trim()); break; case PLAYLISTLENGTH: newPlaylistLength = Integer.parseInt( line.substring(Status.PLAYLISTLENGTH.getStatusPrefix().length()).trim()); break; case CURRENTSONG: newSong = Integer.parseInt(line.substring(Status.CURRENTSONG.getStatusPrefix().length()).trim()); break; case CURRENTSONGID: newSongId = Integer.parseInt( line.substring(Status.CURRENTSONGID.getStatusPrefix().length()).trim()); break; default: // Do nothing break; } } @Override public void reset() { newPlaylistVersion = 0; oldPlaylistVersion = 0; newPlaylistLength = 0; oldPlaylistLength = 0; oldSong = 0; newSong = 0; oldSongId = 0; newSongId = 0; } @Override public void checkStatus() { if (oldPlaylistVersion != newPlaylistVersion) { firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event.PLAYLIST_CHANGED); oldPlaylistVersion = newPlaylistVersion; } if (oldPlaylistLength != newPlaylistLength) { if (oldPlaylistLength < newPlaylistLength) { firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event.SONG_ADDED); } else { firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event.SONG_DELETED); } oldPlaylistLength = newPlaylistLength; } if (playerMonitor.getStatus() == PlayerStatus.STATUS_PLAYING) { if (oldSong != newSong) { firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event.SONG_CHANGED); oldSong = newSong; } else if (oldSongId != newSongId) { firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event.SONG_CHANGED); oldSongId = newSongId; } } } }
3,957
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDStandAloneMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MPDStandAloneMonitor.java
package org.bff.javampd.monitor; import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.bff.javampd.output.OutputChangeListener; import org.bff.javampd.player.*; import org.bff.javampd.playlist.PlaylistBasicChangeListener; import org.bff.javampd.server.ConnectionChangeListener; import org.bff.javampd.server.ErrorListener; import org.bff.javampd.server.ServerStatus; /** * MPDStandAloneMonitor monitors a MPD connection by querying the status and statistics of the MPD * server at given getDelay intervals. As statistics change appropriate events are fired indicating * these changes. If more detailed events are desired attach listeners to the different controllers * of a connection. * * @author Bill * @version 1.0 */ @Singleton public class MPDStandAloneMonitor implements StandAloneMonitor, PlayerBasicChangeListener { private final StandAloneMonitorThread standAloneMonitorThread; private final OutputMonitor outputMonitor; private final ErrorMonitor errorMonitor; private final ConnectionMonitor connectionMonitor; private final PlayerMonitor playerMonitor; private final TrackMonitor trackMonitor; private final PlaylistMonitor playlistMonitor; private final MonitorProperties monitorProperties; private ExecutorService executorService; @Inject MPDStandAloneMonitor( ServerStatus serverStatus, OutputMonitor outputMonitor, TrackMonitor trackMonitor, ConnectionMonitor connectionMonitor, PlayerMonitor playerMonitor, PlaylistMonitor playlistMonitor, ErrorMonitor errorMonitor) { this.monitorProperties = new MonitorProperties(); this.outputMonitor = outputMonitor; this.trackMonitor = trackMonitor; this.connectionMonitor = connectionMonitor; this.playerMonitor = playerMonitor; this.playlistMonitor = playlistMonitor; this.errorMonitor = errorMonitor; this.standAloneMonitorThread = new StandAloneMonitorThread( serverStatus, connectionMonitor, monitorProperties.getMonitorDelay(), monitorProperties.getExceptionDelay()); createMonitors(); } private void createMonitors() { standAloneMonitorThread.addMonitor( new ThreadedMonitor(trackMonitor, monitorProperties.getTrackDelay()), new ThreadedMonitor(playerMonitor, monitorProperties.getPlayerDelay()), new ThreadedMonitor(errorMonitor, monitorProperties.getErrorDelay()), new ThreadedMonitor(playlistMonitor, monitorProperties.getPlaylistDelay()), new ThreadedMonitor(connectionMonitor, monitorProperties.getConnectionDelay()), new ThreadedMonitor(outputMonitor, monitorProperties.getOutputDelay())); } /** * Adds a {@link org.bff.javampd.player.TrackPositionChangeListener} to this object to receive * {@link org.bff.javampd.player.TrackPositionChangeEvent}s. * * @param tpcl the TrackPositionChangeListener to add */ @Override public synchronized void addTrackPositionChangeListener(TrackPositionChangeListener tpcl) { trackMonitor.addTrackPositionChangeListener(tpcl); } /** * Removes a {@link TrackPositionChangeListener} from this object. * * @param tpcl the TrackPositionChangeListener to remove */ @Override public synchronized void removeTrackPositionChangeListener(TrackPositionChangeListener tpcl) { trackMonitor.removeTrackPositionChangeListener(tpcl); } /** * Adds a {@link org.bff.javampd.server.ConnectionChangeListener} to this object to receive {@link * org.bff.javampd.server.ConnectionChangeEvent}s. * * @param ccl the ConnectionChangeListener to add */ @Override public synchronized void addConnectionChangeListener(ConnectionChangeListener ccl) { connectionMonitor.addConnectionChangeListener(ccl); } /** * Removes a {@link ConnectionChangeListener} from this object. * * @param ccl the ConnectionChangeListener to remove */ @Override public synchronized void removeConnectionChangeListener(ConnectionChangeListener ccl) { connectionMonitor.removeConnectionChangeListener(ccl); } @Override public synchronized void addPlayerChangeListener(PlayerBasicChangeListener pcl) { playerMonitor.addPlayerChangeListener(pcl); } @Override public synchronized void removePlayerChangeListener(PlayerBasicChangeListener pcl) { playerMonitor.removePlayerChangeListener(pcl); } @Override public synchronized void addVolumeChangeListener(VolumeChangeListener vcl) { playerMonitor.addVolumeChangeListener(vcl); } @Override public synchronized void removeVolumeChangeListener(VolumeChangeListener vcl) { playerMonitor.removeVolumeChangeListener(vcl); } @Override public synchronized void addBitrateChangeListener(BitrateChangeListener bcl) { playerMonitor.addBitrateChangeListener(bcl); } @Override public synchronized void removeBitrateChangeListener(BitrateChangeListener bcl) { playerMonitor.removeBitrateChangeListener(bcl); } @Override public synchronized void addOutputChangeListener(OutputChangeListener vcl) { outputMonitor.addOutputChangeListener(vcl); } @Override public synchronized void removeOutputChangeListener(OutputChangeListener vcl) { outputMonitor.removeOutputChangeListener(vcl); } @Override public synchronized void addPlaylistChangeListener(PlaylistBasicChangeListener pcl) { playlistMonitor.addPlaylistChangeListener(pcl); } @Override public synchronized void removePlaylistChangeListener(PlaylistBasicChangeListener pcl) { playlistMonitor.removePlaylistChangeListener(pcl); } @Override public synchronized void addErrorListener(ErrorListener el) { errorMonitor.addErrorListener(el); } @Override public synchronized void removeErrorListener(ErrorListener el) { errorMonitor.removeErrorListener(el); } @Override public void start() { executorService = Executors.newSingleThreadExecutor(); executorService.execute(this.standAloneMonitorThread); } @Override public void stop() { this.standAloneMonitorThread.setStopped(true); executorService.shutdown(); } @Override public boolean isDone() { return this.standAloneMonitorThread.isDone(); } @Override public boolean isLoaded() { return this.standAloneMonitorThread.isInitialized(); } @Override public void playerBasicChange(PlayerBasicChangeEvent event) { if (event.getStatus() == PlayerBasicChangeEvent.Status.PLAYER_STOPPED) { processStoppedStatus(); } } private void processStoppedStatus() { trackMonitor.resetElapsedTime(); playlistMonitor.playerStopped(); } }
6,757
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
BitrateMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/BitrateMonitor.java
package org.bff.javampd.monitor; import org.bff.javampd.player.BitrateChangeListener; public interface BitrateMonitor extends StatusMonitor { void addBitrateChangeListener(BitrateChangeListener bcl); void removeBitrateChangeListener(BitrateChangeListener bcl); }
271
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
StatusMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/StatusMonitor.java
package org.bff.javampd.monitor; public interface StatusMonitor extends Monitor { void processResponseStatus(String line); void reset(); }
145
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
VolumeMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/VolumeMonitor.java
package org.bff.javampd.monitor; import org.bff.javampd.player.VolumeChangeListener; public interface VolumeMonitor extends StatusMonitor { void addVolumeChangeListener(VolumeChangeListener vcl); void removeVolumeChangeListener(VolumeChangeListener vcl); }
264
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlaylistMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/PlaylistMonitor.java
package org.bff.javampd.monitor; import org.bff.javampd.playlist.PlaylistBasicChangeListener; public interface PlaylistMonitor extends StatusMonitor { void addPlaylistChangeListener(PlaylistBasicChangeListener pcl); void removePlaylistChangeListener(PlaylistBasicChangeListener pcl); int getSongId(); void playerStopped(); }
338
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
ErrorMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/ErrorMonitor.java
package org.bff.javampd.monitor; import org.bff.javampd.server.ErrorListener; public interface ErrorMonitor extends StatusMonitor { void addErrorListener(ErrorListener el); void removeErrorListener(ErrorListener el); }
226
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MPDBitrateMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MPDBitrateMonitor.java
package org.bff.javampd.monitor; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.List; import org.bff.javampd.player.BitrateChangeEvent; import org.bff.javampd.player.BitrateChangeListener; import org.bff.javampd.server.Status; @Singleton public class MPDBitrateMonitor extends MPDVolumeMonitor implements BitrateMonitor { private int oldBitrate; private int newBitrate; private final List<BitrateChangeListener> bitrateListeners; MPDBitrateMonitor() { bitrateListeners = new ArrayList<>(); } @Override public synchronized void addBitrateChangeListener(BitrateChangeListener bcl) { bitrateListeners.add(bcl); } @Override public synchronized void removeBitrateChangeListener(BitrateChangeListener bcl) { bitrateListeners.remove(bcl); } @Override public void processResponseStatus(String line) { super.processResponseStatus(line); if (Status.lookup(line) == Status.BITRATE) { newBitrate = Integer.parseInt(line.substring(Status.BITRATE.getStatusPrefix().length()).trim()); } } @Override public void checkStatus() { super.checkStatus(); if (oldBitrate != newBitrate) { fireBitrateChangeEvent(new BitrateChangeEvent(this, oldBitrate, newBitrate)); oldBitrate = newBitrate; } } private void fireBitrateChangeEvent(BitrateChangeEvent bitrateChangeEvent) { for (BitrateChangeListener bcl : bitrateListeners) { bcl.bitrateChanged(bitrateChangeEvent); } } @Override public void reset() { oldBitrate = 0; newBitrate = 0; } }
1,588
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlayerStatus.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/PlayerStatus.java
package org.bff.javampd.monitor; public enum PlayerStatus { /** player stopped status */ STATUS_STOPPED, /** player playing status */ STATUS_PLAYING, /** player paused status */ STATUS_PAUSED, }
209
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
MonitorProperties.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/MonitorProperties.java
package org.bff.javampd.monitor; import lombok.Getter; import org.bff.javampd.server.MPDProperties; /** * Properties for the {@link org.bff.javampd.monitor.MPDStandAloneMonitor}. All properties are in * seconds * * @author bill */ public class MonitorProperties extends MPDProperties { @Getter private enum Delay { OUTPUT("monitor.output.multiplier"), CONNECTION("monitor.connection.multiplier"), PLAYLIST("monitor.playlist.multiplier"), ERROR("monitor.error.multiplier"), PLAYER("monitor.player.multiplier"), TRACK("monitor.track.multiplier"), MONITOR("monitor.delay"), EXCEPTION("monitor.exception.multiplier"); private final String key; Delay(String key) { this.key = key; } } public int getOutputDelay() { return Integer.parseInt(getPropertyString(Delay.OUTPUT.getKey())); } public int getConnectionDelay() { return Integer.parseInt(getPropertyString(Delay.CONNECTION.getKey())); } public int getPlaylistDelay() { return Integer.parseInt(getPropertyString(Delay.PLAYLIST.getKey())); } public int getPlayerDelay() { return Integer.parseInt(getPropertyString(Delay.PLAYER.getKey())); } public int getErrorDelay() { return Integer.parseInt(getPropertyString(Delay.ERROR.getKey())); } public int getTrackDelay() { return Integer.parseInt(getPropertyString(Delay.TRACK.getKey())); } public int getMonitorDelay() { return Integer.parseInt(getPropertyString(Delay.MONITOR.getKey())); } public int getExceptionDelay() { return Integer.parseInt(getPropertyString(Delay.EXCEPTION.getKey())); } }
1,628
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
StandAloneMonitor.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/monitor/StandAloneMonitor.java
package org.bff.javampd.monitor; import lombok.Getter; import org.bff.javampd.output.OutputChangeListener; import org.bff.javampd.player.BitrateChangeListener; import org.bff.javampd.player.PlayerBasicChangeListener; import org.bff.javampd.player.TrackPositionChangeListener; import org.bff.javampd.player.VolumeChangeListener; import org.bff.javampd.playlist.PlaylistBasicChangeListener; import org.bff.javampd.server.ConnectionChangeListener; import org.bff.javampd.server.ErrorListener; /** * @author bill */ public interface StandAloneMonitor { /** * Adds a {@link org.bff.javampd.player.TrackPositionChangeListener} to this object to receive * {@link org.bff.javampd.player.PlayerChangeEvent}s. * * @param tpcl the TrackPositionChangeListener to add */ void addTrackPositionChangeListener(TrackPositionChangeListener tpcl); /** * Removes a {@link org.bff.javampd.player.TrackPositionChangeListener} from this object. * * @param tpcl the TrackPositionChangeListener to remove */ void removeTrackPositionChangeListener(TrackPositionChangeListener tpcl); /** * Adds a {@link org.bff.javampd.server.ConnectionChangeListener} to this object to receive {@link * org.bff.javampd.player.PlayerChangeEvent}s. * * @param ccl the ConnectionChangeListener to add */ void addConnectionChangeListener(ConnectionChangeListener ccl); /** * Removes a {@link org.bff.javampd.server.ConnectionChangeListener} from this object. * * @param ccl the ConnectionChangeListener to remove */ void removeConnectionChangeListener(ConnectionChangeListener ccl); /** * Adds a {@link org.bff.javampd.player.PlayerBasicChangeListener} to this object to receive * {@link org.bff.javampd.player.PlayerChangeEvent}s. * * @param pcl the PlayerBasicChangeListener to add */ void addPlayerChangeListener(PlayerBasicChangeListener pcl); /** * Removes a {@link org.bff.javampd.player.PlayerBasicChangeListener} from this object. * * @param pcl the PlayerBasicChangeListener to remove */ void removePlayerChangeListener(PlayerBasicChangeListener pcl); /** * Adds a {@link org.bff.javampd.player.VolumeChangeListener} to this object to receive {@link * org.bff.javampd.player.VolumeChangeEvent}s. * * @param vcl the VolumeChangeListener to add */ void addVolumeChangeListener(VolumeChangeListener vcl); /** * Removes a {@link org.bff.javampd.player.VolumeChangeListener} from this object. * * @param vcl the VolumeChangeListener to remove */ void removeVolumeChangeListener(VolumeChangeListener vcl); /** * Adds a {@link org.bff.javampd.player.BitrateChangeListener} to this object to receive {@link * org.bff.javampd.player.BitrateChangeEvent}s. * * @param bcl the BitrateChangeListener to add */ void addBitrateChangeListener(BitrateChangeListener bcl); /** * Removes a {@link org.bff.javampd.player.BitrateChangeListener} from this object. * * @param bcl the BitrateChangeListener to remove */ void removeBitrateChangeListener(BitrateChangeListener bcl); /** * Adds a {@link org.bff.javampd.output.OutputChangeListener} to this object to receive {@link * org.bff.javampd.output.OutputChangeEvent}s. * * @param vcl the OutputChangeListener to add */ void addOutputChangeListener(OutputChangeListener vcl); /** * Removes a {@link org.bff.javampd.output.OutputChangeListener} from this object. * * @param vcl the OutputChangeListener to remove */ void removeOutputChangeListener(OutputChangeListener vcl); /** * Adds a {@link org.bff.javampd.playlist.PlaylistBasicChangeListener} to this object to receive * {@link org.bff.javampd.playlist.PlaylistChangeEvent}s. * * @param pcl the PlaylistChangeListener to add */ void addPlaylistChangeListener(PlaylistBasicChangeListener pcl); /** * Removes a {@link org.bff.javampd.playlist.PlaylistBasicChangeListener} from this object. * * @param pcl the PlaylistBasicChangeListener to remove */ void removePlaylistChangeListener(PlaylistBasicChangeListener pcl); /** * Adds a {@link ErrorListener} to this object to receive {@link * org.bff.javampd.server.ErrorEvent}s. * * @param el the ErrorListener to add */ void addErrorListener(ErrorListener el); /** * Removes a {@link ErrorListener} from this object. * * @param el the ErrorListener to remove */ void removeErrorListener(ErrorListener el); /** * Starts the monitor by creating and starting a thread using this instance as the Runnable * interface. */ void start(); /** Stops the thread. */ void stop(); /** * Returns true if the monitor is stopped, false if the monitor is still running. * * @return true if monitor is running, false otherwise false */ boolean isDone(); /** * Returns true after the initial statuses have been loaded by the monitor * * @return if the initial state has been loaded */ boolean isLoaded(); @Getter enum PlayerResponse { PLAY("play"), STOP("stop"), PAUSE("pause"); private final String prefix; PlayerResponse(String prefix) { this.prefix = prefix; } } }
5,235
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z