repo created

This commit is contained in:
Fr4nz D13trich 2025-09-18 17:54:51 +02:00
commit 1ef725ef20
2483 changed files with 278273 additions and 0 deletions

View file

@ -0,0 +1,83 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.datamodel
import com.owncloud.android.AbstractIT
import org.junit.Assert.assertEquals
import org.junit.Test
class ArbitraryDataProviderIT : AbstractIT() {
@Test
fun testEmpty() {
val key = "DUMMY_KEY"
arbitraryDataProvider.storeOrUpdateKeyValue(user.accountName, key, "")
assertEquals("", arbitraryDataProvider.getValue(user.accountName, key))
}
@Test
fun testString() {
val key = "DUMMY_KEY"
var value = "123"
arbitraryDataProvider.storeOrUpdateKeyValue(user.accountName, key, value)
assertEquals(value, arbitraryDataProvider.getValue(user.accountName, key))
value = ""
arbitraryDataProvider.storeOrUpdateKeyValue(user.accountName, key, value)
assertEquals(value, arbitraryDataProvider.getValue(user.accountName, key))
value = "-1"
arbitraryDataProvider.storeOrUpdateKeyValue(user.accountName, key, value)
assertEquals(value, arbitraryDataProvider.getValue(user.accountName, key))
}
@Test
fun testBoolean() {
val key = "DUMMY_KEY"
var value = true
arbitraryDataProvider.storeOrUpdateKeyValue(user.accountName, key, value)
assertEquals(value, arbitraryDataProvider.getBooleanValue(user.accountName, key))
value = false
arbitraryDataProvider.storeOrUpdateKeyValue(user.accountName, key, value)
assertEquals(value, arbitraryDataProvider.getBooleanValue(user.accountName, key))
}
@Test
fun testInteger() {
val key = "DUMMY_KEY"
var value = 1
arbitraryDataProvider.storeOrUpdateKeyValue(user.accountName, key, value.toString())
assertEquals(value, arbitraryDataProvider.getIntegerValue(user.accountName, key))
value = -1
arbitraryDataProvider.storeOrUpdateKeyValue(user.accountName, key, value.toString())
assertEquals(value, arbitraryDataProvider.getIntegerValue(user.accountName, key))
}
@Test
fun testIncrement() {
val key = "INCREMENT"
// key does not exist
assertEquals(-1, arbitraryDataProvider.getIntegerValue(user.accountName, key))
// increment -> 1
arbitraryDataProvider.incrementValue(user.accountName, key)
assertEquals(1, arbitraryDataProvider.getIntegerValue(user.accountName, key))
// increment -> 2
arbitraryDataProvider.incrementValue(user.accountName, key)
assertEquals(2, arbitraryDataProvider.getIntegerValue(user.accountName, key))
// delete
arbitraryDataProvider.deleteKeyForAccount(user.accountName, key)
assertEquals(-1, arbitraryDataProvider.getIntegerValue(user.accountName, key))
}
}

View file

@ -0,0 +1,80 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2021 Álvaro Brey <alvaro@alvarobrey.com>
* SPDX-FileCopyrightText: 2021 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.datamodel
import android.content.ContentResolver
import android.net.Uri
import android.os.Build
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.mockito.kotlin.argThat
import org.mockito.kotlin.eq
import org.mockito.kotlin.verify
@RunWith(AndroidJUnit4::class)
class ContentResolverHelperIT {
companion object {
private val URI = Uri.parse("http://foo.bar")
private val PROJECTION = arrayOf("Foo")
private const val SELECTION = "selection"
private const val SORT_COLUMN = "sortColumn"
private const val SORT_DIRECTION = ContentResolverHelper.SORT_DIRECTION_ASCENDING
private const val SORT_DIRECTION_INT = ContentResolver.QUERY_SORT_DIRECTION_ASCENDING
private const val LIMIT = 10
}
@Mock
lateinit var resolver: ContentResolver
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
fun contentResolver_onAndroid26_usesNewAPI() {
ContentResolverHelper
.queryResolver(resolver, URI, PROJECTION, SELECTION, null, SORT_COLUMN, SORT_DIRECTION, LIMIT)
verify(resolver).query(
eq(URI),
eq(PROJECTION),
argThat { bundle ->
bundle.getString(ContentResolver.QUERY_ARG_SQL_SELECTION) == SELECTION &&
bundle.getInt(ContentResolver.QUERY_ARG_LIMIT) == LIMIT &&
bundle.getStringArray(ContentResolver.QUERY_ARG_SORT_COLUMNS)!!
.contentEquals(arrayOf(SORT_COLUMN)) &&
bundle.getInt(ContentResolver.QUERY_ARG_SORT_DIRECTION) == SORT_DIRECTION_INT
},
null
)
}
@Test
@SdkSuppress(maxSdkVersion = Build.VERSION_CODES.N_MR1)
fun contentResolver_onAndroidBelow26_usesOldAPI() {
ContentResolverHelper
.queryResolver(resolver, URI, PROJECTION, SELECTION, null, SORT_COLUMN, SORT_DIRECTION, LIMIT)
verify(resolver).query(
eq(URI),
eq(PROJECTION),
eq(SELECTION),
eq(null),
eq("$SORT_COLUMN $SORT_DIRECTION LIMIT $LIMIT"),
eq(null)
)
}
}

View file

@ -0,0 +1,47 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.datamodel;
import com.owncloud.android.db.ProviderMeta;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class FileDataStorageManagerContentProviderClientIT extends FileDataStorageManagerIT {
public void before() {
sut = new FileDataStorageManager(user,
targetContext
.getContentResolver()
.acquireContentProviderClient(ProviderMeta.ProviderTableMeta.CONTENT_URI)
);
super.before();
}
@Test
public void saveFile() {
String path = "/1.txt";
OCFile file = new OCFile(path);
file.setRemoteId("00000008ocjycgrudn78");
// TODO check via reflection that every parameter is set
file.setFileLength(1024000);
file.setModificationTimestamp(1582019340);
sut.saveNewFile(file);
OCFile read = sut.getFileByPath(path);
assertNotNull(read);
assertEquals(file.getRemotePath(), read.getRemotePath());
}
}

View file

@ -0,0 +1,56 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.datamodel
import org.junit.Assert
import org.junit.Test
class FileDataStorageManagerContentResolverIT : FileDataStorageManagerIT() {
companion object {
private const val MANY_FILES_AMOUNT = 5000
}
override fun before() {
sut = FileDataStorageManager(user, targetContext.contentResolver)
super.before()
}
/**
* only on FileDataStorageManager
*/
@Test
fun testFolderWithManyFiles() {
// create folder
val folderA = OCFile("/folderA/")
folderA.setFolder().parentId = sut.getFileByDecryptedRemotePath("/")!!.fileId
sut.saveFile(folderA)
Assert.assertTrue(sut.fileExists("/folderA/"))
Assert.assertEquals(0, sut.getFolderContent(folderA, false).size)
val folderAId = sut.getFileByDecryptedRemotePath("/folderA/")!!.fileId
// create files
val newFiles = (1..MANY_FILES_AMOUNT).map {
val file = OCFile("/folderA/file$it")
file.parentId = folderAId
sut.saveFile(file)
val storedFile = sut.getFileByDecryptedRemotePath("/folderA/file$it")
Assert.assertNotNull(storedFile)
storedFile
}
// save files in folder
sut.saveFolder(
folderA,
newFiles,
ArrayList()
)
// check file count is correct
Assert.assertEquals(MANY_FILES_AMOUNT, sut.getFolderContent(folderA, false).size)
}
}

View file

@ -0,0 +1,358 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.datamodel;
import android.content.ContentValues;
import com.owncloud.android.AbstractOnServerIT;
import com.owncloud.android.db.ProviderMeta;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.CreateFolderRemoteOperation;
import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
import com.owncloud.android.lib.resources.files.UploadFileRemoteOperation;
import com.owncloud.android.lib.resources.files.model.RemoteFile;
import com.owncloud.android.lib.resources.status.CapabilityBooleanType;
import com.owncloud.android.lib.resources.status.GetCapabilitiesRemoteOperation;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.operations.RefreshFolderOperation;
import com.owncloud.android.utils.FileStorageUtils;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.owncloud.android.lib.resources.files.SearchRemoteOperation.SearchType.GALLERY_SEARCH;
import static com.owncloud.android.lib.resources.files.SearchRemoteOperation.SearchType.PHOTO_SEARCH;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
abstract public class FileDataStorageManagerIT extends AbstractOnServerIT {
protected FileDataStorageManager sut;
private OCCapability capability;
@Before
public void before() {
// make sure everything is removed
sut.deleteAllFiles();
sut.deleteVirtuals(VirtualFolderType.GALLERY);
assertEquals(0, sut.getAllFiles().size());
capability = (OCCapability) new GetCapabilitiesRemoteOperation(null)
.execute(client)
.getSingleData();
}
@After
public void after() {
super.after();
sut.deleteAllFiles();
sut.deleteVirtuals(VirtualFolderType.GALLERY);
}
@Test
public void simpleTest() {
OCFile file = sut.getFileByDecryptedRemotePath("/");
assertNotNull(file);
assertTrue(file.fileExists());
assertNull(sut.getFileByDecryptedRemotePath("/123123"));
}
@Test
public void getAllFiles_NoAvailable() {
assertEquals(0, sut.getAllFiles().size());
}
@Test
public void testFolderContent() throws IOException {
assertEquals(0, sut.getAllFiles().size());
assertTrue(new CreateFolderRemoteOperation("/1/1/", true).execute(client).isSuccess());
assertTrue(new CreateFolderRemoteOperation("/1/2/", true).execute(client).isSuccess());
assertTrue(new UploadFileRemoteOperation(getDummyFile("chunkedFile.txt").getAbsolutePath(),
"/1/1/chunkedFile.txt",
"text/plain",
System.currentTimeMillis() / 1000)
.execute(client).isSuccess());
assertTrue(new UploadFileRemoteOperation(getDummyFile("chunkedFile.txt").getAbsolutePath(),
"/1/1/chunkedFile2.txt",
"text/plain",
System.currentTimeMillis() / 1000)
.execute(client).isSuccess());
File imageFile = getFile("imageFile.png");
assertTrue(new UploadFileRemoteOperation(imageFile.getAbsolutePath(),
"/1/1/imageFile.png",
"image/png",
System.currentTimeMillis() / 1000)
.execute(client).isSuccess());
// sync
assertNull(sut.getFileByDecryptedRemotePath("/1/1/"));
assertTrue(new RefreshFolderOperation(sut.getFileByDecryptedRemotePath("/"),
System.currentTimeMillis() / 1000,
false,
false,
sut,
user,
targetContext).execute(client).isSuccess());
assertTrue(new RefreshFolderOperation(sut.getFileByDecryptedRemotePath("/1/"),
System.currentTimeMillis() / 1000,
false,
false,
sut,
user,
targetContext).execute(client).isSuccess());
assertTrue(new RefreshFolderOperation(sut.getFileByDecryptedRemotePath("/1/1/"),
System.currentTimeMillis() / 1000,
false,
false,
sut,
user,
targetContext).execute(client).isSuccess());
assertEquals(3, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/1/1/"), false).size());
}
/**
* This test creates an image, does a photo search (now returned image is not yet in file hierarchy), then root
* folder is refreshed and it is verified that the same image file is used in database
*/
@Test
public void testPhotoSearch() throws IOException {
String remotePath = "/imageFile.png";
VirtualFolderType virtualType = VirtualFolderType.GALLERY;
assertEquals(0, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).size());
assertEquals(1, sut.getAllFiles().size());
File imageFile = getFile("imageFile.png");
assertTrue(new UploadFileRemoteOperation(imageFile.getAbsolutePath(),
remotePath,
"image/png",
System.currentTimeMillis() / 1000)
.execute(client).isSuccess());
assertNull(sut.getFileByDecryptedRemotePath(remotePath));
// search
SearchRemoteOperation searchRemoteOperation = new SearchRemoteOperation("image/%",
PHOTO_SEARCH,
false,
capability);
RemoteOperationResult<List<RemoteFile>> searchResult = searchRemoteOperation.execute(client);
TestCase.assertTrue(searchResult.isSuccess());
TestCase.assertEquals(1, searchResult.getResultData().size());
OCFile ocFile = FileStorageUtils.fillOCFile(searchResult.getResultData().get(0));
sut.saveFile(ocFile);
List<ContentValues> contentValues = new ArrayList<>();
ContentValues cv = new ContentValues();
cv.put(ProviderMeta.ProviderTableMeta.VIRTUAL_TYPE, virtualType.toString());
cv.put(ProviderMeta.ProviderTableMeta.VIRTUAL_OCFILE_ID, ocFile.getFileId());
contentValues.add(cv);
sut.saveVirtuals(contentValues);
assertEquals(remotePath, ocFile.getRemotePath());
assertEquals(0, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).size());
assertEquals(1, sut.getVirtualFolderContent(virtualType, false).size());
assertEquals(2, sut.getAllFiles().size());
// update root
assertTrue(new RefreshFolderOperation(sut.getFileByDecryptedRemotePath("/"),
System.currentTimeMillis() / 1000,
false,
false,
sut,
user,
targetContext).execute(client).isSuccess());
assertEquals(1, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).size());
assertEquals(1, sut.getVirtualFolderContent(virtualType, false).size());
assertEquals(2, sut.getAllFiles().size());
assertEquals(sut.getVirtualFolderContent(virtualType, false).get(0),
sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).get(0));
}
/**
* This test creates an image and a video, does a gallery search (now returned image and video is not yet in file
* hierarchy), then root folder is refreshed and it is verified that the same image file is used in database
*/
@Test
public void testGallerySearch() throws IOException {
sut = new FileDataStorageManager(user,
targetContext
.getContentResolver()
.acquireContentProviderClient(ProviderMeta.ProviderTableMeta.CONTENT_URI)
);
String imagePath = "/imageFile.png";
VirtualFolderType virtualType = VirtualFolderType.GALLERY;
assertEquals(0, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).size());
assertEquals(1, sut.getAllFiles().size());
File imageFile = getFile("imageFile.png");
assertTrue(new UploadFileRemoteOperation(imageFile.getAbsolutePath(),
imagePath,
"image/png",
(System.currentTimeMillis() - 10000) / 1000)
.execute(client).isSuccess());
// Check that file does not yet exist in local database
assertNull(sut.getFileByDecryptedRemotePath(imagePath));
String videoPath = "/videoFile.mp4";
File videoFile = getFile("videoFile.mp4");
assertTrue(new UploadFileRemoteOperation(videoFile.getAbsolutePath(),
videoPath,
"video/mpeg",
(System.currentTimeMillis() + 10000) / 1000)
.execute(client).isSuccess());
// Check that file does not yet exist in local database
assertNull(sut.getFileByDecryptedRemotePath(videoPath));
// search
SearchRemoteOperation searchRemoteOperation = new SearchRemoteOperation("",
GALLERY_SEARCH,
false,
capability);
RemoteOperationResult<List<RemoteFile>> searchResult = searchRemoteOperation.execute(client);
TestCase.assertTrue(searchResult.isSuccess());
TestCase.assertEquals(2, searchResult.getResultData().size());
// newest file must be video path (as sorted by recently modified)
OCFile ocFile = FileStorageUtils.fillOCFile( searchResult.getResultData().get(0));
sut.saveFile(ocFile);
assertEquals(videoPath, ocFile.getRemotePath());
List<ContentValues> contentValues = new ArrayList<>();
ContentValues cv = new ContentValues();
cv.put(ProviderMeta.ProviderTableMeta.VIRTUAL_TYPE, virtualType.toString());
cv.put(ProviderMeta.ProviderTableMeta.VIRTUAL_OCFILE_ID, ocFile.getFileId());
contentValues.add(cv);
// second is image file, as older
OCFile ocFile2 = FileStorageUtils.fillOCFile(searchResult.getResultData().get(1));
sut.saveFile(ocFile2);
assertEquals(imagePath, ocFile2.getRemotePath());
ContentValues cv2 = new ContentValues();
cv2.put(ProviderMeta.ProviderTableMeta.VIRTUAL_TYPE, virtualType.toString());
cv2.put(ProviderMeta.ProviderTableMeta.VIRTUAL_OCFILE_ID, ocFile2.getFileId());
contentValues.add(cv2);
sut.saveVirtuals(contentValues);
assertEquals(0, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).size());
assertEquals(2, sut.getVirtualFolderContent(virtualType, false).size());
assertEquals(3, sut.getAllFiles().size());
// update root
assertTrue(new RefreshFolderOperation(sut.getFileByDecryptedRemotePath("/"),
System.currentTimeMillis() / 1000,
false,
false,
sut,
user,
targetContext).execute(client).isSuccess());
assertEquals(2, sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).size());
assertEquals(2, sut.getVirtualFolderContent(virtualType, false).size());
assertEquals(3, sut.getAllFiles().size());
assertEquals(sut.getVirtualFolderContent(virtualType, false).get(0),
sut.getFolderContent(sut.getFileByDecryptedRemotePath("/"), false).get(0));
}
@Test
public void testSaveNewFile() {
assertTrue(new CreateFolderRemoteOperation("/1/1/", true).execute(client).isSuccess());
assertTrue(new RefreshFolderOperation(sut.getFileByDecryptedRemotePath("/"),
System.currentTimeMillis() / 1000,
false,
false,
sut,
user,
targetContext).execute(client).isSuccess());
assertTrue(new RefreshFolderOperation(sut.getFileByDecryptedRemotePath("/1/"),
System.currentTimeMillis() / 1000,
false,
false,
sut,
user,
targetContext).execute(client).isSuccess());
assertTrue(new RefreshFolderOperation(sut.getFileByDecryptedRemotePath("/1/1/"),
System.currentTimeMillis() / 1000,
false,
false,
sut,
user,
targetContext).execute(client).isSuccess());
OCFile newFile = new OCFile("/1/1/1.txt");
newFile.setRemoteId("12345678");
sut.saveNewFile(newFile);
}
@Test(expected = IllegalArgumentException.class)
public void testSaveNewFile_NonExistingParent() {
assertTrue(new CreateFolderRemoteOperation("/1/1/", true).execute(client).isSuccess());
OCFile newFile = new OCFile("/1/1/1.txt");
sut.saveNewFile(newFile);
}
@Test
public void testOCCapability() {
OCCapability capability = new OCCapability();
capability.setUserStatus(CapabilityBooleanType.TRUE);
sut.saveCapabilities(capability);
OCCapability newCapability = sut.getCapability(user);
assertEquals(capability.getUserStatus(), newCapability.getUserStatus());
}
}

View file

@ -0,0 +1,36 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.datamodel
import com.owncloud.android.AbstractIT
import com.owncloud.android.lib.resources.status.CapabilityBooleanType
import com.owncloud.android.lib.resources.status.OCCapability
import org.junit.Assert.assertEquals
import org.junit.Test
class OCCapabilityIT : AbstractIT() {
@Test
fun saveCapability() {
val fileDataStorageManager = FileDataStorageManager(user, targetContext.contentResolver)
val capability = OCCapability()
capability.etag = "123"
capability.userStatus = CapabilityBooleanType.TRUE
capability.userStatusSupportsEmoji = CapabilityBooleanType.TRUE
capability.dropAccount = CapabilityBooleanType.TRUE
fileDataStorageManager.saveCapabilities(capability)
val newCapability = fileDataStorageManager.getCapability(user.accountName)
assertEquals(capability.etag, newCapability.etag)
assertEquals(capability.userStatus, newCapability.userStatus)
assertEquals(capability.userStatusSupportsEmoji, newCapability.userStatusSupportsEmoji)
assertEquals(capability.dropAccount, newCapability.dropAccount)
}
}

View file

@ -0,0 +1,91 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2023 Alper Ozturk <alper_ozturk@proton.me>
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.datamodel
import com.owncloud.android.R
import com.owncloud.android.lib.common.network.WebdavEntry.MountType
import org.junit.After
import org.junit.Before
import org.junit.Test
class OCFileIconTests {
private val path = "/path/to/a/file.txt"
private var sut: OCFile? = null
@Before
fun setup() {
sut = OCFile(path)
}
@Test
fun testGetFileOverlayIconWhenFileIsAutoUploadFolderShouldReturnFolderOverlayUploadIcon() {
val fileOverlayIcon = sut?.getFileOverlayIconId(true)
val expectedDrawable = R.drawable.ic_folder_overlay_upload
assert(fileOverlayIcon == expectedDrawable)
}
@Test
fun testGetFileOverlayIconWhenFileIsEncryptedShouldReturnFolderOverlayKeyIcon() {
sut?.isEncrypted = true
val fileOverlayIcon = sut?.getFileOverlayIconId(false)
val expectedDrawable = R.drawable.ic_folder_overlay_key
assert(fileOverlayIcon == expectedDrawable)
}
@Test
fun testGetFileOverlayIconWhenFileIsGroupFolderShouldReturnFolderOverlayAccountGroupIcon() {
sut?.mountType = MountType.GROUP
val fileOverlayIcon = sut?.getFileOverlayIconId(false)
val expectedDrawable = R.drawable.ic_folder_overlay_account_group
assert(fileOverlayIcon == expectedDrawable)
}
@Test
fun testGetFileOverlayIconWhenFileIsSharedViaLinkShouldReturnFolderOverlayLinkIcon() {
sut?.isSharedViaLink = true
val fileOverlayIcon = sut?.getFileOverlayIconId(false)
val expectedDrawable = R.drawable.ic_folder_overlay_link
assert(fileOverlayIcon == expectedDrawable)
}
@Test
fun testGetFileOverlayIconWhenFileIsSharedShouldReturnFolderOverlayShareIcon() {
sut?.isSharedWithSharee = true
val fileOverlayIcon = sut?.getFileOverlayIconId(false)
val expectedDrawable = R.drawable.ic_folder_overlay_share
assert(fileOverlayIcon == expectedDrawable)
}
@Test
fun testGetFileOverlayIconWhenFileIsExternalShouldReturnFolderOverlayExternalIcon() {
sut?.mountType = MountType.EXTERNAL
val fileOverlayIcon = sut?.getFileOverlayIconId(false)
val expectedDrawable = R.drawable.ic_folder_overlay_external
assert(fileOverlayIcon == expectedDrawable)
}
@Test
fun testGetFileOverlayIconWhenFileIsLockedShouldReturnFolderOverlayLockIcon() {
sut?.isLocked = true
val fileOverlayIcon = sut?.getFileOverlayIconId(false)
val expectedDrawable = R.drawable.ic_folder_overlay_lock
assert(fileOverlayIcon == expectedDrawable)
}
@Test
fun testGetFileOverlayIconWhenFileIsFolderShouldReturnNull() {
val fileOverlayIcon = sut?.getFileOverlayIconId(false)
assert(fileOverlayIcon == null)
}
@After
fun destroy() {
sut = null
}
}

View file

@ -0,0 +1,113 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2016 David A. Velasco
* SPDX-FileCopyrightText: 2016 2016 ownCloud Inc
* SPDX-License-Identifier: GPL-2.0-only
*/
package com.owncloud.android.datamodel;
import android.os.Parcel;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Instrumented unit test, to be run in an Android emulator or device.
* At the moment, it's a sample to validate the automatic test environment, in the scope of instrumented unit tests.
* Don't take it as an example of completeness.
* See http://developer.android.com/intl/es/training/testing/unit-testing/instrumented-unit-tests.html .
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class OCFileUnitTest {
private final static String PATH = "/path/to/a/file.txt";
private static final long ID = 12345L;
private static final long PARENT_ID = 567890L;
private static final String STORAGE_PATH = "/mnt/sd/localpath/to/a/file.txt";
private static final String MIME_TYPE = "text/plain";
private static final long FILE_LENGTH = 9876543210L;
private static final long CREATION_TIMESTAMP = 8765432109L;
private static final long MODIFICATION_TIMESTAMP = 7654321098L;
private static final long MODIFICATION_TIMESTAMP_AT_LAST_SYNC_FOR_DATA = 6543210987L;
private static final long LAST_SYNC_DATE_FOR_PROPERTIES = 5432109876L;
private static final long LAST_SYNC_DATE_FOR_DATA = 4321098765L;
private static final String ETAG = "adshfas98ferqw8f9yu2";
private static final String PUBLIC_LINK = "https://nextcloud.localhost/owncloud/987427448712984sdas29";
private static final String PERMISSIONS = "SRKNVD";
private static final String REMOTE_ID = "jadñgiadf8203:9jrp98v2mn3er2089fh";
private static final String ETAG_IN_CONFLICT = "2adshfas98ferqw8f9yu";
private OCFile mFile;
@Before
public void createDefaultOCFile() {
mFile = new OCFile(PATH);
}
@Test
public void writeThenReadAsParcelable() {
// Set up mFile with not-default values
mFile.setFileId(ID);
mFile.setParentId(PARENT_ID);
mFile.setStoragePath(STORAGE_PATH);
mFile.setMimeType(MIME_TYPE);
mFile.setFileLength(FILE_LENGTH);
mFile.setCreationTimestamp(CREATION_TIMESTAMP);
mFile.setModificationTimestamp(MODIFICATION_TIMESTAMP);
mFile.setModificationTimestampAtLastSyncForData(MODIFICATION_TIMESTAMP_AT_LAST_SYNC_FOR_DATA);
mFile.setLastSyncDateForProperties(LAST_SYNC_DATE_FOR_PROPERTIES);
mFile.setLastSyncDateForData(LAST_SYNC_DATE_FOR_DATA);
mFile.setEtag(ETAG);
mFile.setSharedViaLink(true);
mFile.setSharedWithSharee(true);
mFile.setPermissions(PERMISSIONS);
mFile.setRemoteId(REMOTE_ID);
mFile.setUpdateThumbnailNeeded(true);
mFile.setDownloading(true);
mFile.setEtagInConflict(ETAG_IN_CONFLICT);
// Write the file data in a Parcel
Parcel parcel = Parcel.obtain();
mFile.writeToParcel(parcel, mFile.describeContents());
// Read the data from the parcel
parcel.setDataPosition(0);
OCFile fileReadFromParcel = OCFile.CREATOR.createFromParcel(parcel);
// Verify that the received data are correct
assertThat(fileReadFromParcel.getRemotePath(), is(PATH));
assertThat(fileReadFromParcel.getFileId(), is(ID));
assertThat(fileReadFromParcel.getParentId(), is(PARENT_ID));
assertThat(fileReadFromParcel.getStoragePath(), is(STORAGE_PATH));
assertThat(fileReadFromParcel.getMimeType(), is(MIME_TYPE));
assertThat(fileReadFromParcel.getFileLength(), is(FILE_LENGTH));
assertThat(fileReadFromParcel.getCreationTimestamp(), is(CREATION_TIMESTAMP));
assertThat(fileReadFromParcel.getModificationTimestamp(), is(MODIFICATION_TIMESTAMP));
assertThat(
fileReadFromParcel.getModificationTimestampAtLastSyncForData(),
is(MODIFICATION_TIMESTAMP_AT_LAST_SYNC_FOR_DATA)
);
assertThat(fileReadFromParcel.getLastSyncDateForProperties(), is(LAST_SYNC_DATE_FOR_PROPERTIES));
assertThat(fileReadFromParcel.getLastSyncDateForData(), is(LAST_SYNC_DATE_FOR_DATA));
assertThat(fileReadFromParcel.getEtag(), is(ETAG));
assertThat(fileReadFromParcel.isSharedViaLink(), is(true));
assertThat(fileReadFromParcel.isSharedWithSharee(), is(true));
assertThat(fileReadFromParcel.getPermissions(), is(PERMISSIONS));
assertThat(fileReadFromParcel.getRemoteId(), is(REMOTE_ID));
assertThat(fileReadFromParcel.isUpdateThumbnailNeeded(), is(true));
assertThat(fileReadFromParcel.isDownloading(), is(true));
assertThat(fileReadFromParcel.getEtagInConflict(), is(ETAG_IN_CONFLICT));
}
}

View file

@ -0,0 +1,229 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2017 JARP <jarp@customer-187-174-218-184.uninet-ide.com.mx
* SPDX-FileCopyrightText: 2019 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2021 Chris Narkiewicz <hello@ezaquarii.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.datamodel;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.nextcloud.client.account.User;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.nextcloud.test.RandomStringGenerator;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.MainApp;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.db.UploadResult;
import com.owncloud.android.files.services.NameCollisionPolicy;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.operations.UploadFileOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Created by JARP on 6/7/17.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class UploadStorageManagerTest extends AbstractIT {
private UploadsStorageManager uploadsStorageManager;
private CurrentAccountProvider currentAccountProvider = () -> null;
private UserAccountManager userAccountManager;
private User user2;
@Before
public void setUp() {
Context instrumentationCtx = ApplicationProvider.getApplicationContext();
ContentResolver contentResolver = instrumentationCtx.getContentResolver();
uploadsStorageManager = new UploadsStorageManager(currentAccountProvider, contentResolver);
userAccountManager = UserAccountManagerImpl.fromContext(targetContext);
Account temp = new Account("test2@test.com", MainApp.getAccountType(targetContext));
if (!userAccountManager.exists(temp)) {
AccountManager platformAccountManager = AccountManager.get(targetContext);
platformAccountManager.addAccountExplicitly(temp, "testPassword", null);
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
Integer.toString(UserAccountManager.ACCOUNT_VERSION));
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_VERSION, "14.0.0.0");
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, "test.com");
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, "test"); // same as userId
}
final UserAccountManager userAccountManager = UserAccountManagerImpl.fromContext(targetContext);
user2 = userAccountManager.getUser("test2@test.com").orElseThrow(ActivityNotFoundException::new);
}
@Test
public void testDeleteAllUploads() {
// Clean
for (User user : userAccountManager.getAllUsers()) {
uploadsStorageManager.removeUserUploads(user);
}
int accountRowsA = 3;
int accountRowsB = 4;
insertUploads(account, accountRowsA);
insertUploads(user2.toPlatformAccount(), accountRowsB);
assertEquals("Expected 4 removed uploads files",
4,
uploadsStorageManager.removeUserUploads(user2));
}
@Test
public void largeTest() {
int size = 3000;
ArrayList<OCUpload> uploads = new ArrayList<>();
deleteAllUploads();
assertEquals(0, uploadsStorageManager.getAllStoredUploads().length);
for (int i = 0; i < size; i++) {
OCUpload upload = createUpload(account);
uploads.add(upload);
uploadsStorageManager.storeUpload(upload);
}
OCUpload[] storedUploads = uploadsStorageManager.getAllStoredUploads();
assertEquals(size, uploadsStorageManager.getAllStoredUploads().length);
for (int i = 0; i < size; i++) {
assertTrue(contains(uploads, storedUploads[i]));
}
}
@Test
public void testIsSame() {
OCUpload upload1 = new OCUpload("/test", "/test", account.name);
upload1.setUseWifiOnly(true);
OCUpload upload2 = new OCUpload("/test", "/test", account.name);
upload2.setUseWifiOnly(true);
assertTrue(upload1.isSame(upload2));
upload2.setUseWifiOnly(false);
assertFalse(upload1.isSame(upload2));
assertFalse(upload1.isSame(null));
assertFalse(upload1.isSame(new OCFile("/test")));
}
private boolean contains(ArrayList<OCUpload> uploads, OCUpload storedUpload) {
for (int i = 0; i < uploads.size(); i++) {
if (storedUpload.isSame(uploads.get(i))) {
return true;
}
}
return false;
}
@Test(expected = IllegalArgumentException.class)
public void corruptedUpload() {
OCUpload corruptUpload = new OCUpload(File.separator + "LocalPath",
OCFile.PATH_SEPARATOR + "RemotePath",
account.name);
corruptUpload.setLocalPath(null);
uploadsStorageManager.storeUpload(corruptUpload);
uploadsStorageManager.getAllStoredUploads();
}
@Test
public void getById() {
OCUpload upload = createUpload(account);
long id = uploadsStorageManager.storeUpload(upload);
OCUpload newUpload = uploadsStorageManager.getUploadById(id);
assertNotNull(newUpload);
assertEquals(upload.getLocalAction(), newUpload.getLocalAction());
assertEquals(upload.getFolderUnlockToken(), newUpload.getFolderUnlockToken());
}
@Test
public void getByIdNull() {
OCUpload newUpload = uploadsStorageManager.getUploadById(-1);
assertNull(newUpload);
}
private void insertUploads(Account account, int rowsToInsert) {
for (int i = 0; i < rowsToInsert; i++) {
uploadsStorageManager.storeUpload(createUpload(account));
}
}
public String generateUniqueNumber() {
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
private OCUpload createUpload(Account account) {
OCUpload upload = new OCUpload(File.separator + "very long long long long long long long long long long long " +
"long long long long long long long long long long long long long long " +
"long long long long long long long long long long long long long long " +
"long long long long long long long LocalPath " +
generateUniqueNumber(),
OCFile.PATH_SEPARATOR + "very long long long long long long long long long " +
"long long long long long long long long long long long long long long " +
"long long long long long long long long long long long long long long " +
"long long long long long long long long long long long long RemotePath " +
generateUniqueNumber(),
account.name);
upload.setFileSize(new Random().nextInt(20000) * 10000);
upload.setUploadStatus(UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS);
upload.setLocalAction(2);
upload.setNameCollisionPolicy(NameCollisionPolicy.ASK_USER);
upload.setCreateRemoteFolder(false);
upload.setUploadEndTimestamp(System.currentTimeMillis());
upload.setLastResult(UploadResult.DELAYED_FOR_WIFI);
upload.setCreatedBy(UploadFileOperation.CREATED_BY_USER);
upload.setUseWifiOnly(true);
upload.setWhileChargingOnly(false);
upload.setFolderUnlockToken(RandomStringGenerator.make(10));
return upload;
}
private void deleteAllUploads() {
uploadsStorageManager.removeAllUploads();
assertEquals(0, uploadsStorageManager.getAllStoredUploads().length);
}
@After
public void tearDown() {
deleteAllUploads();
userAccountManager.removeUser(user2);
}
}