diff --git a/app/src/main/java/net/osmtracker/gpx/ExportToStorageTask.java b/app/src/main/java/net/osmtracker/gpx/ExportToStorageTask.java index 6abc1023..855929f8 100644 --- a/app/src/main/java/net/osmtracker/gpx/ExportToStorageTask.java +++ b/app/src/main/java/net/osmtracker/gpx/ExportToStorageTask.java @@ -1,5 +1,7 @@ package net.osmtracker.gpx; +import static net.osmtracker.util.FileSystemUtils.getUniqueChildNameFor; + import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; @@ -15,35 +17,57 @@ import java.io.File; import java.util.Date; -import static net.osmtracker.util.FileSystemUtils.getUniqueChildNameFor; - -import androidx.core.content.ContextCompat; - /** - * Exports to the external storage / SD card - * in a folder defined by the user. + * ExportToStorageTask is responsible for exporting track data to the device's storage. + * It extends the ExportTrackTask class and provides specific implementations for + * exporting track data to a directory on the external storage. */ public class ExportToStorageTask extends ExportTrackTask { private static final String TAG = ExportToStorageTask.class.getSimpleName(); - private String ERROR_MESSAGE; - - + private final String ERROR_MESSAGE; + private final DataHelper dataHelper; + private final SharedPreferences sharedPreferences; + + /** + * Constructor for ExportToStorageTask. + * + * @param context the context of the application + * @param trackId the IDs of the tracks to be exported + */ public ExportToStorageTask(Context context, long... trackId) { + this(context, new DataHelper(context), trackId); + } + + /** + * Constructor for ExportToStorageTask with a DataHelper instance. + * + * @param context the context of the application + * @param dataHelper the DataHelper instance for accessing track data + * @param trackId the IDs of the tracks to be exported + */ + public ExportToStorageTask(Context context, DataHelper dataHelper, long... trackId) { super(context, trackId); + this.dataHelper = dataHelper; + this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); ERROR_MESSAGE = context.getString(R.string.error_create_track_dir); } + /** + * Gets the directory where the track data will be exported. + * + * @param startDate the start date of the track + * @return the directory where the track data will be exported + * @throws ExportTrackException if the directory cannot be created + */ @Override protected File getExportDirectory(Date startDate) throws ExportTrackException { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - String trackName = getSanitizedTrackNameByStartDate(startDate); - boolean shouldCreateDirectoryPerTrack = shouldCreateDirectoryPerTrack(preferences); - File finalExportDirectory = getBaseExportDirectory(preferences); - Log.d(TAG, "absolute dir: " + finalExportDirectory.getAbsolutePath().toString()); + boolean shouldCreateDirectoryPerTrack = shouldCreateDirectoryPerTrack(); + File finalExportDirectory = getBaseExportDirectory(); + Log.d(TAG, "absolute dir: " + finalExportDirectory.getAbsolutePath()); - if( shouldCreateDirectoryPerTrack && trackName.length() >= 1){ + if( shouldCreateDirectoryPerTrack && !trackName.isEmpty()){ String uniqueFolderName = getUniqueChildNameFor(finalExportDirectory, trackName, ""); finalExportDirectory = new File(finalExportDirectory, uniqueFolderName); finalExportDirectory.mkdirs(); @@ -54,46 +78,58 @@ protected File getExportDirectory(Date startDate) throws ExportTrackException { return finalExportDirectory; } + /** + * Gets a sanitized track name based on the start date. + * + * @param startDate the start date of the track + * @return the sanitized track name + */ + public String getSanitizedTrackNameByStartDate(Date startDate) { + Track track = dataHelper.getTrackByStartDate(startDate); + + String trackName = ""; + if (track != null) { + trackName = track.getName(); + } + if (trackName != null && !trackName.isEmpty()) { + trackName = trackName.replace("/", "_").trim(); + } + return trackName; + } - /** - * - * @param startDate - * @return - */ - public String getSanitizedTrackNameByStartDate(Date startDate){ - - DataHelper dh = new DataHelper(context); - Track track = dh.getTrackByStartDate(startDate); - - String trackName = ""; - if(track != null){ - trackName = track.getName(); - } - if(trackName != null && trackName.length() >= 1) { - trackName = trackName.replace("/", "_").trim(); - } - return trackName; - } - - public boolean shouldCreateDirectoryPerTrack(SharedPreferences prefs){ - return prefs.getBoolean(OSMTracker.Preferences.KEY_OUTPUT_DIR_PER_TRACK, + /** + * Determines whether a separate directory should be created for each track. + * + * @return true if a separate directory should be created for each track, false otherwise + */ + public boolean shouldCreateDirectoryPerTrack(){ + return sharedPreferences.getBoolean(OSMTracker.Preferences.KEY_OUTPUT_DIR_PER_TRACK, OSMTracker.Preferences.VAL_OUTPUT_GPX_OUTPUT_DIR_PER_TRACK); - } - // Checks if a volume containing external storage is available for read and write. + /** + * Checks if external storage is writable. + * + * @return true if external storage is writable, false otherwise + */ private boolean isExternalStorageWritable() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } - // Create before returning if not exists - public File getBaseExportDirectory(SharedPreferences prefs) throws ExportTrackException { + /** + * Gets the base directory where the track data will be exported. + * Creates the directory if it does not exist. + * + * @return the base directory where the track data will be exported + * @throws ExportTrackException if the directory cannot be created or is not writable + */ + public File getBaseExportDirectory() throws ExportTrackException { if (!isExternalStorageWritable()) { throw new ExportTrackException( context.getResources().getString(R.string.error_externalstorage_not_writable)); } - String exportDirectoryNameInPreferences = prefs.getString( + String exportDirectoryNameInPreferences = sharedPreferences.getString( OSMTracker.Preferences.KEY_STORAGE_DIR, OSMTracker.Preferences.VAL_STORAGE_DIR); Log.d(TAG,"exportDirectoryNameInPreferences: " + exportDirectoryNameInPreferences); diff --git a/app/src/test/java/net/osmtracker/gpx/ExportToStorageTaskTest.java b/app/src/test/java/net/osmtracker/gpx/ExportToStorageTaskTest.java new file mode 100644 index 00000000..ce5d5b5a --- /dev/null +++ b/app/src/test/java/net/osmtracker/gpx/ExportToStorageTaskTest.java @@ -0,0 +1,329 @@ +package net.osmtracker.gpx; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertNull; +import static net.osmtracker.OSMTracker.Preferences; +import static net.osmtracker.OSMTracker.Preferences.KEY_OUTPUT_FILENAME; +import static net.osmtracker.OSMTracker.Preferences.VAL_OUTPUT_FILENAME; +import static net.osmtracker.db.TrackContentProvider.Schema; +import static net.osmtracker.util.UnitTestUtils.createDateFrom; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.when; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.database.Cursor; +import android.os.Environment; +import android.preference.PreferenceManager; + +import net.osmtracker.OSMTracker; +import net.osmtracker.R; +import net.osmtracker.db.DataHelper; +import net.osmtracker.db.model.Track; +import net.osmtracker.exception.ExportTrackException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.File; +import java.util.Date; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({Environment.class, PreferenceManager.class}) +@PowerMockIgnore("jdk.internal.reflect.*") +public class ExportToStorageTaskTest { + + @Rule + private final TemporaryFolder temporaryFolder = new TemporaryFolder(); + private final Context mockContext = mock(Context.class); + private final DataHelper mockDataHelper = mock(DataHelper.class); + private final SharedPreferences mockPrefs = mock(SharedPreferences.class); + private final Resources mockResources = mock(Resources.class); + + private ExportToStorageTask task; + + private static final String ERROR_CREATE_TRACK_DIR = "Error creating track directory"; + private static final String UNABLE_TO_WRITE_STORAGE = "Unable to write to external storage"; + + @Before + public void setUp() { + mockStatic(Environment.class); + mockStatic(PreferenceManager.class); + + when(PreferenceManager.getDefaultSharedPreferences(mockContext)).thenReturn(mockPrefs); + when(mockContext.getResources()).thenReturn(mockResources); + when(mockResources.getString(R.string.error_create_track_dir)).thenReturn(ERROR_CREATE_TRACK_DIR); + when(mockResources.getString(R.string.error_externalstorage_not_writable)).thenReturn(UNABLE_TO_WRITE_STORAGE); + + task = new ExportToStorageTask(mockContext, mockDataHelper, 1L); + } + + @After + public void tearDown() { + temporaryFolder.delete(); + } + + @Test + public void testBuildGPXFilenameUsingOnlyTrackName() { + String trackNameInDatabase = "MyTrack"; + Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); + String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME; + + String expectedFilename = "MyTrack.gpx"; + + doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); + } + + @Test + public void testBuildGPXFilenameUsingTrackNameAndStartDate() { + String trackNameInDatabase = "MyTrack"; + Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); + String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME_DATE; + + String expectedFilename = "MyTrack_2000-01-02_03-04-05.gpx"; + + doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); + } + + @Test + public void testBuildGPXFilenameUsingOnlyStartDate() { + String trackNameInDatabase = "MyTrack"; + Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); + String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_DATE; + + String expectedFilename = "2000-01-02_03-04-05.gpx"; + + doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); + } + + @Test + public void testBuildGPXFilenameWhenSanitizesTrackName() { + String trackNameInDatabase = ":M/y*T@r~a\\c?k:"; + Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); + String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME; + + String expectedFilename = ";M_y_T_r_a_c_k;.gpx"; + + doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); + } + + @Test + public void testBuildGPXFilenameWhenUsesTrackNameButThereIsNoName() { + String trackNameInDatabase = ""; + Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); + String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME; + + String expectedFilename = "2000-01-02_03-04-05.gpx"; // Must fallback to use the start date + + doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); + } + + @Test + public void testBuildGPXFilenameWhenUsesTrackNameAndStartDateButThereIsNoName() { + String trackNameInDatabase = ""; + Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); + String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME_DATE; + + String expectedFilename = "2000-01-02_03-04-05.gpx"; // Must fallback to use the start date + + doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); + } + + private void doTestBuildGPXFilename(String trackName, String desiredFormat, long trackStartDate, String expectedFilename) { + when(mockPrefs.getString(KEY_OUTPUT_FILENAME, VAL_OUTPUT_FILENAME)).thenReturn(desiredFormat); + + String result = task.buildGPXFilename(createMockCursor(trackName, trackStartDate), temporaryFolder.getRoot()); + + assertEquals(expectedFilename, result); + } + + private Cursor createMockCursor(String trackName, long trackStartDate) { + Cursor mockCursor = mock(Cursor.class); + when(mockCursor.getColumnIndex(Schema.COL_NAME)).thenReturn(1); + when(mockCursor.getString(1)).thenReturn(trackName); + + when(mockCursor.getColumnIndex(Schema.COL_START_DATE)).thenReturn(2); + when(mockCursor.getLong(2)).thenReturn(trackStartDate); + + return mockCursor; + } + + @Test + public void testGetExportDirectoryWhenStorageIsWritableAndDirExists() throws Exception { + // Mocking external storage state + when(Environment.getExternalStorageState()).thenReturn(Environment.MEDIA_MOUNTED); + + // Mocking preferences and context + when(mockPrefs.getString(any(), any())).thenReturn(OSMTracker.Preferences.VAL_STORAGE_DIR); + when(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)).thenReturn(temporaryFolder.getRoot()); + + var osmTrackerFolder = temporaryFolder.newFolder("osmtracker"); + + // Creating task and invoking method + File exportDirectory = task.getExportDirectory(new Date()); + + // Verifying the directory path + assertEquals(osmTrackerFolder.getAbsolutePath(), exportDirectory.getAbsolutePath()); + } + + @Test + public void testGetExportDirectoryWhenStorageIsNotWritable() { + // Mocking external storage state + when(Environment.getExternalStorageState()).thenReturn(Environment.MEDIA_MOUNTED_READ_ONLY); + + // Verifying the exception + assertThrows(ExportTrackException.class, () -> task.getExportDirectory(new Date())); + } + + @Test + public void testGetExportDirectoryWhenStorageIsWritableAndDirNotExists() throws Exception { + // Mocking external storage state + when(Environment.getExternalStorageState()).thenReturn(Environment.MEDIA_MOUNTED); + + // Mocking preferences and context + when(mockPrefs.getString(any(), any())).thenReturn(OSMTracker.Preferences.VAL_STORAGE_DIR); + when(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)).thenReturn(temporaryFolder.getRoot()); + + // Creating task and invoking method + File exportDirectory = task.getExportDirectory(new Date()); + + var osmTrackerFolder = new File(temporaryFolder.getRoot(), OSMTracker.Preferences.VAL_STORAGE_DIR); + + // Verifying the directory path + assertEquals(osmTrackerFolder.getAbsolutePath(), exportDirectory.getAbsolutePath()); + } + + @Test + public void testGetExportDirectoryWhenDirDoesNotExistAndCreatesIt() throws Exception { + // Mocking external storage state + when(Environment.getExternalStorageState()).thenReturn(Environment.MEDIA_MOUNTED); + + // Mocking preferences and context + when(mockPrefs.getString(any(), any())).thenReturn("NonExistentDir"); + + // Creating task and invoking method + File exportDirectory = task.getExportDirectory(new Date()); + + // Verifying the directory creation + assertEquals(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "NonExistentDir").getAbsolutePath(), exportDirectory.getAbsolutePath()); + } + + @Test + public void testGetSanitizedTrackNameByStartDateWithValidTrackName() { + // Mock track data + Track mockTrack = new Track(); + mockTrack.setName("My/Track"); + when(mockDataHelper.getTrackByStartDate(any(Date.class))).thenReturn(mockTrack); + + // Execute the method + String result = task.getSanitizedTrackNameByStartDate(new Date()); + + // Verify the sanitized track name + assertEquals("My_Track", result); + } + + @Test + public void testGetSanitizedTrackNameByStartDateWithEmptyTrackName() { + // Mock track data + Track mockTrack = new Track(); + mockTrack.setName(""); + when(mockDataHelper.getTrackByStartDate(any(Date.class))).thenReturn(mockTrack); + + // Execute the method + String result = task.getSanitizedTrackNameByStartDate(new Date()); + + // Verify the sanitized track name + assertEquals("", result); + } + + @Test + public void testGetSanitizedTrackNameByStartDateWithNullTrackName() { + // Mock track data + Track mockTrack = new Track(); + mockTrack.setName(null); + when(mockDataHelper.getTrackByStartDate(any(Date.class))).thenReturn(mockTrack); + + // Execute the method + String result = task.getSanitizedTrackNameByStartDate(new Date()); + + // Verify the sanitized track name + assertNull(result); + } + + @Test + public void testGetSanitizedTrackNameByStartDateWithSpecialCharacters() { + // Mock track data + Track mockTrack = new Track(); + mockTrack.setName("/M/y/T/r/@/c/k/"); + when(mockDataHelper.getTrackByStartDate(any(Date.class))).thenReturn(mockTrack); + + // Execute the method + String result = task.getSanitizedTrackNameByStartDate(new Date()); + + // Verify the sanitized track name + assertEquals("_M_y_T_r_@_c_k_", result); + } + + @Test + public void testGetSanitizedTrackNameByStartDateWithNoTrackFound() { + // Mock no track data + when(mockDataHelper.getTrackByStartDate(any(Date.class))).thenReturn(null); + + // Execute the method + String result = task.getSanitizedTrackNameByStartDate(new Date()); + + // Verify the sanitized track name + assertEquals("", result); + } + + @Test + public void testConstructorCallsSuperclassConstructor() { + long trackId = 1L; + + // Use a spy to verify the constructor call + var taskSpy = new ExportToStorageTask(mockContext, trackId); + + assertTrue(taskSpy.exportMediaFiles()); + assertTrue(taskSpy.updateExportDate()); + } + + @Test + public void testCreateDirectoryPerTrack() throws Exception{ + when(Environment.getExternalStorageState()).thenReturn(Environment.MEDIA_MOUNTED); + when(mockPrefs.getBoolean(anyString(), anyBoolean())).thenReturn(true); + when(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)).thenReturn(temporaryFolder.getRoot()); + when(mockPrefs.getString(any(), any())).thenReturn(OSMTracker.Preferences.VAL_STORAGE_DIR); + Track mockTrack = new Track(); + mockTrack.setName("MyTrack"); + when(mockDataHelper.getTrackByStartDate(any(Date.class))).thenReturn(mockTrack); + + task.getExportDirectory(new Date()); + } + + @Test + public void testCreateDirectoryPerTrackEmptyTrackname() throws Exception{ + when(Environment.getExternalStorageState()).thenReturn(Environment.MEDIA_MOUNTED); + when(mockPrefs.getBoolean(anyString(), anyBoolean())).thenReturn(true); + when(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)).thenReturn(temporaryFolder.getRoot()); + when(mockPrefs.getString(any(), any())).thenReturn(OSMTracker.Preferences.VAL_STORAGE_DIR); + Track mockTrack = new Track(); + mockTrack.setName(""); + when(mockDataHelper.getTrackByStartDate(any(Date.class))).thenReturn(mockTrack); + + task.getExportDirectory(new Date()); + } +} diff --git a/app/src/test/java/net/osmtracker/gpx/ExportTrackTest.java b/app/src/test/java/net/osmtracker/gpx/ExportTrackTest.java deleted file mode 100644 index 29d9190e..00000000 --- a/app/src/test/java/net/osmtracker/gpx/ExportTrackTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package net.osmtracker.gpx; - -import android.content.Context; -import android.content.SharedPreferences; -import android.database.Cursor; -import android.preference.PreferenceManager; - -import net.osmtracker.R; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.Date; - -import static junit.framework.TestCase.assertEquals; -import static net.osmtracker.db.TrackContentProvider.Schema; -import static net.osmtracker.OSMTracker.Preferences.KEY_OUTPUT_FILENAME; -import static net.osmtracker.OSMTracker.Preferences.VAL_OUTPUT_FILENAME; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -import static net.osmtracker.util.UnitTestUtils.createDateFrom; -import static net.osmtracker.OSMTracker.Preferences; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ PreferenceManager.class }) -//https://stackoverflow.com/questions/52966897/powermock-java-11 -@PowerMockIgnore("jdk.internal.reflect.*") -public class ExportTrackTest { - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - ExportToStorageTask task; - Context mockContext = Mockito.mock(Context.class); - - - @Test - public void testBuildGPXFilenameUsingOnlyTrackName() { - // Method parameters - String trackNameInDatabase = "MyTrack"; - Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); - String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME; - - String expectedFilename = "MyTrack.gpx"; - - doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); - - } - - @Test - public void testBuildGPXFilenameUsingTrackNameAndStartDate() { - // Method parameters - String trackNameInDatabase = "MyTrack"; - Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); - String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME_DATE; - - String expectedFilename = "MyTrack_2000-01-02_03-04-05.gpx"; - - doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); - } - - @Test - public void testBuildGPXFilenameUsingOnlyStartDate() { - // Method parameters - String trackNameInDatabase = "MyTrack"; - Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); - String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_DATE; - - String expectedFilename = "2000-01-02_03-04-05.gpx"; - - doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); - } - - @Test - public void testBuildGPXFilenameWhenSanitizesTrackName() { - // Method parameters - String trackNameInDatabase = ":M/y*T@r~a\\c?k:"; - Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); - String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME; - - String expectedFilename = ";M_y_T_r_a_c_k;.gpx"; - - doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); - } - - @Test - public void testBuildGPXFilenameWhenUsesTrackNameButThereIsNoName() { - // Method parameters - String trackNameInDatabase = ""; - Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); - String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME; - - String expectedFilename = "2000-01-02_03-04-05.gpx"; // Must fallback to use the start date - - doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); - } - - @Test - public void testBuildGPXFilenameWhenUsesTrackNameAndStartDateButThereIsNoName() { - // Method parameters - String trackNameInDatabase = ""; - Date trackStartDate = createDateFrom(2000, 1, 2, 3, 4, 5); - String preferenceSetting = Preferences.VAL_OUTPUT_FILENAME_NAME_DATE; - - String expectedFilename = "2000-01-02_03-04-05.gpx"; // Must fallback to use the start date - - doTestBuildGPXFilename(trackNameInDatabase, preferenceSetting, trackStartDate.getTime(), expectedFilename); - } - - - void doTestBuildGPXFilename(String trackName, String desiredFormat, long trackStartDate, - String expectedFilename) { - setupPreferencesToReturn(desiredFormat); - - when(mockContext.getString(R.string.error_create_track_dir)).thenReturn("Any"); - - task = new ExportToStorageTask(mockContext, 3); - - String result = task.buildGPXFilename(createMockCursor(trackName, trackStartDate), temporaryFolder.getRoot()); - - assertEquals(expectedFilename, result); - } - - - // Used for testing buildGPXFilename - void setupPreferencesToReturn(String desiredFormat) { - // Mock preferences - SharedPreferences mockPrefs = mock(SharedPreferences.class); - when(mockPrefs.getString(KEY_OUTPUT_FILENAME, VAL_OUTPUT_FILENAME)).thenReturn(desiredFormat); - - mockStatic(PreferenceManager.class); - - when(PreferenceManager.getDefaultSharedPreferences(mockContext)).thenReturn(mockPrefs); - } - - - // Used for testing buildGPXFilename - Cursor createMockCursor(String trackName, long trackStartDate){ - Cursor mockCursor = Mockito.mock(Cursor.class); - when(mockCursor.getColumnIndex(Schema.COL_NAME)).thenReturn(1); - when(mockCursor.getString(1)).thenReturn(trackName); - - when(mockCursor.getColumnIndex(Schema.COL_START_DATE)).thenReturn(2); - when(mockCursor.getLong(2)).thenReturn(trackStartDate); - - return mockCursor; - - } - - - -}