diff options
Diffstat (limited to 'subsonic-main/src/test/java/net/sourceforge/subsonic')
21 files changed, 2471 insertions, 0 deletions
diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/MissingTranslations.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/MissingTranslations.java new file mode 100644 index 00000000..cf3dbc6c --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/MissingTranslations.java @@ -0,0 +1,35 @@ +package net.sourceforge.subsonic; + +import java.io.*; +import java.util.*; + +public class MissingTranslations { + + public static void main(String[] args) throws IOException { + String[] locales = {"da", "de", "es", "pt", "fi", "fr", "is", "it", "ja_JP", "mk", "nl", "no", "pl", "ru", "sl", "sv", "zh_CN", "zh_TW"}; + + for (String locale : locales) { + diff(locale, "en"); + } + } + + private static void diff(String locale1, String locale2) throws IOException { + Properties en = new Properties(); + en.load(MissingTranslations.class.getResourceAsStream("/net/sourceforge/subsonic/i18n/ResourceBundle_" + locale1 + ".properties")); + SortedMap<Object,Object> enSorted = new TreeMap<Object, Object>(en); + + Properties mk = new Properties(); + mk.load(MissingTranslations.class.getResourceAsStream("/net/sourceforge/subsonic/i18n/ResourceBundle_" + locale2 + ".properties")); + + System.out.println("\nMessages present in locale " + locale1 + " and missing in locale " + locale2 + ":"); + int count = 0; + for (Map.Entry<Object, Object> entry : enSorted.entrySet()) { + if (!mk.containsKey(entry.getKey())) { + System.out.println(entry.getKey() + " = " + entry.getValue()); + count++; + } + } + + System.out.println("\nTotal: " + count); + } +} diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/controller/StreamControllerTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/controller/StreamControllerTestCase.java new file mode 100644 index 00000000..6fe77f4b --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/controller/StreamControllerTestCase.java @@ -0,0 +1,122 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.controller; + +import java.awt.Dimension; + +import junit.framework.TestCase; + +/** + * @author Sindre Mehus + * @version $Id$ + */ +public class StreamControllerTestCase extends TestCase { + + public void testGetRequestedVideoSize() { + StreamController controller = new StreamController(); + + // Valid spec. + assertEquals("Wrong size.", new Dimension(123, 456), controller.getRequestedVideoSize("123x456")); + assertEquals("Wrong size.", new Dimension(456, 123), controller.getRequestedVideoSize("456x123")); + assertEquals("Wrong size.", new Dimension(1, 1), controller.getRequestedVideoSize("1x1")); + + // Missing spec. + assertNull("Wrong size.", controller.getRequestedVideoSize(null)); + + // Invalid spec. + assertNull("Wrong size.", controller.getRequestedVideoSize("123")); + assertNull("Wrong size.", controller.getRequestedVideoSize("123x")); + assertNull("Wrong size.", controller.getRequestedVideoSize("x123")); + assertNull("Wrong size.", controller.getRequestedVideoSize("x")); + assertNull("Wrong size.", controller.getRequestedVideoSize("foo123x456bar")); + assertNull("Wrong size.", controller.getRequestedVideoSize("foo123x456")); + assertNull("Wrong size.", controller.getRequestedVideoSize("123x456bar")); + assertNull("Wrong size.", controller.getRequestedVideoSize("fooxbar")); + assertNull("Wrong size.", controller.getRequestedVideoSize("-1x1")); + assertNull("Wrong size.", controller.getRequestedVideoSize("1x-1")); + + // Too large. + assertNull("Wrong size.", controller.getRequestedVideoSize("3000x100")); + assertNull("Wrong size.", controller.getRequestedVideoSize("100x3000")); + } + + public void testGetSuitableVideoSize() { + + // 4:3 aspect rate + doTestGetSuitableVideoSize(720, 540, 200, 320, 240); + doTestGetSuitableVideoSize(720, 540, 300, 320, 240); + doTestGetSuitableVideoSize(720, 540, 400, 320, 240); + doTestGetSuitableVideoSize(720, 540, 500, 320, 240); + doTestGetSuitableVideoSize(720, 540, 600, 320, 240); + + doTestGetSuitableVideoSize(720, 540, 700, 480, 360); + doTestGetSuitableVideoSize(720, 540, 800, 480, 360); + doTestGetSuitableVideoSize(720, 540, 900, 480, 360); + doTestGetSuitableVideoSize(720, 540, 1000, 480, 360); + + doTestGetSuitableVideoSize(720, 540, 1100, 640, 480); + doTestGetSuitableVideoSize(720, 540, 1200, 640, 480); + doTestGetSuitableVideoSize(720, 540, 1500, 640, 480); + doTestGetSuitableVideoSize(720, 540, 2000, 640, 480); + + // 16:9 aspect rate + doTestGetSuitableVideoSize(960, 540, 200, 428, 240); + doTestGetSuitableVideoSize(960, 540, 300, 428, 240); + doTestGetSuitableVideoSize(960, 540, 400, 428, 240); + doTestGetSuitableVideoSize(960, 540, 500, 428, 240); + doTestGetSuitableVideoSize(960, 540, 600, 428, 240); + + doTestGetSuitableVideoSize(960, 540, 700, 640, 360); + doTestGetSuitableVideoSize(960, 540, 800, 640, 360); + doTestGetSuitableVideoSize(960, 540, 900, 640, 360); + doTestGetSuitableVideoSize(960, 540, 1000, 640, 360); + + doTestGetSuitableVideoSize(960, 540, 1100, 854, 480); + doTestGetSuitableVideoSize(960, 540, 1200, 854, 480); + doTestGetSuitableVideoSize(960, 540, 1500, 854, 480); + doTestGetSuitableVideoSize(960, 540, 2000, 854, 480); + + // Small original size. + doTestGetSuitableVideoSize(100, 100, 1000, 100, 100); + doTestGetSuitableVideoSize(100, 1000, 1000, 100, 1000); + doTestGetSuitableVideoSize(1000, 100, 100, 1000, 100); + + // Unknown original size. + doTestGetSuitableVideoSize(720, null, 200, 320, 240); + doTestGetSuitableVideoSize(null, 540, 300, 320, 240); + doTestGetSuitableVideoSize(null, null, 400, 320, 240); + doTestGetSuitableVideoSize(720, null, 500, 320, 240); + doTestGetSuitableVideoSize(null, 540, 600, 320, 240); + doTestGetSuitableVideoSize(null, null, 700, 480, 360); + doTestGetSuitableVideoSize(720, null, 1200, 640, 480); + doTestGetSuitableVideoSize(null, 540, 1500, 640, 480); + doTestGetSuitableVideoSize(null, null, 2000, 640, 480); + + // Odd original size. + doTestGetSuitableVideoSize(853, 464, 1500, 854, 464); + doTestGetSuitableVideoSize(464, 853, 1500, 464, 854); + } + + private void doTestGetSuitableVideoSize(Integer existingWidth, Integer existingHeight, Integer maxBitRate, int expectedWidth, int expectedHeight) { + StreamController controller = new StreamController(); + Dimension dimension = controller.getSuitableVideoSize(existingWidth, existingHeight, maxBitRate); + assertEquals("Wrong width.", expectedWidth, dimension.width); + assertEquals("Wrong height.", expectedHeight, dimension.height); + } +} diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/DaoTestCaseBase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/DaoTestCaseBase.java new file mode 100644 index 00000000..8d3a7f88 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/DaoTestCaseBase.java @@ -0,0 +1,83 @@ +package net.sourceforge.subsonic.dao; + +import junit.framework.TestCase; +import net.sourceforge.subsonic.util.FileUtil; +import org.springframework.jdbc.core.JdbcTemplate; + +import java.io.File; + +/** + * Superclass for all DAO test cases. + * Creates and configures the DAO's, and resets the test database. + * + * @author Sindre Mehus + */ +public abstract class DaoTestCaseBase extends TestCase { + + /** Do not re-create database if it is less than one hour old. */ + private static final long MAX_DB_AGE_MILLIS = 60L * 60 * 1000; + + static { + deleteDatabase(); + } + + private DaoHelper daoHelper; + protected PlayerDao playerDao; + protected InternetRadioDao internetRadioDao; + protected RatingDao ratingDao; + protected MusicFolderDao musicFolderDao; + protected UserDao userDao; + protected TranscodingDao transcodingDao; + protected PodcastDao podcastDao; + + protected DaoTestCaseBase() { + daoHelper = new DaoHelper(); + + playerDao = new PlayerDao(); + internetRadioDao = new InternetRadioDao(); + ratingDao = new RatingDao(); + musicFolderDao = new MusicFolderDao(); + userDao = new UserDao(); + transcodingDao = new TranscodingDao(); + podcastDao = new PodcastDao(); + + playerDao.setDaoHelper(daoHelper); + internetRadioDao.setDaoHelper(daoHelper); + ratingDao.setDaoHelper(daoHelper); + musicFolderDao.setDaoHelper(daoHelper); + userDao.setDaoHelper(daoHelper); + transcodingDao.setDaoHelper(daoHelper); + podcastDao.setDaoHelper(daoHelper); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + getJdbcTemplate().execute("shutdown"); + } + + protected JdbcTemplate getJdbcTemplate() { + return daoHelper.getJdbcTemplate(); + } + + private static void deleteDatabase() { + File subsonicHome = new File("/tmp/subsonic"); + File dbHome = new File(subsonicHome, "db"); + System.setProperty("subsonic.home", subsonicHome.getPath()); + + long now = System.currentTimeMillis(); + if (now - dbHome.lastModified() > MAX_DB_AGE_MILLIS) { + System.out.println("Resetting test database: " + dbHome); + delete(dbHome); + } + } + + private static void delete(File file) { + if (file.isDirectory()) { + for (File child : FileUtil.listFiles(file)) { + delete(child); + } + } + file.delete(); + } +} diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/InternetRadioDaoTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/InternetRadioDaoTestCase.java new file mode 100644 index 00000000..5e5c64e7 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/InternetRadioDaoTestCase.java @@ -0,0 +1,67 @@ +package net.sourceforge.subsonic.dao; + +import java.util.Date; + +import net.sourceforge.subsonic.domain.InternetRadio; + +/** + * Unit test of {@link InternetRadioDao}. + * + * @author Sindre Mehus + */ +public class InternetRadioDaoTestCase extends DaoTestCaseBase { + + protected void setUp() throws Exception { + getJdbcTemplate().execute("delete from internet_radio"); + } + + public void testCreateInternetRadio() { + InternetRadio radio = new InternetRadio("name", "streamUrl", "homePageUrl", true, new Date()); + internetRadioDao.createInternetRadio(radio); + + InternetRadio newRadio = internetRadioDao.getAllInternetRadios().get(0); + assertInternetRadioEquals(radio, newRadio); + } + + public void testUpdateInternetRadio() { + InternetRadio radio = new InternetRadio("name", "streamUrl", "homePageUrl", true, new Date()); + internetRadioDao.createInternetRadio(radio); + radio = internetRadioDao.getAllInternetRadios().get(0); + + radio.setName("newName"); + radio.setStreamUrl("newStreamUrl"); + radio.setHomepageUrl("newHomePageUrl"); + radio.setEnabled(false); + radio.setChanged(new Date(234234L)); + internetRadioDao.updateInternetRadio(radio); + + InternetRadio newRadio = internetRadioDao.getAllInternetRadios().get(0); + assertInternetRadioEquals(radio, newRadio); + } + + public void testDeleteInternetRadio() { + assertEquals("Wrong number of radios.", 0, internetRadioDao.getAllInternetRadios().size()); + + internetRadioDao.createInternetRadio(new InternetRadio("name", "streamUrl", "homePageUrl", true, new Date())); + assertEquals("Wrong number of radios.", 1, internetRadioDao.getAllInternetRadios().size()); + + internetRadioDao.createInternetRadio(new InternetRadio("name", "streamUrl", "homePageUrl", true, new Date())); + assertEquals("Wrong number of radios.", 2, internetRadioDao.getAllInternetRadios().size()); + + internetRadioDao.deleteInternetRadio(internetRadioDao.getAllInternetRadios().get(0).getId()); + assertEquals("Wrong number of radios.", 1, internetRadioDao.getAllInternetRadios().size()); + + internetRadioDao.deleteInternetRadio(internetRadioDao.getAllInternetRadios().get(0).getId()); + assertEquals("Wrong number of radios.", 0, internetRadioDao.getAllInternetRadios().size()); + } + + private void assertInternetRadioEquals(InternetRadio expected, InternetRadio actual) { + assertEquals("Wrong name.", expected.getName(), actual.getName()); + assertEquals("Wrong stream url.", expected.getStreamUrl(), actual.getStreamUrl()); + assertEquals("Wrong home page url.", expected.getHomepageUrl(), actual.getHomepageUrl()); + assertEquals("Wrong enabled state.", expected.isEnabled(), actual.isEnabled()); + assertEquals("Wrong changed date.", expected.getChanged(), actual.getChanged()); + } + + +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/MusicFolderDaoTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/MusicFolderDaoTestCase.java new file mode 100644 index 00000000..b65e8b17 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/MusicFolderDaoTestCase.java @@ -0,0 +1,85 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.dao; + +import java.io.File; +import java.util.Date; + +import net.sourceforge.subsonic.domain.MusicFolder; + +/** + * Unit test of {@link MusicFolderDao}. + * + * @author Sindre Mehus + */ +public class MusicFolderDaoTestCase extends DaoTestCaseBase { + + @Override + protected void setUp() throws Exception { + getJdbcTemplate().execute("delete from music_folder"); + } + + public void testCreateMusicFolder() { + MusicFolder musicFolder = new MusicFolder(new File("path"), "name", true, new Date()); + musicFolderDao.createMusicFolder(musicFolder); + + MusicFolder newMusicFolder = musicFolderDao.getAllMusicFolders().get(0); + assertMusicFolderEquals(musicFolder, newMusicFolder); + } + + public void testUpdateMusicFolder() { + MusicFolder musicFolder = new MusicFolder(new File("path"), "name", true, new Date()); + musicFolderDao.createMusicFolder(musicFolder); + musicFolder = musicFolderDao.getAllMusicFolders().get(0); + + musicFolder.setPath(new File("newPath")); + musicFolder.setName("newName"); + musicFolder.setEnabled(false); + musicFolder.setChanged(new Date(234234L)); + musicFolderDao.updateMusicFolder(musicFolder); + + MusicFolder newMusicFolder = musicFolderDao.getAllMusicFolders().get(0); + assertMusicFolderEquals(musicFolder, newMusicFolder); + } + + public void testDeleteMusicFolder() { + assertEquals("Wrong number of music folders.", 0, musicFolderDao.getAllMusicFolders().size()); + + musicFolderDao.createMusicFolder(new MusicFolder(new File("path"), "name", true, new Date())); + assertEquals("Wrong number of music folders.", 1, musicFolderDao.getAllMusicFolders().size()); + + musicFolderDao.createMusicFolder(new MusicFolder(new File("path"), "name", true, new Date())); + assertEquals("Wrong number of music folders.", 2, musicFolderDao.getAllMusicFolders().size()); + + musicFolderDao.deleteMusicFolder(musicFolderDao.getAllMusicFolders().get(0).getId()); + assertEquals("Wrong number of music folders.", 1, musicFolderDao.getAllMusicFolders().size()); + + musicFolderDao.deleteMusicFolder(musicFolderDao.getAllMusicFolders().get(0).getId()); + assertEquals("Wrong number of music folders.", 0, musicFolderDao.getAllMusicFolders().size()); + } + + private void assertMusicFolderEquals(MusicFolder expected, MusicFolder actual) { + assertEquals("Wrong name.", expected.getName(), actual.getName()); + assertEquals("Wrong path.", expected.getPath(), actual.getPath()); + assertEquals("Wrong enabled state.", expected.isEnabled(), actual.isEnabled()); + assertEquals("Wrong changed date.", expected.getChanged(), actual.getChanged()); + } + + +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/PlayerDaoTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/PlayerDaoTestCase.java new file mode 100644 index 00000000..9bf949f5 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/PlayerDaoTestCase.java @@ -0,0 +1,165 @@ +package net.sourceforge.subsonic.dao; + +import java.util.Date; +import java.util.List; + +import net.sourceforge.subsonic.domain.CoverArtScheme; +import net.sourceforge.subsonic.domain.Player; +import net.sourceforge.subsonic.domain.PlayerTechnology; +import net.sourceforge.subsonic.domain.PlayQueue; +import net.sourceforge.subsonic.domain.TranscodeScheme; + +/** + * Unit test of {@link PlayerDao}. + * + * @author Sindre Mehus + */ +public class PlayerDaoTestCase extends DaoTestCaseBase { + + @Override + protected void setUp() throws Exception { + getJdbcTemplate().execute("delete from player"); + } + + public void testCreatePlayer() { + Player player = new Player(); + player.setName("name"); + player.setType("type"); + player.setUsername("username"); + player.setIpAddress("ipaddress"); + player.setDynamicIp(false); + player.setAutoControlEnabled(false); + player.setTechnology(PlayerTechnology.EXTERNAL_WITH_PLAYLIST); + player.setClientId("android"); + player.setLastSeen(new Date()); + player.setCoverArtScheme(CoverArtScheme.LARGE); + player.setTranscodeScheme(TranscodeScheme.MAX_160); + + playerDao.createPlayer(player); + Player newPlayer = playerDao.getAllPlayers().get(0); + assertPlayerEquals(player, newPlayer); + + Player newPlayer2 = playerDao.getPlayerById(newPlayer.getId()); + assertPlayerEquals(player, newPlayer2); + } + + public void testDefaultValues() { + playerDao.createPlayer(new Player()); + Player player = playerDao.getAllPlayers().get(0); + + assertTrue("Player should have dynamic IP by default.", player.isDynamicIp()); + assertTrue("Player should be auto-controlled by default.", player.isAutoControlEnabled()); + assertNull("Player client ID should be null by default.", player.getClientId()); + } + + public void testIdentity() { + Player player = new Player(); + + playerDao.createPlayer(player); + assertEquals("Wrong ID", "1", player.getId()); + assertEquals("Wrong number of players.", 1, playerDao.getAllPlayers().size()); + + playerDao.createPlayer(player); + assertEquals("Wrong ID", "2", player.getId()); + assertEquals("Wrong number of players.", 2, playerDao.getAllPlayers().size()); + + playerDao.createPlayer(player); + assertEquals("Wrong ID", "3", player.getId()); + assertEquals("Wrong number of players.", 3, playerDao.getAllPlayers().size()); + + playerDao.deletePlayer("3"); + playerDao.createPlayer(player); + assertEquals("Wrong ID", "3", player.getId()); + assertEquals("Wrong number of players.", 3, playerDao.getAllPlayers().size()); + + playerDao.deletePlayer("2"); + playerDao.createPlayer(player); + assertEquals("Wrong ID", "4", player.getId()); + assertEquals("Wrong number of players.", 3, playerDao.getAllPlayers().size()); + } + + public void testPlaylist() { + Player player = new Player(); + playerDao.createPlayer(player); + PlayQueue playQueue = player.getPlayQueue(); + assertNotNull("Missing playlist.", playQueue); + + playerDao.deletePlayer(player.getId()); + playerDao.createPlayer(player); + assertNotSame("Wrong playlist.", playQueue, player.getPlayQueue()); + } + + public void testGetPlayersForUserAndClientId() { + Player player = new Player(); + player.setUsername("sindre"); + playerDao.createPlayer(player); + player = playerDao.getAllPlayers().get(0); + + List<Player> players = playerDao.getPlayersForUserAndClientId("sindre", null); + assertFalse("Error in getPlayersForUserAndClientId().", players.isEmpty()); + assertPlayerEquals(player, players.get(0)); + assertTrue("Error in getPlayersForUserAndClientId().", playerDao.getPlayersForUserAndClientId("sindre", "foo").isEmpty()); + + player.setClientId("foo"); + playerDao.updatePlayer(player); + + players = playerDao.getPlayersForUserAndClientId("sindre", null); + assertTrue("Error in getPlayersForUserAndClientId().", players.isEmpty()); + players = playerDao.getPlayersForUserAndClientId("sindre", "foo"); + assertFalse("Error in getPlayersForUserAndClientId().", players.isEmpty()); + assertPlayerEquals(player, players.get(0)); + } + + public void testUpdatePlayer() { + Player player = new Player(); + playerDao.createPlayer(player); + assertPlayerEquals(player, playerDao.getAllPlayers().get(0)); + + player.setName("name"); + player.setType("Winamp"); + player.setTechnology(PlayerTechnology.WEB); + player.setClientId("foo"); + player.setUsername("username"); + player.setIpAddress("ipaddress"); + player.setDynamicIp(true); + player.setAutoControlEnabled(false); + player.setLastSeen(new Date()); + player.setCoverArtScheme(CoverArtScheme.LARGE); + player.setTranscodeScheme(TranscodeScheme.MAX_160); + + playerDao.updatePlayer(player); + Player newPlayer = playerDao.getAllPlayers().get(0); + assertPlayerEquals(player, newPlayer); + } + + public void testDeletePlayer() { + assertEquals("Wrong number of players.", 0, playerDao.getAllPlayers().size()); + + playerDao.createPlayer(new Player()); + assertEquals("Wrong number of players.", 1, playerDao.getAllPlayers().size()); + + playerDao.createPlayer(new Player()); + assertEquals("Wrong number of players.", 2, playerDao.getAllPlayers().size()); + + playerDao.deletePlayer("1"); + assertEquals("Wrong number of players.", 1, playerDao.getAllPlayers().size()); + + playerDao.deletePlayer("2"); + assertEquals("Wrong number of players.", 0, playerDao.getAllPlayers().size()); + } + + private void assertPlayerEquals(Player expected, Player actual) { + assertEquals("Wrong ID.", expected.getId(), actual.getId()); + assertEquals("Wrong name.", expected.getName(), actual.getName()); + assertEquals("Wrong technology.", expected.getTechnology(), actual.getTechnology()); + assertEquals("Wrong client ID.", expected.getClientId(), actual.getClientId()); + assertEquals("Wrong type.", expected.getType(), actual.getType()); + assertEquals("Wrong username.", expected.getUsername(), actual.getUsername()); + assertEquals("Wrong IP address.", expected.getIpAddress(), actual.getIpAddress()); + assertEquals("Wrong dynamic IP.", expected.isDynamicIp(), actual.isDynamicIp()); + assertEquals("Wrong auto control enabled.", expected.isAutoControlEnabled(), actual.isAutoControlEnabled()); + assertEquals("Wrong last seen.", expected.getLastSeen(), actual.getLastSeen()); + assertEquals("Wrong cover art scheme.", expected.getCoverArtScheme(), actual.getCoverArtScheme()); + assertEquals("Wrong transcode scheme.", expected.getTranscodeScheme(), actual.getTranscodeScheme()); + } +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/PodcastDaoTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/PodcastDaoTestCase.java new file mode 100644 index 00000000..f5952c3e --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/PodcastDaoTestCase.java @@ -0,0 +1,214 @@ +package net.sourceforge.subsonic.dao; + +import java.util.Date; +import java.util.List; + +import net.sourceforge.subsonic.domain.PodcastChannel; +import net.sourceforge.subsonic.domain.PodcastEpisode; +import net.sourceforge.subsonic.domain.PodcastStatus; + +/** + * Unit test of {@link PodcastDao}. + * + * @author Sindre Mehus + */ +public class PodcastDaoTestCase extends DaoTestCaseBase { + + @Override + protected void setUp() throws Exception { + getJdbcTemplate().execute("delete from podcast_channel"); + } + + public void testCreateChannel() { + PodcastChannel channel = new PodcastChannel("http://foo"); + podcastDao.createChannel(channel); + + PodcastChannel newChannel = podcastDao.getAllChannels().get(0); + assertNotNull("Wrong ID.", newChannel.getId()); + assertChannelEquals(channel, newChannel); + } + + public void testChannelId() { + int channelId = podcastDao.createChannel(new PodcastChannel("http://foo")); + + assertEquals("Error in createChannel.", channelId + 1, podcastDao.createChannel(new PodcastChannel("http://foo"))); + assertEquals("Error in createChannel.", channelId + 2, podcastDao.createChannel(new PodcastChannel("http://foo"))); + assertEquals("Error in createChannel.", channelId + 3, podcastDao.createChannel(new PodcastChannel("http://foo"))); + + podcastDao.deleteChannel(channelId + 1); + assertEquals("Error in createChannel.", channelId + 4, podcastDao.createChannel(new PodcastChannel("http://foo"))); + + podcastDao.deleteChannel(channelId + 4); + assertEquals("Error in createChannel.", channelId + 5, podcastDao.createChannel(new PodcastChannel("http://foo"))); + } + + public void testUpdateChannel() { + PodcastChannel channel = new PodcastChannel("http://foo"); + podcastDao.createChannel(channel); + channel = podcastDao.getAllChannels().get(0); + + channel.setUrl("http://bar"); + channel.setTitle("Title"); + channel.setDescription("Description"); + channel.setStatus(PodcastStatus.ERROR); + channel.setErrorMessage("Something went terribly wrong."); + + podcastDao.updateChannel(channel); + PodcastChannel newChannel = podcastDao.getAllChannels().get(0); + + assertEquals("Wrong ID.", channel.getId(), newChannel.getId()); + assertChannelEquals(channel, newChannel); + } + + public void testDeleteChannel() { + assertEquals("Wrong number of channels.", 0, podcastDao.getAllChannels().size()); + + PodcastChannel channel = new PodcastChannel("http://foo"); + podcastDao.createChannel(channel); + assertEquals("Wrong number of channels.", 1, podcastDao.getAllChannels().size()); + + podcastDao.createChannel(channel); + assertEquals("Wrong number of channels.", 2, podcastDao.getAllChannels().size()); + + podcastDao.deleteChannel(podcastDao.getAllChannels().get(0).getId()); + assertEquals("Wrong number of channels.", 1, podcastDao.getAllChannels().size()); + + podcastDao.deleteChannel(podcastDao.getAllChannels().get(0).getId()); + assertEquals("Wrong number of channels.", 0, podcastDao.getAllChannels().size()); + } + + public void testCreateEpisode() { + int channelId = createChannel(); + PodcastEpisode episode = new PodcastEpisode(null, channelId, "http://bar", "path", "title", "description", + new Date(), "12:34", null, null, PodcastStatus.NEW, null); + podcastDao.createEpisode(episode); + + PodcastEpisode newEpisode = podcastDao.getEpisodes(channelId).get(0); + assertNotNull("Wrong ID.", newEpisode.getId()); + assertEpisodeEquals(episode, newEpisode); + } + + public void testGetEpisode() { + assertNull("Error in getEpisode()", podcastDao.getEpisode(23)); + + int channelId = createChannel(); + PodcastEpisode episode = new PodcastEpisode(null, channelId, "http://bar", "path", "title", "description", + new Date(), "12:34", 3276213L, 2341234L, PodcastStatus.NEW, "error"); + podcastDao.createEpisode(episode); + + int episodeId = podcastDao.getEpisodes(channelId).get(0).getId(); + PodcastEpisode newEpisode = podcastDao.getEpisode(episodeId); + assertEpisodeEquals(episode, newEpisode); + } + + public void testGetEpisodes() { + int channelId = createChannel(); + PodcastEpisode a = new PodcastEpisode(null, channelId, "a", null, null, null, + new Date(3000), null, null, null, PodcastStatus.NEW, null); + PodcastEpisode b = new PodcastEpisode(null, channelId, "b", null, null, null, + new Date(1000), null, null, null, PodcastStatus.NEW, "error"); + PodcastEpisode c = new PodcastEpisode(null, channelId, "c", null, null, null, + new Date(2000), null, null, null, PodcastStatus.NEW, null); + PodcastEpisode d = new PodcastEpisode(null, channelId, "c", null, null, null, + null, null, null, null, PodcastStatus.NEW, ""); + podcastDao.createEpisode(a); + podcastDao.createEpisode(b); + podcastDao.createEpisode(c); + podcastDao.createEpisode(d); + + List<PodcastEpisode> episodes = podcastDao.getEpisodes(channelId); + assertEquals("Error in getEpisodes().", 4, episodes.size()); + assertEpisodeEquals(a, episodes.get(0)); + assertEpisodeEquals(c, episodes.get(1)); + assertEpisodeEquals(b, episodes.get(2)); + assertEpisodeEquals(d, episodes.get(3)); + } + + + public void testUpdateEpisode() { + int channelId = createChannel(); + PodcastEpisode episode = new PodcastEpisode(null, channelId, "http://bar", null, null, null, + null, null, null, null, PodcastStatus.NEW, null); + podcastDao.createEpisode(episode); + episode = podcastDao.getEpisodes(channelId).get(0); + + episode.setUrl("http://bar"); + episode.setPath("c:/tmp"); + episode.setTitle("Title"); + episode.setDescription("Description"); + episode.setPublishDate(new Date()); + episode.setDuration("1:20"); + episode.setBytesTotal(87628374612L); + episode.setBytesDownloaded(9086L); + episode.setStatus(PodcastStatus.DOWNLOADING); + episode.setErrorMessage("Some error"); + + podcastDao.updateEpisode(episode); + PodcastEpisode newEpisode = podcastDao.getEpisodes(channelId).get(0); + assertEquals("Wrong ID.", episode.getId(), newEpisode.getId()); + assertEpisodeEquals(episode, newEpisode); + } + + public void testDeleteEpisode() { + int channelId = createChannel(); + + assertEquals("Wrong number of episodes.", 0, podcastDao.getEpisodes(channelId).size()); + + PodcastEpisode episode = new PodcastEpisode(null, channelId, "http://bar", null, null, null, + null, null, null, null, PodcastStatus.NEW, null); + + podcastDao.createEpisode(episode); + assertEquals("Wrong number of episodes.", 1, podcastDao.getEpisodes(channelId).size()); + + podcastDao.createEpisode(episode); + assertEquals("Wrong number of episodes.", 2, podcastDao.getEpisodes(channelId).size()); + + podcastDao.deleteEpisode(podcastDao.getEpisodes(channelId).get(0).getId()); + assertEquals("Wrong number of episodes.", 1, podcastDao.getEpisodes(channelId).size()); + + podcastDao.deleteEpisode(podcastDao.getEpisodes(channelId).get(0).getId()); + assertEquals("Wrong number of episodes.", 0, podcastDao.getEpisodes(channelId).size()); + } + + + public void testCascadingDelete() { + int channelId = createChannel(); + PodcastEpisode episode = new PodcastEpisode(null, channelId, "http://bar", null, null, null, + null, null, null, null, PodcastStatus.NEW, null); + podcastDao.createEpisode(episode); + podcastDao.createEpisode(episode); + assertEquals("Wrong number of episodes.", 2, podcastDao.getEpisodes(channelId).size()); + + podcastDao.deleteChannel(channelId); + assertEquals("Wrong number of episodes.", 0, podcastDao.getEpisodes(channelId).size()); + } + + private int createChannel() { + PodcastChannel channel = new PodcastChannel("http://foo"); + podcastDao.createChannel(channel); + channel = podcastDao.getAllChannels().get(0); + return channel.getId(); + } + + private void assertChannelEquals(PodcastChannel expected, PodcastChannel actual) { + assertEquals("Wrong URL.", expected.getUrl(), actual.getUrl()); + assertEquals("Wrong title.", expected.getTitle(), actual.getTitle()); + assertEquals("Wrong description.", expected.getDescription(), actual.getDescription()); + assertSame("Wrong status.", expected.getStatus(), actual.getStatus()); + assertEquals("Wrong error message.", expected.getErrorMessage(), actual.getErrorMessage()); + } + + private void assertEpisodeEquals(PodcastEpisode expected, PodcastEpisode actual) { + assertEquals("Wrong URL.", expected.getUrl(), actual.getUrl()); + assertEquals("Wrong path.", expected.getPath(), actual.getPath()); + assertEquals("Wrong title.", expected.getTitle(), actual.getTitle()); + assertEquals("Wrong description.", expected.getDescription(), actual.getDescription()); + assertEquals("Wrong date.", expected.getPublishDate(), actual.getPublishDate()); + assertEquals("Wrong duration.", expected.getDuration(), actual.getDuration()); + assertEquals("Wrong bytes total.", expected.getBytesTotal(), actual.getBytesTotal()); + assertEquals("Wrong bytes downloaded.", expected.getBytesDownloaded(), actual.getBytesDownloaded()); + assertSame("Wrong status.", expected.getStatus(), actual.getStatus()); + assertEquals("Wrong error message.", expected.getErrorMessage(), actual.getErrorMessage()); + } + +} diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/TranscodingDaoTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/TranscodingDaoTestCase.java new file mode 100644 index 00000000..9cf4441b --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/TranscodingDaoTestCase.java @@ -0,0 +1,133 @@ +package net.sourceforge.subsonic.dao; + +import java.util.List; + +import net.sourceforge.subsonic.domain.Player; +import net.sourceforge.subsonic.domain.Transcoding; + +/** + * Unit test of {@link TranscodingDao}. + * + * @author Sindre Mehus + */ +public class TranscodingDaoTestCase extends DaoTestCaseBase { + + @Override + protected void setUp() throws Exception { + getJdbcTemplate().execute("delete from transcoding2"); + } + + public void testCreateTranscoding() { + Transcoding transcoding = new Transcoding(null, "name", "sourceFormats", "targetFormat", "step1", "step2", "step3", false); + transcodingDao.createTranscoding(transcoding); + + Transcoding newTranscoding = transcodingDao.getAllTranscodings().get(0); + assertTranscodingEquals(transcoding, newTranscoding); + } + + public void testUpdateTranscoding() { + Transcoding transcoding = new Transcoding(null, "name", "sourceFormats", "targetFormat", "step1", "step2", "step3", false); + transcodingDao.createTranscoding(transcoding); + transcoding = transcodingDao.getAllTranscodings().get(0); + + transcoding.setName("newName"); + transcoding.setSourceFormats("newSourceFormats"); + transcoding.setTargetFormat("newTargetFormats"); + transcoding.setStep1("newStep1"); + transcoding.setStep2("newStep2"); + transcoding.setStep3("newStep3"); + transcoding.setDefaultActive(true); + transcodingDao.updateTranscoding(transcoding); + + Transcoding newTranscoding = transcodingDao.getAllTranscodings().get(0); + assertTranscodingEquals(transcoding, newTranscoding); + } + + public void testDeleteTranscoding() { + assertEquals("Wrong number of transcodings.", 0, transcodingDao.getAllTranscodings().size()); + + transcodingDao.createTranscoding(new Transcoding(null, "name", "sourceFormats", "targetFormat", "step1", "step2", "step3", true)); + assertEquals("Wrong number of transcodings.", 1, transcodingDao.getAllTranscodings().size()); + + transcodingDao.createTranscoding(new Transcoding(null, "name", "sourceFormats", "targetFormat", "step1", "step2", "step3", true)); + assertEquals("Wrong number of transcodings.", 2, transcodingDao.getAllTranscodings().size()); + + transcodingDao.deleteTranscoding(transcodingDao.getAllTranscodings().get(0).getId()); + assertEquals("Wrong number of transcodings.", 1, transcodingDao.getAllTranscodings().size()); + + transcodingDao.deleteTranscoding(transcodingDao.getAllTranscodings().get(0).getId()); + assertEquals("Wrong number of transcodings.", 0, transcodingDao.getAllTranscodings().size()); + } + + public void testPlayerTranscoding() { + Player player = new Player(); + playerDao.createPlayer(player); + + transcodingDao.createTranscoding(new Transcoding(null, "name", "sourceFormats", "targetFormat", "step1", "step2", "step3", false)); + transcodingDao.createTranscoding(new Transcoding(null, "name", "sourceFormats", "targetFormat", "step1", "step2", "step3", false)); + transcodingDao.createTranscoding(new Transcoding(null, "name", "sourceFormats", "targetFormat", "step1", "step2", "step3", false)); + Transcoding transcodingA = transcodingDao.getAllTranscodings().get(0); + Transcoding transcodingB = transcodingDao.getAllTranscodings().get(1); + Transcoding transcodingC = transcodingDao.getAllTranscodings().get(2); + + List<Transcoding> activeTranscodings = transcodingDao.getTranscodingsForPlayer(player.getId()); + assertEquals("Wrong number of transcodings.", 0, activeTranscodings.size()); + + transcodingDao.setTranscodingsForPlayer(player.getId(), new int[]{transcodingA.getId()}); + activeTranscodings = transcodingDao.getTranscodingsForPlayer(player.getId()); + assertEquals("Wrong number of transcodings.", 1, activeTranscodings.size()); + assertTranscodingEquals(transcodingA, activeTranscodings.get(0)); + + transcodingDao.setTranscodingsForPlayer(player.getId(), new int[]{transcodingB.getId(), transcodingC.getId()}); + activeTranscodings = transcodingDao.getTranscodingsForPlayer(player.getId()); + assertEquals("Wrong number of transcodings.", 2, activeTranscodings.size()); + assertTranscodingEquals(transcodingB, activeTranscodings.get(0)); + assertTranscodingEquals(transcodingC, activeTranscodings.get(1)); + + transcodingDao.setTranscodingsForPlayer(player.getId(), new int[0]); + activeTranscodings = transcodingDao.getTranscodingsForPlayer(player.getId()); + assertEquals("Wrong number of transcodings.", 0, activeTranscodings.size()); + } + + public void testCascadingDeletePlayer() { + Player player = new Player(); + playerDao.createPlayer(player); + + transcodingDao.createTranscoding(new Transcoding(null, "name", "sourceFormats", "targetFormat", "step1", "step2", "step3", true)); + Transcoding transcoding = transcodingDao.getAllTranscodings().get(0); + + transcodingDao.setTranscodingsForPlayer(player.getId(), new int[]{transcoding.getId()}); + List<Transcoding> activeTranscodings = transcodingDao.getTranscodingsForPlayer(player.getId()); + assertEquals("Wrong number of transcodings.", 1, activeTranscodings.size()); + + playerDao.deletePlayer(player.getId()); + activeTranscodings = transcodingDao.getTranscodingsForPlayer(player.getId()); + assertEquals("Wrong number of transcodings.", 0, activeTranscodings.size()); + } + + public void testCascadingDeleteTranscoding() { + Player player = new Player(); + playerDao.createPlayer(player); + + transcodingDao.createTranscoding(new Transcoding(null, "name", "sourceFormats", "targetFormat", "step1", "step2", "step3", true)); + Transcoding transcoding = transcodingDao.getAllTranscodings().get(0); + + transcodingDao.setTranscodingsForPlayer(player.getId(), new int[]{transcoding.getId()}); + List<Transcoding> activeTranscodings = transcodingDao.getTranscodingsForPlayer(player.getId()); + assertEquals("Wrong number of transcodings.", 1, activeTranscodings.size()); + + transcodingDao.deleteTranscoding(transcoding.getId()); + activeTranscodings = transcodingDao.getTranscodingsForPlayer(player.getId()); + assertEquals("Wrong number of transcodings.", 0, activeTranscodings.size()); + } + + private void assertTranscodingEquals(Transcoding expected, Transcoding actual) { + assertEquals("Wrong name.", expected.getName(), actual.getName()); + assertEquals("Wrong source formats.", expected.getSourceFormats(), actual.getSourceFormats()); + assertEquals("Wrong target format.", expected.getTargetFormat(), actual.getTargetFormat()); + assertEquals("Wrong step 1.", expected.getStep1(), actual.getStep1()); + assertEquals("Wrong step 2.", expected.getStep2(), actual.getStep2()); + assertEquals("Wrong step 3.", expected.getStep3(), actual.getStep3()); + assertEquals("Wrong default active.", expected.isDefaultActive(), actual.isDefaultActive()); + } +} diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/UserDaoTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/UserDaoTestCase.java new file mode 100644 index 00000000..24dc9ec5 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/UserDaoTestCase.java @@ -0,0 +1,230 @@ +package net.sourceforge.subsonic.dao; + +import java.util.Date; +import java.util.Locale; + +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.core.JdbcTemplate; + +import net.sourceforge.subsonic.domain.AvatarScheme; +import net.sourceforge.subsonic.domain.TranscodeScheme; +import net.sourceforge.subsonic.domain.User; +import net.sourceforge.subsonic.domain.UserSettings; + +/** + * Unit test of {@link UserDao}. + * + * @author Sindre Mehus + */ +public class UserDaoTestCase extends DaoTestCaseBase { + + @Override + protected void setUp() throws Exception { + JdbcTemplate template = getJdbcTemplate(); + template.execute("delete from user_role"); + template.execute("delete from user"); + } + + public void testCreateUser() { + User user = new User("sindre", "secret", "sindre@activeobjects.no", false, 1000L, 2000L, 3000L); + user.setAdminRole(true); + user.setCommentRole(true); + user.setCoverArtRole(true); + user.setDownloadRole(false); + user.setPlaylistRole(true); + user.setUploadRole(false); + user.setPodcastRole(true); + user.setStreamRole(true); + user.setJukeboxRole(true); + user.setSettingsRole(true); + userDao.createUser(user); + + User newUser = userDao.getAllUsers().get(0); + assertUserEquals(user, newUser); + } + + public void testUpdateUser() { + User user = new User("sindre", "secret", null); + user.setAdminRole(true); + user.setCommentRole(true); + user.setCoverArtRole(true); + user.setDownloadRole(false); + user.setPlaylistRole(true); + user.setUploadRole(false); + user.setPodcastRole(true); + user.setStreamRole(true); + user.setJukeboxRole(true); + user.setSettingsRole(true); + userDao.createUser(user); + + user.setPassword("foo"); + user.setEmail("sindre@foo.bar"); + user.setLdapAuthenticated(true); + user.setBytesStreamed(1); + user.setBytesDownloaded(2); + user.setBytesUploaded(3); + user.setAdminRole(false); + user.setCommentRole(false); + user.setCoverArtRole(false); + user.setDownloadRole(true); + user.setPlaylistRole(false); + user.setUploadRole(true); + user.setPodcastRole(false); + user.setStreamRole(false); + user.setJukeboxRole(false); + user.setSettingsRole(false); + userDao.updateUser(user); + + User newUser = userDao.getAllUsers().get(0); + assertUserEquals(user, newUser); + assertEquals("Wrong bytes streamed.", 1, newUser.getBytesStreamed()); + assertEquals("Wrong bytes downloaded.", 2, newUser.getBytesDownloaded()); + assertEquals("Wrong bytes uploaded.", 3, newUser.getBytesUploaded()); + } + + public void testGetUserByName() { + User user = new User("sindre", "secret", null); + userDao.createUser(user); + + User newUser = userDao.getUserByName("sindre"); + assertNotNull("Error in getUserByName().", newUser); + assertUserEquals(user, newUser); + + assertNull("Error in getUserByName().", userDao.getUserByName("sindre2")); + assertNull("Error in getUserByName().", userDao.getUserByName("sindre ")); + assertNull("Error in getUserByName().", userDao.getUserByName("bente")); + assertNull("Error in getUserByName().", userDao.getUserByName("")); + assertNull("Error in getUserByName().", userDao.getUserByName(null)); + } + + public void testDeleteUser() { + assertEquals("Wrong number of users.", 0, userDao.getAllUsers().size()); + + userDao.createUser(new User("sindre", "secret", null)); + assertEquals("Wrong number of users.", 1, userDao.getAllUsers().size()); + + userDao.createUser(new User("bente", "secret", null)); + assertEquals("Wrong number of users.", 2, userDao.getAllUsers().size()); + + userDao.deleteUser("sindre"); + assertEquals("Wrong number of users.", 1, userDao.getAllUsers().size()); + + userDao.deleteUser("bente"); + assertEquals("Wrong number of users.", 0, userDao.getAllUsers().size()); + } + + public void testGetRolesForUser() { + User user = new User("sindre", "secret", null); + user.setAdminRole(true); + user.setCommentRole(true); + user.setPodcastRole(true); + user.setStreamRole(true); + user.setSettingsRole(true); + userDao.createUser(user); + + String[] roles = userDao.getRolesForUser("sindre"); + assertEquals("Wrong number of roles.", 5, roles.length); + assertEquals("Wrong role.", "admin", roles[0]); + assertEquals("Wrong role.", "comment", roles[1]); + assertEquals("Wrong role.", "podcast", roles[2]); + assertEquals("Wrong role.", "stream", roles[3]); + assertEquals("Wrong role.", "settings", roles[4]); + } + + public void testUserSettings() { + assertNull("Error in getUserSettings.", userDao.getUserSettings("sindre")); + + try { + userDao.updateUserSettings(new UserSettings("sindre")); + fail("Expected DataIntegrityViolationException."); + } catch (DataIntegrityViolationException x) { + } + + userDao.createUser(new User("sindre", "secret", null)); + assertNull("Error in getUserSettings.", userDao.getUserSettings("sindre")); + + userDao.updateUserSettings(new UserSettings("sindre")); + UserSettings userSettings = userDao.getUserSettings("sindre"); + assertNotNull("Error in getUserSettings().", userSettings); + assertNull("Error in getUserSettings().", userSettings.getLocale()); + assertNull("Error in getUserSettings().", userSettings.getThemeId()); + assertFalse("Error in getUserSettings().", userSettings.isFinalVersionNotificationEnabled()); + assertFalse("Error in getUserSettings().", userSettings.isBetaVersionNotificationEnabled()); + assertFalse("Error in getUserSettings().", userSettings.isLastFmEnabled()); + assertNull("Error in getUserSettings().", userSettings.getLastFmUsername()); + assertNull("Error in getUserSettings().", userSettings.getLastFmPassword()); + assertSame("Error in getUserSettings().", TranscodeScheme.OFF, userSettings.getTranscodeScheme()); + assertFalse("Error in getUserSettings().", userSettings.isShowNowPlayingEnabled()); + assertEquals("Error in getUserSettings().", -1, userSettings.getSelectedMusicFolderId()); + assertFalse("Error in getUserSettings().", userSettings.isPartyModeEnabled()); + assertFalse("Error in getUserSettings().", userSettings.isNowPlayingAllowed()); + assertSame("Error in getUserSettings().", AvatarScheme.NONE, userSettings.getAvatarScheme()); + assertNull("Error in getUserSettings().", userSettings.getSystemAvatarId()); + + UserSettings settings = new UserSettings("sindre"); + settings.setLocale(Locale.SIMPLIFIED_CHINESE); + settings.setThemeId("midnight"); + settings.setBetaVersionNotificationEnabled(true); + settings.getMainVisibility().setCaptionCutoff(42); + settings.getMainVisibility().setBitRateVisible(true); + settings.getPlaylistVisibility().setCaptionCutoff(44); + settings.getPlaylistVisibility().setYearVisible(true); + settings.setLastFmEnabled(true); + settings.setLastFmUsername("last_user"); + settings.setLastFmPassword("last_pass"); + settings.setTranscodeScheme(TranscodeScheme.MAX_192); + settings.setShowNowPlayingEnabled(false); + settings.setSelectedMusicFolderId(3); + settings.setPartyModeEnabled(true); + settings.setNowPlayingAllowed(true); + settings.setAvatarScheme(AvatarScheme.SYSTEM); + settings.setSystemAvatarId(1); + settings.setChanged(new Date(9412L)); + + userDao.updateUserSettings(settings); + userSettings = userDao.getUserSettings("sindre"); + assertNotNull("Error in getUserSettings().", userSettings); + assertEquals("Error in getUserSettings().", Locale.SIMPLIFIED_CHINESE, userSettings.getLocale()); + assertEquals("Error in getUserSettings().", false, userSettings.isFinalVersionNotificationEnabled()); + assertEquals("Error in getUserSettings().", true, userSettings.isBetaVersionNotificationEnabled()); + assertEquals("Error in getUserSettings().", "midnight", userSettings.getThemeId()); + assertEquals("Error in getUserSettings().", 42, userSettings.getMainVisibility().getCaptionCutoff()); + assertEquals("Error in getUserSettings().", true, userSettings.getMainVisibility().isBitRateVisible()); + assertEquals("Error in getUserSettings().", 44, userSettings.getPlaylistVisibility().getCaptionCutoff()); + assertEquals("Error in getUserSettings().", true, userSettings.getPlaylistVisibility().isYearVisible()); + assertEquals("Error in getUserSettings().", true, userSettings.isLastFmEnabled()); + assertEquals("Error in getUserSettings().", "last_user", userSettings.getLastFmUsername()); + assertEquals("Error in getUserSettings().", "last_pass", userSettings.getLastFmPassword()); + assertSame("Error in getUserSettings().", TranscodeScheme.MAX_192, userSettings.getTranscodeScheme()); + assertFalse("Error in getUserSettings().", userSettings.isShowNowPlayingEnabled()); + assertEquals("Error in getUserSettings().", 3, userSettings.getSelectedMusicFolderId()); + assertTrue("Error in getUserSettings().", userSettings.isPartyModeEnabled()); + assertTrue("Error in getUserSettings().", userSettings.isNowPlayingAllowed()); + assertSame("Error in getUserSettings().", AvatarScheme.SYSTEM, userSettings.getAvatarScheme()); + assertEquals("Error in getUserSettings().", 1, userSettings.getSystemAvatarId().intValue()); + assertEquals("Error in getUserSettings().", new Date(9412L), userSettings.getChanged()); + + userDao.deleteUser("sindre"); + assertNull("Error in cascading delete.", userDao.getUserSettings("sindre")); + } + + private void assertUserEquals(User expected, User actual) { + assertEquals("Wrong name.", expected.getUsername(), actual.getUsername()); + assertEquals("Wrong password.", expected.getPassword(), actual.getPassword()); + assertEquals("Wrong email.", expected.getEmail(), actual.getEmail()); + assertEquals("Wrong LDAP auth.", expected.isLdapAuthenticated(), actual.isLdapAuthenticated()); + assertEquals("Wrong bytes streamed.", expected.getBytesStreamed(), actual.getBytesStreamed()); + assertEquals("Wrong bytes downloaded.", expected.getBytesDownloaded(), actual.getBytesDownloaded()); + assertEquals("Wrong bytes uploaded.", expected.getBytesUploaded(), actual.getBytesUploaded()); + assertEquals("Wrong admin role.", expected.isAdminRole(), actual.isAdminRole()); + assertEquals("Wrong comment role.", expected.isCommentRole(), actual.isCommentRole()); + assertEquals("Wrong cover art role.", expected.isCoverArtRole(), actual.isCoverArtRole()); + assertEquals("Wrong download role.", expected.isDownloadRole(), actual.isDownloadRole()); + assertEquals("Wrong playlist role.", expected.isPlaylistRole(), actual.isPlaylistRole()); + assertEquals("Wrong upload role.", expected.isUploadRole(), actual.isUploadRole()); + assertEquals("Wrong upload role.", expected.isUploadRole(), actual.isUploadRole()); + assertEquals("Wrong stream role.", expected.isStreamRole(), actual.isStreamRole()); + assertEquals("Wrong jukebox role.", expected.isJukeboxRole(), actual.isJukeboxRole()); + assertEquals("Wrong settings role.", expected.isSettingsRole(), actual.isSettingsRole()); + } +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/CacheElementTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/CacheElementTestCase.java new file mode 100644 index 00000000..6c6e871a --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/CacheElementTestCase.java @@ -0,0 +1,44 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.domain; + +import junit.framework.TestCase; + +/** + * Unit test of {@link net.sourceforge.subsonic.domain.CacheElement}. + * + * @author Sindre Mehus + */ +public class CacheElementTestCase extends TestCase { + + public void testCreateId() { + + assertTrue(CacheElement.createId(1, "/Volumes/WD Passport/music/'Til Tuesday/Welcome Home") == + CacheElement.createId(1, "/Volumes/WD Passport/music/'Til Tuesday/Welcome Home")); + + assertTrue(CacheElement.createId(1, "/Volumes/WD Passport/music/'Til Tuesday/Welcome Home") != + CacheElement.createId(2, "/Volumes/WD Passport/music/'Til Tuesday/Welcome Home")); + + assertTrue(CacheElement.createId(237462763, "/Volumes/WD Passport/music/'Til Tuesday/Welcome Home") != + CacheElement.createId(28374922, "/Volumes/WD Passport/music/'Til Tuesday/Welcome Home")); + + assertTrue(CacheElement.createId(1, "/Volumes/WD Passport/music/'Til Tuesday/Welcome Home bla bla") != + CacheElement.createId(1, "/Volumes/WD Passport/music/'Til Tuesday/Welcome Home")); + } +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/MediaFileComparatorTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/MediaFileComparatorTestCase.java new file mode 100644 index 00000000..6e1047f4 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/MediaFileComparatorTestCase.java @@ -0,0 +1,124 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.domain; + +import junit.framework.TestCase; + +/** + * @author Sindre Mehus + * @version $Id$ + */ +public class MediaFileComparatorTestCase extends TestCase { + + private final MediaFileComparator comparator = new MediaFileComparator(true); + + public void testCompareAlbums() throws Exception { + + MediaFile albumA2012 = new MediaFile(); + albumA2012.setMediaType(MediaFile.MediaType.ALBUM); + albumA2012.setPath("a"); + albumA2012.setYear(2012); + + MediaFile albumB2012 = new MediaFile(); + albumB2012.setMediaType(MediaFile.MediaType.ALBUM); + albumB2012.setPath("b"); + albumB2012.setYear(2012); + + MediaFile album2013 = new MediaFile(); + album2013.setMediaType(MediaFile.MediaType.ALBUM); + album2013.setPath("c"); + album2013.setYear(2013); + + MediaFile albumWithoutYear = new MediaFile(); + albumWithoutYear.setMediaType(MediaFile.MediaType.ALBUM); + albumWithoutYear.setPath("c"); + + assertEquals(0, comparator.compare(albumWithoutYear, albumWithoutYear)); + assertEquals(0, comparator.compare(albumA2012, albumA2012)); + + assertEquals(-1, comparator.compare(albumA2012, albumWithoutYear)); + assertEquals(-1, comparator.compare(album2013, albumWithoutYear)); + assertEquals(1, comparator.compare(album2013, albumA2012)); + + assertEquals(1, comparator.compare(albumWithoutYear, albumA2012)); + assertEquals(1, comparator.compare(albumWithoutYear, album2013)); + assertEquals(-1, comparator.compare(albumA2012, album2013)); + + assertEquals(-1, comparator.compare(albumA2012, albumB2012)); + assertEquals(1, comparator.compare(albumB2012, albumA2012)); + } + + public void testCompareDiscNumbers() throws Exception { + + MediaFile discXtrack1 = new MediaFile(); + discXtrack1.setMediaType(MediaFile.MediaType.MUSIC); + discXtrack1.setPath("a"); + discXtrack1.setTrackNumber(1); + + MediaFile discXtrack2 = new MediaFile(); + discXtrack2.setMediaType(MediaFile.MediaType.MUSIC); + discXtrack2.setPath("a"); + discXtrack2.setTrackNumber(2); + + MediaFile disc5track1 = new MediaFile(); + disc5track1.setMediaType(MediaFile.MediaType.MUSIC); + disc5track1.setPath("a"); + disc5track1.setDiscNumber(5); + disc5track1.setTrackNumber(1); + + MediaFile disc5track2 = new MediaFile(); + disc5track2.setMediaType(MediaFile.MediaType.MUSIC); + disc5track2.setPath("a"); + disc5track2.setDiscNumber(5); + disc5track2.setTrackNumber(2); + + MediaFile disc6track1 = new MediaFile(); + disc6track1.setMediaType(MediaFile.MediaType.MUSIC); + disc6track1.setPath("a"); + disc6track1.setDiscNumber(6); + disc6track1.setTrackNumber(1); + + MediaFile disc6track2 = new MediaFile(); + disc6track2.setMediaType(MediaFile.MediaType.MUSIC); + disc6track2.setPath("a"); + disc6track2.setDiscNumber(6); + disc6track2.setTrackNumber(2); + + assertEquals(0, comparator.compare(discXtrack1, discXtrack1)); + assertEquals(0, comparator.compare(disc5track1, disc5track1)); + + assertEquals(-1, comparator.compare(discXtrack1, discXtrack2)); + assertEquals(1, comparator.compare(discXtrack2, discXtrack1)); + + assertEquals(-1, comparator.compare(disc5track1, disc5track2)); + assertEquals(1, comparator.compare(disc6track2, disc5track1)); + + assertEquals(-1, comparator.compare(disc5track1, disc6track1)); + assertEquals(1, comparator.compare(disc6track1, disc5track1)); + + assertEquals(-1, comparator.compare(disc5track2, disc6track1)); + assertEquals(1, comparator.compare(disc6track1, disc5track2)); + + assertEquals(-1, comparator.compare(discXtrack1, disc5track1)); + assertEquals(1, comparator.compare(disc5track1, discXtrack1)); + + assertEquals(-1, comparator.compare(discXtrack1, disc5track2)); + assertEquals(1, comparator.compare(disc5track2, discXtrack1)); + } +} diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/PlayQueueTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/PlayQueueTestCase.java new file mode 100644 index 00000000..07b4be57 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/PlayQueueTestCase.java @@ -0,0 +1,311 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.domain; + +import java.io.File; +import java.io.IOException; + +import junit.framework.TestCase; +import net.sourceforge.subsonic.domain.PlayQueue.SortOrder; +import net.sourceforge.subsonic.domain.PlayQueue.Status; + +/** + * Unit test of {@link PlayQueue}. + * + * @author Sindre Mehus + */ +public class PlayQueueTestCase extends TestCase { + + public void testEmpty() { + PlayQueue playQueue = new PlayQueue(); + assertEquals(0, playQueue.size()); + assertTrue(playQueue.isEmpty()); + assertEquals(0, playQueue.getFiles().size()); + assertNull(playQueue.getCurrentFile()); + } + + public void testStatus() throws Exception { + PlayQueue playQueue = new PlayQueue(); + assertEquals(Status.PLAYING, playQueue.getStatus()); + + playQueue.setStatus(Status.STOPPED); + assertEquals(Status.STOPPED, playQueue.getStatus()); + + playQueue.addFiles(true, new TestMediaFile()); + assertEquals(Status.PLAYING, playQueue.getStatus()); + + playQueue.clear(); + assertEquals(Status.PLAYING, playQueue.getStatus()); + } + + public void testMoveUp() throws Exception { + PlayQueue playQueue = createPlaylist(0, "A", "B", "C", "D"); + playQueue.moveUp(0); + assertPlaylistEquals(playQueue, 0, "A", "B", "C", "D"); + + playQueue = createPlaylist(0, "A", "B", "C", "D"); + playQueue.moveUp(9999); + assertPlaylistEquals(playQueue, 0, "A", "B", "C", "D"); + + playQueue = createPlaylist(1, "A", "B", "C", "D"); + playQueue.moveUp(1); + assertPlaylistEquals(playQueue, 0, "B", "A", "C", "D"); + + playQueue = createPlaylist(3, "A", "B", "C", "D"); + playQueue.moveUp(3); + assertPlaylistEquals(playQueue, 2, "A", "B", "D", "C"); + } + + public void testMoveDown() throws Exception { + PlayQueue playQueue = createPlaylist(0, "A", "B", "C", "D"); + playQueue.moveDown(0); + assertPlaylistEquals(playQueue, 1, "B", "A", "C", "D"); + + playQueue = createPlaylist(0, "A", "B", "C", "D"); + playQueue.moveDown(9999); + assertPlaylistEquals(playQueue, 0, "A", "B", "C", "D"); + + playQueue = createPlaylist(1, "A", "B", "C", "D"); + playQueue.moveDown(1); + assertPlaylistEquals(playQueue, 2, "A", "C", "B", "D"); + + playQueue = createPlaylist(3, "A", "B", "C", "D"); + playQueue.moveDown(3); + assertPlaylistEquals(playQueue, 3, "A", "B", "C", "D"); + } + + public void testRemove() throws Exception { + PlayQueue playQueue = createPlaylist(0, "A", "B", "C", "D"); + playQueue.removeFileAt(0); + assertPlaylistEquals(playQueue, 0, "B", "C", "D"); + + playQueue = createPlaylist(1, "A", "B", "C", "D"); + playQueue.removeFileAt(0); + assertPlaylistEquals(playQueue, 0, "B", "C", "D"); + + playQueue = createPlaylist(0, "A", "B", "C", "D"); + playQueue.removeFileAt(3); + assertPlaylistEquals(playQueue, 0, "A", "B", "C"); + + playQueue = createPlaylist(1, "A", "B", "C", "D"); + playQueue.removeFileAt(1); + assertPlaylistEquals(playQueue, 1, "A", "C", "D"); + + playQueue = createPlaylist(3, "A", "B", "C", "D"); + playQueue.removeFileAt(3); + assertPlaylistEquals(playQueue, 2, "A", "B", "C"); + + playQueue = createPlaylist(0, "A"); + playQueue.removeFileAt(0); + assertPlaylistEquals(playQueue, -1); + } + + public void testNext() throws Exception { + PlayQueue playQueue = createPlaylist(0, "A", "B", "C"); + assertFalse(playQueue.isRepeatEnabled()); + playQueue.next(); + assertPlaylistEquals(playQueue, 1, "A", "B", "C"); + playQueue.next(); + assertPlaylistEquals(playQueue, 2, "A", "B", "C"); + playQueue.next(); + assertPlaylistEquals(playQueue, -1, "A", "B", "C"); + + playQueue = createPlaylist(0, "A", "B", "C"); + playQueue.setRepeatEnabled(true); + assertTrue(playQueue.isRepeatEnabled()); + playQueue.next(); + assertPlaylistEquals(playQueue, 1, "A", "B", "C"); + playQueue.next(); + assertPlaylistEquals(playQueue, 2, "A", "B", "C"); + playQueue.next(); + assertPlaylistEquals(playQueue, 0, "A", "B", "C"); + } + + public void testPlayAfterEndReached() throws Exception { + PlayQueue playQueue = createPlaylist(2, "A", "B", "C"); + playQueue.setStatus(Status.PLAYING); + playQueue.next(); + assertNull(playQueue.getCurrentFile()); + assertEquals(Status.STOPPED, playQueue.getStatus()); + + playQueue.setStatus(Status.PLAYING); + assertEquals(Status.PLAYING, playQueue.getStatus()); + assertEquals(0, playQueue.getIndex()); + assertEquals("A", playQueue.getCurrentFile().getName()); + } + + public void testAppend() throws Exception { + PlayQueue playQueue = createPlaylist(1, "A", "B", "C"); + + playQueue.addFiles(true, new TestMediaFile("D")); + assertPlaylistEquals(playQueue, 1, "A", "B", "C", "D"); + + playQueue.addFiles(false, new TestMediaFile("E")); + assertPlaylistEquals(playQueue, 0, "E"); + } + + public void testUndo() throws Exception { + PlayQueue playQueue = createPlaylist(0, "A", "B", "C"); + playQueue.setIndex(2); + playQueue.undo(); + assertPlaylistEquals(playQueue, 0, "A", "B", "C"); + + playQueue.removeFileAt(2); + playQueue.undo(); + assertPlaylistEquals(playQueue, 0, "A", "B", "C"); + + playQueue.clear(); + playQueue.undo(); + assertPlaylistEquals(playQueue, 0, "A", "B", "C"); + + playQueue.addFiles(true, new TestMediaFile()); + playQueue.undo(); + assertPlaylistEquals(playQueue, 0, "A", "B", "C"); + + playQueue.moveDown(1); + playQueue.undo(); + assertPlaylistEquals(playQueue, 0, "A", "B", "C"); + + playQueue.moveUp(1); + playQueue.undo(); + assertPlaylistEquals(playQueue, 0, "A", "B", "C"); + } + + public void testOrder() throws IOException { + PlayQueue playQueue = new PlayQueue(); + playQueue.addFiles(true, new TestMediaFile(2, "Artist A", "Album B")); + playQueue.addFiles(true, new TestMediaFile(1, "Artist C", "Album C")); + playQueue.addFiles(true, new TestMediaFile(3, "Artist B", "Album A")); + playQueue.addFiles(true, new TestMediaFile(null, "Artist D", "Album D")); + playQueue.setIndex(2); + assertEquals("Error in sort.", new Integer(3), playQueue.getCurrentFile().getTrackNumber()); + + // Order by track. + playQueue.sort(SortOrder.TRACK); + assertEquals("Error in sort().", null, playQueue.getFile(0).getTrackNumber()); + assertEquals("Error in sort().", new Integer(1), playQueue.getFile(1).getTrackNumber()); + assertEquals("Error in sort().", new Integer(2), playQueue.getFile(2).getTrackNumber()); + assertEquals("Error in sort().", new Integer(3), playQueue.getFile(3).getTrackNumber()); + assertEquals("Error in sort().", new Integer(3), playQueue.getCurrentFile().getTrackNumber()); + + // Order by artist. + playQueue.sort(SortOrder.ARTIST); + assertEquals("Error in sort().", "Artist A", playQueue.getFile(0).getArtist()); + assertEquals("Error in sort().", "Artist B", playQueue.getFile(1).getArtist()); + assertEquals("Error in sort().", "Artist C", playQueue.getFile(2).getArtist()); + assertEquals("Error in sort().", "Artist D", playQueue.getFile(3).getArtist()); + assertEquals("Error in sort().", new Integer(3), playQueue.getCurrentFile().getTrackNumber()); + + // Order by album. + playQueue.sort(SortOrder.ALBUM); + assertEquals("Error in sort().", "Album A", playQueue.getFile(0).getAlbumName()); + assertEquals("Error in sort().", "Album B", playQueue.getFile(1).getAlbumName()); + assertEquals("Error in sort().", "Album C", playQueue.getFile(2).getAlbumName()); + assertEquals("Error in sort().", "Album D", playQueue.getFile(3).getAlbumName()); + assertEquals("Error in sort().", new Integer(3), playQueue.getCurrentFile().getTrackNumber()); + } + + private void assertPlaylistEquals(PlayQueue playQueue, int index, String... songs) { + assertEquals(songs.length, playQueue.size()); + for (int i = 0; i < songs.length; i++) { + assertEquals(songs[i], playQueue.getFiles().get(i).getName()); + } + + if (index == -1) { + assertNull(playQueue.getCurrentFile()); + } else { + assertEquals(songs[index], playQueue.getCurrentFile().getName()); + } + } + + private PlayQueue createPlaylist(int index, String... songs) throws Exception { + PlayQueue playQueue = new PlayQueue(); + for (String song : songs) { + playQueue.addFiles(true, new TestMediaFile(song)); + } + playQueue.setIndex(index); + return playQueue; + } + + private static class TestMediaFile extends MediaFile { + + private String name; + private Integer track; + private String album; + private String artist; + + TestMediaFile() { + } + + TestMediaFile(String name) { + this.name = name; + } + + TestMediaFile(Integer track, String artist, String album) { + this.track = track; + this.album = album; + this.artist = artist; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isFile() { + return true; + } + + @Override + public Integer getTrackNumber() { + return track; + } + + @Override + public String getArtist() { + return artist; + } + + @Override + public String getAlbumName() { + return album; + } + + @Override + public File getFile() { + return new File(name); + } + + @Override + public boolean exists() { + return true; + } + + @Override + public boolean isDirectory() { + return false; + } + + @Override + public boolean equals(Object o) { + return this == o; + } + } +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/TranscodeSchemeTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/TranscodeSchemeTestCase.java new file mode 100644 index 00000000..634ac41c --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/TranscodeSchemeTestCase.java @@ -0,0 +1,43 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.domain; + +import junit.framework.TestCase; +import static net.sourceforge.subsonic.domain.TranscodeScheme.*; + +/** + * Unit test of {@link TranscodeScheme}. + * + * @author Sindre Mehus + */ +public class TranscodeSchemeTestCase extends TestCase { + + /** + * Tests {@link TranscodeScheme#strictest}. + */ + public void testStrictest() { + assertSame("Error in strictest().", OFF, OFF.strictest(null)); + assertSame("Error in strictest().", OFF, OFF.strictest(OFF)); + assertSame("Error in strictest().", MAX_32, OFF.strictest(MAX_32)); + assertSame("Error in strictest().", MAX_32, MAX_32.strictest(null)); + assertSame("Error in strictest().", MAX_32, MAX_32.strictest(OFF)); + assertSame("Error in strictest().", MAX_32, MAX_32.strictest(MAX_64)); + assertSame("Error in strictest().", MAX_32, MAX_64.strictest(MAX_32)); + } +} diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/VersionTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/VersionTestCase.java new file mode 100644 index 00000000..79a8bfdf --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/domain/VersionTestCase.java @@ -0,0 +1,70 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.domain; + +/** + * Unit test of {@link Version}. + * @author Sindre Mehus + */ + +import junit.framework.*; + +public class VersionTestCase extends TestCase { + + /** + * Tests that equals(), hashCode(), toString() and compareTo() works. + */ + public void testVersion() { + doTestVersion("0.0", "0.1"); + doTestVersion("1.5", "2.3"); + doTestVersion("2.3", "2.34"); + + doTestVersion("1.5", "1.5.1"); + doTestVersion("1.5.1", "1.5.2"); + doTestVersion("1.5.2", "1.5.11"); + + doTestVersion("1.4", "1.5.beta1"); + doTestVersion("1.4.1", "1.5.beta1"); + doTestVersion("1.5.beta1", "1.5"); + doTestVersion("1.5.beta1", "1.5.1"); + doTestVersion("1.5.beta1", "1.6"); + doTestVersion("1.5.beta1", "1.5.beta2"); + doTestVersion("1.5.beta2", "1.5.beta11"); + } + + /** + * Tests that equals(), hashCode(), toString() and compareTo() works. + * @param v1 A lower version. + * @param v2 A higher version. + */ + private void doTestVersion(String v1, String v2) { + Version ver1 = new Version(v1); + Version ver2 = new Version(v2); + + assertEquals("Error in toString().", v1, ver1.toString()); + assertEquals("Error in toString().", v2, ver2.toString()); + + assertEquals("Error in equals().", ver1, ver1); + + assertEquals("Error in compareTo().", 0, ver1.compareTo(ver1)); + assertEquals("Error in compareTo().", 0, ver2.compareTo(ver2)); + assertTrue("Error in compareTo().", ver1.compareTo(ver2) < 0); + assertTrue("Error in compareTo().", ver2.compareTo(ver1) > 0); + } +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/service/MusicIndexServiceTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/MusicIndexServiceTestCase.java new file mode 100644 index 00000000..18fa2443 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/MusicIndexServiceTestCase.java @@ -0,0 +1,76 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.service; + +import junit.framework.TestCase; +import net.sourceforge.subsonic.domain.MusicIndex; + +import java.util.List; + +/** + * Unit test of {@link MusicIndex}. + * + * @author Sindre Mehus + */ +public class MusicIndexServiceTestCase extends TestCase { + + private final MusicIndexService musicIndexService = new MusicIndexService(); + + public void testCreateIndexFromExpression() throws Exception { + MusicIndex index = musicIndexService.createIndexFromExpression("A"); + assertEquals("A", index.getIndex()); + assertEquals(1, index.getPrefixes().size()); + assertEquals("A", index.getPrefixes().get(0)); + + index = musicIndexService.createIndexFromExpression("The"); + assertEquals("The", index.getIndex()); + assertEquals(1, index.getPrefixes().size()); + assertEquals("The", index.getPrefixes().get(0)); + + index = musicIndexService.createIndexFromExpression("X-Z(XYZ)"); + assertEquals("X-Z", index.getIndex()); + assertEquals(3, index.getPrefixes().size()); + assertEquals("X", index.getPrefixes().get(0)); + assertEquals("Y", index.getPrefixes().get(1)); + assertEquals("Z", index.getPrefixes().get(2)); + } + + public void testCreateIndexesFromExpression() throws Exception { + List<MusicIndex> indexes = musicIndexService.createIndexesFromExpression("A B The X-Z(XYZ)"); + assertEquals(4, indexes.size()); + + assertEquals("A", indexes.get(0).getIndex()); + assertEquals(1, indexes.get(0).getPrefixes().size()); + assertEquals("A", indexes.get(0).getPrefixes().get(0)); + + assertEquals("B", indexes.get(1).getIndex()); + assertEquals(1, indexes.get(1).getPrefixes().size()); + assertEquals("B", indexes.get(1).getPrefixes().get(0)); + + assertEquals("The", indexes.get(2).getIndex()); + assertEquals(1, indexes.get(2).getPrefixes().size()); + assertEquals("The", indexes.get(2).getPrefixes().get(0)); + + assertEquals("X-Z", indexes.get(3).getIndex()); + assertEquals(3, indexes.get(3).getPrefixes().size()); + assertEquals("X", indexes.get(3).getPrefixes().get(0)); + assertEquals("Y", indexes.get(3).getPrefixes().get(1)); + assertEquals("Z", indexes.get(3).getPrefixes().get(2)); + } +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/service/SecurityServiceTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/SecurityServiceTestCase.java new file mode 100644 index 00000000..001b124c --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/SecurityServiceTestCase.java @@ -0,0 +1,59 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.service; + +import junit.framework.*; +/** + * Unit test of {@link SecurityService}. + * + * @author Sindre Mehus + */ +public class SecurityServiceTestCase extends TestCase { + + public void testIsFileInFolder() { + SecurityService service = new SecurityService(); + + assertTrue(service.isFileInFolder("/music/foo.mp3", "\\")); + assertTrue(service.isFileInFolder("/music/foo.mp3", "/")); + + assertTrue(service.isFileInFolder("/music/foo.mp3", "/music")); + assertTrue(service.isFileInFolder("\\music\\foo.mp3", "/music")); + assertTrue(service.isFileInFolder("/music/foo.mp3", "\\music")); + assertTrue(service.isFileInFolder("/music/foo.mp3", "\\music\\")); + + assertFalse(service.isFileInFolder("", "/tmp")); + assertFalse(service.isFileInFolder("foo.mp3", "/tmp")); + assertFalse(service.isFileInFolder("/music/foo.mp3", "/tmp")); + assertFalse(service.isFileInFolder("/music/foo.mp3", "/tmp/music")); + + // Test that references to the parent directory (..) is not allowed. + assertTrue(service.isFileInFolder("/music/foo..mp3", "/music")); + assertTrue(service.isFileInFolder("/music/foo..", "/music")); + assertTrue(service.isFileInFolder("/music/foo.../", "/music")); + assertFalse(service.isFileInFolder("/music/foo/..", "/music")); + assertFalse(service.isFileInFolder("../music/foo", "/music")); + assertFalse(service.isFileInFolder("/music/../foo", "/music")); + assertFalse(service.isFileInFolder("/music/../bar/../foo", "/music")); + assertFalse(service.isFileInFolder("/music\\foo\\..", "/music")); + assertFalse(service.isFileInFolder("..\\music/foo", "/music")); + assertFalse(service.isFileInFolder("/music\\../foo", "/music")); + assertFalse(service.isFileInFolder("/music/..\\bar/../foo", "/music")); + } +} + diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/service/SettingsServiceTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/SettingsServiceTestCase.java new file mode 100644 index 00000000..bbb2fda0 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/SettingsServiceTestCase.java @@ -0,0 +1,140 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.service; + +import junit.framework.*; +import java.io.*; +import java.util.*; + +/** + * Unit test of {@link SettingsService}. + * + * @author Sindre Mehus + */ +public class SettingsServiceTestCase extends TestCase { + + private static final File SUBSONIC_HOME = new File("/tmp/subsonic"); + + private SettingsService settingsService; + + @Override + protected void setUp() throws Exception { + System.setProperty("subsonic.home", SUBSONIC_HOME.getPath()); + new File(SUBSONIC_HOME, "subsonic.properties").delete(); + settingsService = new SettingsService(); + } + + public void testSubsonicHome() { + assertEquals("Wrong Subsonic home.", SUBSONIC_HOME, SettingsService.getSubsonicHome()); + } + + public void testDefaultValues() { + assertEquals("Wrong default language.", "en", settingsService.getLocale().getLanguage()); + assertEquals("Wrong default cover art limit.", 30, settingsService.getCoverArtLimit()); + assertEquals("Wrong default index creation interval.", 1, settingsService.getIndexCreationInterval()); + assertEquals("Wrong default index creation hour.", 3, settingsService.getIndexCreationHour()); + assertEquals("Wrong default theme.", "default", settingsService.getThemeId()); + assertEquals("Wrong default stream port.", 0, settingsService.getStreamPort()); + assertNull("Wrong default license email.", settingsService.getLicenseEmail()); + assertNull("Wrong default license code.", settingsService.getLicenseCode()); + assertNull("Wrong default license date.", settingsService.getLicenseDate()); + assertEquals("Wrong default Podcast episode retention count.", 10, settingsService.getPodcastEpisodeRetentionCount()); + assertEquals("Wrong default Podcast episode download count.", 1, settingsService.getPodcastEpisodeDownloadCount()); + assertTrue("Wrong default Podcast folder.", settingsService.getPodcastFolder().endsWith("Podcast")); + assertEquals("Wrong default Podcast update interval.", 24, settingsService.getPodcastUpdateInterval()); + assertEquals("Wrong default rewrite URL enabled.", true, settingsService.isRewriteUrlEnabled()); + assertEquals("Wrong default LDAP enabled.", false, settingsService.isLdapEnabled()); + assertEquals("Wrong default LDAP URL.", "ldap://host.domain.com:389/cn=Users,dc=domain,dc=com", settingsService.getLdapUrl()); + assertNull("Wrong default LDAP manager DN.", settingsService.getLdapManagerDn()); + assertNull("Wrong default LDAP manager password.", settingsService.getLdapManagerPassword()); + assertEquals("Wrong default LDAP search filter.", "(sAMAccountName={0})", settingsService.getLdapSearchFilter()); + assertEquals("Wrong default LDAP auto-shadowing.", false, settingsService.isLdapAutoShadowing()); + } + + public void testChangeSettings() { + settingsService.setIndexString("indexString"); + settingsService.setIgnoredArticles("a the foo bar"); + settingsService.setShortcuts("new incoming \"rock 'n' roll\""); + settingsService.setMusicFileTypes("mp3 ogg aac"); + settingsService.setCoverArtFileTypes("jpeg gif png"); + settingsService.setCoverArtLimit(99); + settingsService.setWelcomeMessage("welcomeMessage"); + settingsService.setLoginMessage("loginMessage"); + settingsService.setLocale(Locale.CANADA_FRENCH); + settingsService.setThemeId("dark"); + settingsService.setIndexCreationInterval(4); + settingsService.setIndexCreationHour(9); + settingsService.setStreamPort(8080); + settingsService.setLicenseEmail("sindre@foo.bar.no"); + settingsService.setLicenseCode(null); + settingsService.setLicenseDate(new Date(223423412351253L)); + settingsService.setPodcastEpisodeRetentionCount(5); + settingsService.setPodcastEpisodeDownloadCount(-1); + settingsService.setPodcastFolder("d:/podcasts"); + settingsService.setPodcastUpdateInterval(-1); + settingsService.setRewriteUrlEnabled(false); + settingsService.setLdapEnabled(true); + settingsService.setLdapUrl("newLdapUrl"); + settingsService.setLdapManagerDn("admin"); + settingsService.setLdapManagerPassword("secret"); + settingsService.setLdapSearchFilter("newLdapSearchFilter"); + settingsService.setLdapAutoShadowing(true); + + verifySettings(settingsService); + + settingsService.save(); + verifySettings(settingsService); + + verifySettings(new SettingsService()); + } + + private void verifySettings(SettingsService ss) { + assertEquals("Wrong index string.", "indexString", ss.getIndexString()); + assertEquals("Wrong ignored articles.", "a the foo bar", ss.getIgnoredArticles()); + assertEquals("Wrong shortcuts.", "new incoming \"rock 'n' roll\"", ss.getShortcuts()); + assertTrue("Wrong ignored articles array.", Arrays.equals(new String[] {"a", "the", "foo", "bar"}, ss.getIgnoredArticlesAsArray())); + assertTrue("Wrong shortcut array.", Arrays.equals(new String[] {"new", "incoming", "rock 'n' roll"}, ss.getShortcutsAsArray())); + assertEquals("Wrong music mask.", "mp3 ogg aac", ss.getMusicFileTypes()); + assertTrue("Wrong music mask array.", Arrays.equals(new String[] {"mp3", "ogg", "aac"}, ss.getMusicFileTypesAsArray())); + assertEquals("Wrong cover art mask.", "jpeg gif png", ss.getCoverArtFileTypes()); + assertTrue("Wrong cover art mask array.", Arrays.equals(new String[] {"jpeg", "gif", "png"}, ss.getCoverArtFileTypesAsArray())); + assertEquals("Wrong cover art limit.", 99, ss.getCoverArtLimit()); + assertEquals("Wrong welcome message.", "welcomeMessage", ss.getWelcomeMessage()); + assertEquals("Wrong login message.", "loginMessage", ss.getLoginMessage()); + assertEquals("Wrong locale.", Locale.CANADA_FRENCH, ss.getLocale()); + assertEquals("Wrong theme.", "dark", ss.getThemeId()); + assertEquals("Wrong index creation interval.", 4, ss.getIndexCreationInterval()); + assertEquals("Wrong index creation hour.", 9, ss.getIndexCreationHour()); + assertEquals("Wrong stream port.", 8080, ss.getStreamPort()); + assertEquals("Wrong license email.", "sindre@foo.bar.no", ss.getLicenseEmail()); + assertEquals("Wrong license code.", null, ss.getLicenseCode()); + assertEquals("Wrong license date.", new Date(223423412351253L), ss.getLicenseDate()); + assertEquals("Wrong Podcast episode retention count.", 5, settingsService.getPodcastEpisodeRetentionCount()); + assertEquals("Wrong Podcast episode download count.", -1, settingsService.getPodcastEpisodeDownloadCount()); + assertEquals("Wrong Podcast folder.", "d:/podcasts", settingsService.getPodcastFolder()); + assertEquals("Wrong Podcast update interval.", -1, settingsService.getPodcastUpdateInterval()); + assertEquals("Wrong rewrite URL enabled.", false, settingsService.isRewriteUrlEnabled()); + assertTrue("Wrong LDAP enabled.", settingsService.isLdapEnabled()); + assertEquals("Wrong LDAP URL.", "newLdapUrl", settingsService.getLdapUrl()); + assertEquals("Wrong LDAP manager DN.", "admin", settingsService.getLdapManagerDn()); + assertEquals("Wrong LDAP manager password.", "secret", settingsService.getLdapManagerPassword()); + assertEquals("Wrong LDAP search filter.", "newLdapSearchFilter", settingsService.getLdapSearchFilter()); + assertTrue("Wrong LDAP auto-shadowing.", settingsService.isLdapAutoShadowing()); + } +} diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/service/StatusServiceTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/StatusServiceTestCase.java new file mode 100644 index 00000000..47f27fbf --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/StatusServiceTestCase.java @@ -0,0 +1,83 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.service; + +import junit.framework.TestCase; +import net.sourceforge.subsonic.domain.Player; +import net.sourceforge.subsonic.domain.TransferStatus; + +import java.util.Arrays; + +/** + * Unit test of {@link StatusService}. + * + * @author Sindre Mehus + */ +public class StatusServiceTestCase extends TestCase { + + private StatusService service; + private Player player1; + + @Override + protected void setUp() throws Exception { + super.setUp(); + service = new StatusService(); + player1 = new Player(); + player1.setId("1"); + } + + public void testSimpleAddRemove() { + TransferStatus status = service.createStreamStatus(player1); + assertTrue("Wrong status.", status.isActive()); + assertEquals("Wrong list of statuses.", Arrays.asList(status), service.getAllStreamStatuses()); + assertEquals("Wrong list of statuses.", Arrays.asList(status), service.getStreamStatusesForPlayer(player1)); + + service.removeStreamStatus(status); + assertFalse("Wrong status.", status.isActive()); + assertEquals("Wrong list of statuses.", Arrays.asList(status), service.getAllStreamStatuses()); + assertEquals("Wrong list of statuses.", Arrays.asList(status), service.getStreamStatusesForPlayer(player1)); + } + + public void testMultipleStreamsSamePlayer() { + TransferStatus statusA = service.createStreamStatus(player1); + TransferStatus statusB = service.createStreamStatus(player1); + + assertEquals("Wrong list of statuses.", Arrays.asList(statusA, statusB), service.getAllStreamStatuses()); + assertEquals("Wrong list of statuses.", Arrays.asList(statusA, statusB), service.getStreamStatusesForPlayer(player1)); + + // Stop stream A. + service.removeStreamStatus(statusA); + assertFalse("Wrong status.", statusA.isActive()); + assertTrue("Wrong status.", statusB.isActive()); + assertEquals("Wrong list of statuses.", Arrays.asList(statusB), service.getAllStreamStatuses()); + assertEquals("Wrong list of statuses.", Arrays.asList(statusB), service.getStreamStatusesForPlayer(player1)); + + // Stop stream B. + service.removeStreamStatus(statusB); + assertFalse("Wrong status.", statusB.isActive()); + assertEquals("Wrong list of statuses.", Arrays.asList(statusB), service.getAllStreamStatuses()); + assertEquals("Wrong list of statuses.", Arrays.asList(statusB), service.getStreamStatusesForPlayer(player1)); + + // Start stream C. + TransferStatus statusC = service.createStreamStatus(player1); + assertTrue("Wrong status.", statusC.isActive()); + assertEquals("Wrong list of statuses.", Arrays.asList(statusC), service.getAllStreamStatuses()); + assertEquals("Wrong list of statuses.", Arrays.asList(statusC), service.getStreamStatusesForPlayer(player1)); + } +} diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/service/metadata/MediaFileTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/metadata/MediaFileTestCase.java new file mode 100644 index 00000000..ccc728ea --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/metadata/MediaFileTestCase.java @@ -0,0 +1,60 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.service.metadata; + +import junit.framework.TestCase; +import net.sourceforge.subsonic.domain.MediaFile; + +/** + * Unit test of {@link MediaFile}. + * + * @author Sindre Mehus + */ +public class MediaFileTestCase extends TestCase { + + public void testGetDurationAsString() throws Exception { + doTestGetDurationAsString(0, "0:00"); + doTestGetDurationAsString(1, "0:01"); + doTestGetDurationAsString(10, "0:10"); + doTestGetDurationAsString(33, "0:33"); + doTestGetDurationAsString(59, "0:59"); + doTestGetDurationAsString(60, "1:00"); + doTestGetDurationAsString(61, "1:01"); + doTestGetDurationAsString(70, "1:10"); + doTestGetDurationAsString(119, "1:59"); + doTestGetDurationAsString(120, "2:00"); + doTestGetDurationAsString(1200, "20:00"); + doTestGetDurationAsString(1201, "20:01"); + doTestGetDurationAsString(3599, "59:59"); + doTestGetDurationAsString(3600, "1:00:00"); + doTestGetDurationAsString(3601, "1:00:01"); + doTestGetDurationAsString(3661, "1:01:01"); + doTestGetDurationAsString(4200, "1:10:00"); + doTestGetDurationAsString(4201, "1:10:01"); + doTestGetDurationAsString(4210, "1:10:10"); + doTestGetDurationAsString(36000, "10:00:00"); + doTestGetDurationAsString(360000, "100:00:00"); + } + + private void doTestGetDurationAsString(int seconds, String expected) { + MediaFile mediaFile = new MediaFile(); + mediaFile.setDurationSeconds(seconds); + assertEquals("Error in getDurationString().", expected, mediaFile.getDurationString()); + } +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/service/metadata/MetaDataParserTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/metadata/MetaDataParserTestCase.java new file mode 100644 index 00000000..254e93d0 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/service/metadata/MetaDataParserTestCase.java @@ -0,0 +1,92 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.service.metadata; + +import java.io.File; + +import junit.framework.TestCase; +import net.sourceforge.subsonic.domain.MediaFile; + +/** + * Unit test of {@link MetaDataParser}. + * + * @author Sindre Mehus + */ +public class MetaDataParserTestCase extends TestCase { + + public void testRemoveTrackNumberFromTitle() throws Exception { + + MetaDataParser parser = new MetaDataParser() { + public MetaData getRawMetaData(File file) { + return null; + } + + public void setMetaData(MediaFile file, MetaData metaData) { + } + + public boolean isEditingSupported() { + return false; + } + + public boolean isApplicable(File file) { + return false; + } + }; + + assertEquals("", parser.removeTrackNumberFromTitle("", null)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("kokos", null)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("01 kokos", null)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("01 - kokos", null)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("01-kokos", null)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("01 - kokos", null)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("99 - kokos", null)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("99.- kokos", null)); + assertEquals("kokos", parser.removeTrackNumberFromTitle(" 01 kokos", null)); + assertEquals("400 years", parser.removeTrackNumberFromTitle("400 years", null)); + assertEquals("49ers", parser.removeTrackNumberFromTitle("49ers", null)); + assertEquals("01", parser.removeTrackNumberFromTitle("01", null)); + assertEquals("01", parser.removeTrackNumberFromTitle("01 ", null)); + assertEquals("01", parser.removeTrackNumberFromTitle(" 01 ", null)); + assertEquals("01", parser.removeTrackNumberFromTitle(" 01", null)); + + assertEquals("", parser.removeTrackNumberFromTitle("", 1)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("01 kokos", 1)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("01 - kokos", 1)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("01-kokos", 1)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("99 - kokos", 99)); + assertEquals("kokos", parser.removeTrackNumberFromTitle("99.- kokos", 99)); + assertEquals("01 kokos", parser.removeTrackNumberFromTitle("01 kokos", 2)); + assertEquals("1 kokos", parser.removeTrackNumberFromTitle("1 kokos", 2)); + assertEquals("50 years", parser.removeTrackNumberFromTitle("50 years", 1)); + assertEquals("years", parser.removeTrackNumberFromTitle("50 years", 50)); + assertEquals("15 Step", parser.removeTrackNumberFromTitle("15 Step", 1)); + assertEquals("Step", parser.removeTrackNumberFromTitle("15 Step", 15)); + + assertEquals("49ers", parser.removeTrackNumberFromTitle("49ers", 1)); + assertEquals("49ers", parser.removeTrackNumberFromTitle("49ers", 49)); + assertEquals("01", parser.removeTrackNumberFromTitle("01", 1)); + assertEquals("01", parser.removeTrackNumberFromTitle("01 ", 1)); + assertEquals("01", parser.removeTrackNumberFromTitle(" 01 ", 1)); + assertEquals("01", parser.removeTrackNumberFromTitle(" 01", 1)); + assertEquals("01", parser.removeTrackNumberFromTitle("01", 2)); + assertEquals("01", parser.removeTrackNumberFromTitle("01 ", 2)); + assertEquals("01", parser.removeTrackNumberFromTitle(" 01 ", 2)); + assertEquals("01", parser.removeTrackNumberFromTitle(" 01", 2)); + } +}
\ No newline at end of file diff --git a/subsonic-main/src/test/java/net/sourceforge/subsonic/util/StringUtilTestCase.java b/subsonic-main/src/test/java/net/sourceforge/subsonic/util/StringUtilTestCase.java new file mode 100644 index 00000000..034b5a76 --- /dev/null +++ b/subsonic-main/src/test/java/net/sourceforge/subsonic/util/StringUtilTestCase.java @@ -0,0 +1,235 @@ +/* + This file is part of Subsonic. + + Subsonic is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Subsonic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Subsonic. If not, see <http://www.gnu.org/licenses/>. + + Copyright 2009 (C) Sindre Mehus + */ +package net.sourceforge.subsonic.util; + +import junit.framework.TestCase; + +import java.util.Locale; +import java.util.Arrays; + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.math.LongRange; + +/** + * Unit test of {@link StringUtil}. + * + * @author Sindre Mehus + */ +public class StringUtilTestCase extends TestCase { + + public void testToHtml() throws Exception { + assertEquals(null, StringUtil.toHtml(null)); + assertEquals("", StringUtil.toHtml("")); + assertEquals(" ", StringUtil.toHtml(" ")); + assertEquals("q & a", StringUtil.toHtml("q & a")); + assertEquals("q & a <> b", StringUtil.toHtml("q & a <> b")); + } + + public void testRemoveSuffix() { + assertEquals("Error in removeSuffix().", "foo", StringUtil.removeSuffix("foo.mp3")); + assertEquals("Error in removeSuffix().", "", StringUtil.removeSuffix(".mp3")); + assertEquals("Error in removeSuffix().", "foo.bar", StringUtil.removeSuffix("foo.bar.mp3")); + assertEquals("Error in removeSuffix().", "foo.", StringUtil.removeSuffix("foo..mp3")); + assertEquals("Error in removeSuffix().", "foo", StringUtil.removeSuffix("foo")); + assertEquals("Error in removeSuffix().", "", StringUtil.removeSuffix("")); + } + + public void testGetMimeType() { + assertEquals("Error in getMimeType().", "audio/mpeg", StringUtil.getMimeType("mp3")); + assertEquals("Error in getMimeType().", "audio/mpeg", StringUtil.getMimeType(".mp3")); + assertEquals("Error in getMimeType().", "audio/mpeg", StringUtil.getMimeType(".MP3")); + assertEquals("Error in getMimeType().", "application/octet-stream", StringUtil.getMimeType("koko")); + assertEquals("Error in getMimeType().", "application/octet-stream", StringUtil.getMimeType("")); + assertEquals("Error in getMimeType().", "application/octet-stream", StringUtil.getMimeType(null)); + } + + public void testFormatBytes() throws Exception { + Locale locale = Locale.ENGLISH; + assertEquals("Error in formatBytes().", "918 B", StringUtil.formatBytes(918, locale)); + assertEquals("Error in formatBytes().", "1023 B", StringUtil.formatBytes(1023, locale)); + assertEquals("Error in formatBytes().", "1 KB", StringUtil.formatBytes(1024, locale)); + assertEquals("Error in formatBytes().", "96 KB", StringUtil.formatBytes(98765, locale)); + assertEquals("Error in formatBytes().", "1024 KB", StringUtil.formatBytes(1048575, locale)); + assertEquals("Error in formatBytes().", "1.2 MB", StringUtil.formatBytes(1238476, locale)); + assertEquals("Error in formatBytes().", "3.50 GB", StringUtil.formatBytes(3758096384L, locale)); + + locale = new Locale("no", "", ""); + assertEquals("Error in formatBytes().", "918 B", StringUtil.formatBytes(918, locale)); + assertEquals("Error in formatBytes().", "1023 B", StringUtil.formatBytes(1023, locale)); + assertEquals("Error in formatBytes().", "1 KB", StringUtil.formatBytes(1024, locale)); + assertEquals("Error in formatBytes().", "96 KB", StringUtil.formatBytes(98765, locale)); + assertEquals("Error in formatBytes().", "1024 KB", StringUtil.formatBytes(1048575, locale)); + assertEquals("Error in formatBytes().", "1,2 MB", StringUtil.formatBytes(1238476, locale)); + assertEquals("Error in formatBytes().", "3,50 GB", StringUtil.formatBytes(3758096384L, locale)); + } + + public void testFormatDuration() { + assertEquals("Error in formatDuration().", "0:00", StringUtil.formatDuration(0)); + assertEquals("Error in formatDuration().", "0:05", StringUtil.formatDuration(5)); + assertEquals("Error in formatDuration().", "0:10", StringUtil.formatDuration(10)); + assertEquals("Error in formatDuration().", "0:59", StringUtil.formatDuration(59)); + assertEquals("Error in formatDuration().", "1:00", StringUtil.formatDuration(60)); + assertEquals("Error in formatDuration().", "1:01", StringUtil.formatDuration(61)); + assertEquals("Error in formatDuration().", "1:10", StringUtil.formatDuration(70)); + assertEquals("Error in formatDuration().", "10:00", StringUtil.formatDuration(600)); + assertEquals("Error in formatDuration().", "45:50", StringUtil.formatDuration(2750)); + assertEquals("Error in formatDuration().", "83:45", StringUtil.formatDuration(5025)); + } + + public void testSplit() { + doTestSplit("u2 rem \"greatest hits\"", "u2", "rem", "greatest hits"); + doTestSplit("u2", "u2"); + doTestSplit("u2 rem", "u2", "rem"); + doTestSplit(" u2 \t rem ", "u2", "rem"); + doTestSplit("u2 \"rem\"", "u2", "rem"); + doTestSplit("u2 \"rem", "u2", "\"rem"); + doTestSplit("\"", "\""); + + assertEquals(0, StringUtil.split("").length); + assertEquals(0, StringUtil.split(" ").length); + assertEquals(0, StringUtil.split(null).length); + } + + private void doTestSplit(String input, String... expected) { + String[] actual = StringUtil.split(input); + assertEquals("Wrong number of elements.", expected.length, actual.length); + + for (int i = 0; i < expected.length; i++) { + assertEquals("Wrong criteria.", expected[i], actual[i]); + } + } + + public void testParseInts() { + doTestParseInts("123", 123); + doTestParseInts("1 2 3", 1, 2, 3); + doTestParseInts("10 20 \t\n 30", 10, 20, 30); + + assertTrue("Error in parseInts().", StringUtil.parseInts(null).length == 0); + assertTrue("Error in parseInts().", StringUtil.parseInts("").length == 0); + assertTrue("Error in parseInts().", StringUtil.parseInts(" ").length == 0); + assertTrue("Error in parseInts().", StringUtil.parseInts(" ").length == 0); + } + + private void doTestParseInts(String s, int... expected) { + assertEquals("Error in parseInts().", Arrays.toString(expected), Arrays.toString(StringUtil.parseInts(s))); + } + + public void testToHttpUrl() throws Exception { + assertEquals("Error in toHttpUrl.", "http://foo.bar.com", StringUtil.toHttpUrl("http://foo.bar.com", 8080)); + assertEquals("Error in toHttpUrl.", "http://foo.bar.com:12/abc?f=a", StringUtil.toHttpUrl("http://foo.bar.com:12/abc?f=a", 8080)); + assertEquals("Error in toHttpUrl.", "http://foo.bar.com:443", StringUtil.toHttpUrl("https://foo.bar.com", 443)); + assertEquals("Error in toHttpUrl.", "http://foo.bar.com:443/a/b/c?k=1&j=2", StringUtil.toHttpUrl("https://foo.bar.com/a/b/c?k=1&j=2", 443)); + } + + public void testParseLocale() { + assertEquals("Error in parseLocale().", null, null); + assertEquals("Error in parseLocale().", new Locale("en"), StringUtil.parseLocale("en")); + assertEquals("Error in parseLocale().", new Locale("en"), StringUtil.parseLocale("en_")); + assertEquals("Error in parseLocale().", new Locale("en"), StringUtil.parseLocale("en__")); + assertEquals("Error in parseLocale().", new Locale("en", "US"), StringUtil.parseLocale("en_US")); + assertEquals("Error in parseLocale().", new Locale("en", "US", "WIN"), StringUtil.parseLocale("en_US_WIN")); + assertEquals("Error in parseLocale().", new Locale("en", "", "WIN"), StringUtil.parseLocale("en__WIN")); + } + + public void testUtf8Hex() throws Exception { + doTestUtf8Hex(null); + doTestUtf8Hex(""); + doTestUtf8Hex("a"); + doTestUtf8Hex("abcdefg"); + doTestUtf8Hex("abc������"); + doTestUtf8Hex("NRK P3 � FK Fotball"); + } + + private void doTestUtf8Hex(String s) throws Exception { + assertEquals("Error in utf8hex.", s, StringUtil.utf8HexDecode(StringUtil.utf8HexEncode(s))); + } + + public void testMd5Hex() { + assertNull("Error in md5Hex().", StringUtil.md5Hex(null)); + assertEquals("Error in md5Hex().", "d41d8cd98f00b204e9800998ecf8427e", StringUtil.md5Hex("")); + assertEquals("Error in md5Hex().", "308ed0af23d48f6d2fd4717e77a23e0c", StringUtil.md5Hex("sindre@activeobjects.no")); + } + + public void testGetUrlFile() { + assertEquals("Error in getUrlFile().", "foo.mp3", StringUtil.getUrlFile("http://www.asdf.com/foo.mp3")); + assertEquals("Error in getUrlFile().", "foo.mp3", StringUtil.getUrlFile("http://www.asdf.com/bar/foo.mp3")); + assertEquals("Error in getUrlFile().", "foo", StringUtil.getUrlFile("http://www.asdf.com/bar/foo")); + assertEquals("Error in getUrlFile().", "foo.mp3", StringUtil.getUrlFile("http://www.asdf.com/bar/foo.mp3?a=1&b=2")); + assertNull("Error in getUrlFile().", StringUtil.getUrlFile("not a url")); + assertNull("Error in getUrlFile().", StringUtil.getUrlFile("http://www.asdf.com")); + assertNull("Error in getUrlFile().", StringUtil.getUrlFile("http://www.asdf.com/")); + assertNull("Error in getUrlFile().", StringUtil.getUrlFile("http://www.asdf.com/foo/")); + } + + public void testFileSystemSafe() { + assertEquals("Error in fileSystemSafe().", "foo", StringUtil.fileSystemSafe("foo")); + assertEquals("Error in fileSystemSafe().", "foo.mp3", StringUtil.fileSystemSafe("foo.mp3")); + assertEquals("Error in fileSystemSafe().", "foo-bar", StringUtil.fileSystemSafe("foo/bar")); + assertEquals("Error in fileSystemSafe().", "foo-bar", StringUtil.fileSystemSafe("foo\\bar")); + assertEquals("Error in fileSystemSafe().", "foo-bar", StringUtil.fileSystemSafe("foo:bar")); + } + + public void testRewriteUrl() { + assertEquals("Error in rewriteUrl().", "http://foo/", StringUtil.rewriteUrl("http://foo/", "http://foo/")); + assertEquals("Error in rewriteUrl().", "http://foo:81/", StringUtil.rewriteUrl("http://foo/", "http://foo:81/")); + assertEquals("Error in rewriteUrl().", "http://bar/", StringUtil.rewriteUrl("http://foo/", "http://bar/")); + assertEquals("Error in rewriteUrl().", "http://bar.com/", StringUtil.rewriteUrl("http://foo.com/", "http://bar.com/")); + assertEquals("Error in rewriteUrl().", "http://bar.com/", StringUtil.rewriteUrl("http://foo.com/", "http://bar.com/")); + assertEquals("Error in rewriteUrl().", "http://bar.com/a", StringUtil.rewriteUrl("http://foo.com/a", "http://bar.com/")); + assertEquals("Error in rewriteUrl().", "http://bar.com/a/b", StringUtil.rewriteUrl("http://foo.com/a/b", "http://bar.com/c")); + assertEquals("Error in rewriteUrl().", "http://bar.com:8080/a?b=1&c=2", StringUtil.rewriteUrl("http://foo.com/a?b=1&c=2", "http://bar.com:8080/e?f=3")); + assertEquals("Error in rewriteUrl().", "http://foo.com:8080/a?b=1&c=2", StringUtil.rewriteUrl("http://foo.com/a?b=1&c=2", "http://foo.com:8080/e?f=3")); + assertEquals("Error in rewriteUrl().", "https://foo.com:8080/a?b=1&c=2", StringUtil.rewriteUrl("http://foo.com/a?b=1&c=2", "https://foo.com:8080/e?f=3")); + assertEquals("Error in rewriteUrl().", "http://foo/", StringUtil.rewriteUrl("http://foo/", "not:a:url")); + assertEquals("Error in rewriteUrl().", "http://foo/", StringUtil.rewriteUrl("http://foo/", "")); + assertEquals("Error in rewriteUrl().", "http://foo/", StringUtil.rewriteUrl("http://foo/", null)); + } + + public void testParseRange() { + doTestParseRange(0L, 0L, "bytes=0-0"); + doTestParseRange(0L, 1L, "bytes=0-1"); + doTestParseRange(100L, 100L, "bytes=100-100"); + doTestParseRange(0L, 499L, "bytes=0-499"); + doTestParseRange(500L, 999L, "bytes=500-999"); + doTestParseRange(9500L, Long.MAX_VALUE, "bytes=9500-"); + + assertNull("Error in parseRange().", StringUtil.parseRange(null)); + assertNull("Error in parseRange().", StringUtil.parseRange("")); + assertNull("Error in parseRange().", StringUtil.parseRange("bytes")); + assertNull("Error in parseRange().", StringUtil.parseRange("bytes=a-b")); + assertNull("Error in parseRange().", StringUtil.parseRange("bytes=-100-500")); + assertNull("Error in parseRange().", StringUtil.parseRange("bytes=-500")); + assertNull("Error in parseRange().", StringUtil.parseRange("bytes=500-600,601-999")); + assertNull("Error in parseRange().", StringUtil.parseRange("bytes=200-100")); + } + + private void doTestParseRange(long expectedFrom, long expectedTo, String range) { + LongRange actual = StringUtil.parseRange(range); + assertEquals("Error in parseRange().", expectedFrom, actual.getMinimumLong()); + assertEquals("Error in parseRange().", expectedTo, actual.getMaximumLong()); + } + + public void testRemoveMarkup() { + assertEquals("Error in removeMarkup()", "foo", StringUtil.removeMarkup("<b>foo</b>")); + assertEquals("Error in removeMarkup()", "foobar", StringUtil.removeMarkup("<b>foo</b>bar")); + assertEquals("Error in removeMarkup()", "foo", StringUtil.removeMarkup("foo")); + assertEquals("Error in removeMarkup()", "foo", StringUtil.removeMarkup("<b>foo")); + assertEquals("Error in removeMarkup()", null, StringUtil.removeMarkup(null)); + } +} |