aboutsummaryrefslogtreecommitdiff
path: root/subsonic-main/src/test/java/net/sourceforge/subsonic/dao/DaoTestCaseBase.java
blob: 8d3a7f88ea30024b447657cf8be93f682db5d84c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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();
    }
}